blob: cd02eb3bb738aa62ecbcf8a19f20dcf32c1b3798 [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; \
Thomas Wouters477c8d52006-05-27 19:21:47 +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{
Thomas Wouters477c8d52006-05-27 19:21:47 +000069 if (size > PY_SSIZE_T_MAX) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000070 PyErr_NoMemory();
71 return NULL;
72 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000073 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000074}
75
Tim Peters64b5ce32001-09-10 20:52:51 +000076PyObject *
77_PyLong_Copy(PyLongObject *src)
78{
79 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +000080 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000081
82 assert(src != NULL);
83 i = src->ob_size;
84 if (i < 0)
85 i = -(i);
86 result = _PyLong_New(i);
87 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +000088 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +000089 while (--i >= 0)
90 result->ob_digit[i] = src->ob_digit[i];
91 }
92 return (PyObject *)result;
93}
94
Guido van Rossumedcc38a1991-05-05 20:09:44 +000095/* Create a new long int object from a C long int */
96
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000098PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000099{
Tim Petersce9de2f2001-06-14 04:56:19 +0000100 PyLongObject *v;
101 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
102 int ndigits = 0;
103 int negative = 0;
104
105 if (ival < 0) {
106 ival = -ival;
107 negative = 1;
108 }
109
110 /* Count the number of Python digits.
111 We used to pick 5 ("big enough for anything"), but that's a
112 waste of time and space given that 5*15 = 75 bits are rarely
113 needed. */
114 t = (unsigned long)ival;
115 while (t) {
116 ++ndigits;
117 t >>= SHIFT;
118 }
119 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000120 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000121 digit *p = v->ob_digit;
122 v->ob_size = negative ? -ndigits : ndigits;
123 t = (unsigned long)ival;
124 while (t) {
125 *p++ = (digit)(t & MASK);
Guido van Rossum472c04f1996-12-05 21:57:21 +0000126 t >>= SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000129 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000130}
131
Guido van Rossum53756b11997-01-03 17:14:46 +0000132/* Create a new long int object from a C unsigned long int */
133
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000135PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000136{
Tim Petersce9de2f2001-06-14 04:56:19 +0000137 PyLongObject *v;
138 unsigned long t;
139 int ndigits = 0;
140
141 /* Count the number of Python digits. */
142 t = (unsigned long)ival;
143 while (t) {
144 ++ndigits;
145 t >>= SHIFT;
146 }
147 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000148 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000149 digit *p = v->ob_digit;
150 v->ob_size = ndigits;
151 while (ival) {
152 *p++ = (digit)(ival & MASK);
153 ival >>= SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000154 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000155 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000157}
158
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000159/* Create a new long int object from a C double */
160
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000161PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000163{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000164 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000165 double frac;
166 int i, ndig, expo, neg;
167 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000168 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000169 PyErr_SetString(PyExc_OverflowError,
170 "cannot convert float infinity to long");
171 return NULL;
172 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000173 if (dval < 0.0) {
174 neg = 1;
175 dval = -dval;
176 }
177 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
178 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179 return PyLong_FromLong(0L);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000180 ndig = (expo-1) / SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000182 if (v == NULL)
183 return NULL;
184 frac = ldexp(frac, (expo-1) % SHIFT + 1);
185 for (i = ndig; --i >= 0; ) {
186 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000187 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000188 frac = frac - (double)bits;
189 frac = ldexp(frac, SHIFT);
190 }
191 if (neg)
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000192 v->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000193 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000194}
195
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000196/* Get a C long int from a long int object.
197 Returns -1 and sets an error condition if overflow occurs. */
198
199long
Tim Peters9f688bf2000-07-07 15:53:28 +0000200PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000201{
Guido van Rossumf7531811998-05-26 14:33:37 +0000202 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000203 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000204 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000205 Py_ssize_t i;
206 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000207
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000208 if (vv == NULL || !PyLong_Check(vv)) {
Guido van Rossum7e35d572001-09-15 03:14:32 +0000209 if (vv != NULL && PyInt_Check(vv))
210 return PyInt_AsLong(vv);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000212 return -1;
213 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000215 i = v->ob_size;
216 sign = 1;
217 x = 0;
218 if (i < 0) {
219 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000220 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000221 }
222 while (--i >= 0) {
223 prev = x;
224 x = (x << SHIFT) + v->ob_digit[i];
Guido van Rossumf7531811998-05-26 14:33:37 +0000225 if ((x >> SHIFT) != prev)
226 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000227 }
Guido van Rossumf7531811998-05-26 14:33:37 +0000228 /* Haven't lost any bits, but if the sign bit is set we're in
229 * trouble *unless* this is the min negative number. So,
230 * trouble iff sign bit set && (positive || some bit set other
231 * than the sign bit).
232 */
233 if ((long)x < 0 && (sign > 0 || (x << 1) != 0))
234 goto overflow;
235 return (long)x * sign;
236
237 overflow:
238 PyErr_SetString(PyExc_OverflowError,
Skip Montanarobafedec2001-09-13 19:05:30 +0000239 "long int too large to convert to int");
Guido van Rossumf7531811998-05-26 14:33:37 +0000240 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000241}
242
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000243static Py_ssize_t
244_long_as_ssize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000245 register PyLongObject *v;
246 size_t x, prev;
247 Py_ssize_t i;
248 int sign;
249
250 if (vv == NULL || !PyLong_Check(vv)) {
251 PyErr_BadInternalCall();
252 return -1;
253 }
254 v = (PyLongObject *)vv;
255 i = v->ob_size;
256 sign = 1;
257 x = 0;
258 if (i < 0) {
259 sign = -1;
260 i = -(i);
261 }
262 while (--i >= 0) {
263 prev = x;
264 x = (x << SHIFT) + v->ob_digit[i];
265 if ((x >> SHIFT) != prev)
266 goto overflow;
267 }
268 /* Haven't lost any bits, but if the sign bit is set we're in
269 * trouble *unless* this is the min negative number. So,
270 * trouble iff sign bit set && (positive || some bit set other
271 * than the sign bit).
272 */
273 if ((Py_ssize_t)x < 0 && (sign > 0 || (x << 1) != 0))
274 goto overflow;
275 return (Py_ssize_t)x * sign;
276
277 overflow:
278 PyErr_SetString(PyExc_OverflowError,
279 "long int too large to convert to int");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000280 if (sign > 0)
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000281 return PY_SSIZE_T_MAX;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000282 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000283 return PY_SSIZE_T_MIN;
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000284}
285
286/* Get a Py_ssize_t from a long int object.
287 Returns -1 and sets an error condition if overflow occurs. */
288
289Py_ssize_t
290_PyLong_AsSsize_t(PyObject *vv)
291{
292 Py_ssize_t x;
293
294 x = _long_as_ssize_t(vv);
295 if (PyErr_Occurred()) return -1;
296 return x;
297}
298
299
300/* Get a Py_ssize_t from a long int object.
301 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
302 and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000303 On error, return -1 with an exception set.
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000304*/
305
306static Py_ssize_t
307long_index(PyObject *vv)
308{
309 Py_ssize_t x;
310
311 x = _long_as_ssize_t(vv);
312 if (PyErr_Occurred()) {
313 /* If overflow error, ignore the error */
314 if (x != -1) {
315 PyErr_Clear();
316 }
317 }
318 return x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000319}
320
Guido van Rossumd8c80482002-08-13 00:24:58 +0000321/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000322 Returns -1 and sets an error condition if overflow occurs. */
323
324unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000325PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000326{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000328 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000329 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000330
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000331 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000332 if (vv != NULL && PyInt_Check(vv)) {
333 long val = PyInt_AsLong(vv);
334 if (val < 0) {
335 PyErr_SetString(PyExc_OverflowError,
336 "can't convert negative value to unsigned long");
337 return (unsigned long) -1;
338 }
339 return val;
340 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000342 return (unsigned long) -1;
343 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000344 v = (PyLongObject *)vv;
Guido van Rossum53756b11997-01-03 17:14:46 +0000345 i = v->ob_size;
346 x = 0;
347 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000348 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000349 "can't convert negative value to unsigned long");
350 return (unsigned long) -1;
351 }
352 while (--i >= 0) {
353 prev = x;
354 x = (x << SHIFT) + v->ob_digit[i];
355 if ((x >> SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000356 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000357 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000358 return (unsigned long) -1;
359 }
360 }
361 return x;
362}
363
Thomas Hellera4ea6032003-04-17 18:55:45 +0000364/* Get a C unsigned long int from a long int object, ignoring the high bits.
365 Returns -1 and sets an error condition if an error occurs. */
366
367unsigned long
368PyLong_AsUnsignedLongMask(PyObject *vv)
369{
370 register PyLongObject *v;
371 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000372 Py_ssize_t i;
373 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000374
375 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000376 if (vv != NULL && PyInt_Check(vv))
377 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000378 PyErr_BadInternalCall();
379 return (unsigned long) -1;
380 }
381 v = (PyLongObject *)vv;
382 i = v->ob_size;
383 sign = 1;
384 x = 0;
385 if (i < 0) {
386 sign = -1;
387 i = -i;
388 }
389 while (--i >= 0) {
390 x = (x << SHIFT) + v->ob_digit[i];
391 }
392 return x * sign;
393}
394
Tim Peters5b8132f2003-01-31 15:52:05 +0000395int
396_PyLong_Sign(PyObject *vv)
397{
398 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000399
400 assert(v != NULL);
401 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000402
Tim Petersee1a53c2003-02-02 02:57:53 +0000403 return v->ob_size == 0 ? 0 : (v->ob_size < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000404}
405
Tim Petersbaefd9e2003-01-28 20:37:45 +0000406size_t
407_PyLong_NumBits(PyObject *vv)
408{
409 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000410 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000411 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000412
413 assert(v != NULL);
414 assert(PyLong_Check(v));
Guido van Rossum004a65c2003-02-03 15:28:19 +0000415 ndigits = ABS(v->ob_size);
Tim Petersbaefd9e2003-01-28 20:37:45 +0000416 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
417 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000418 digit msd = v->ob_digit[ndigits - 1];
419
Tim Peters5b8132f2003-01-31 15:52:05 +0000420 result = (ndigits - 1) * SHIFT;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000421 if (result / SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000422 goto Overflow;
423 do {
424 ++result;
425 if (result == 0)
426 goto Overflow;
427 msd >>= 1;
428 } while (msd);
429 }
430 return result;
431
432Overflow:
433 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
434 "to express in a platform size_t");
435 return (size_t)-1;
436}
437
Tim Peters2a9b3672001-06-11 21:23:58 +0000438PyObject *
439_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
440 int little_endian, int is_signed)
441{
442 const unsigned char* pstartbyte;/* LSB of bytes */
443 int incr; /* direction to move pstartbyte */
444 const unsigned char* pendbyte; /* MSB of bytes */
445 size_t numsignificantbytes; /* number of bytes that matter */
446 size_t ndigits; /* number of Python long digits */
447 PyLongObject* v; /* result */
448 int idigit = 0; /* next free index in v->ob_digit */
449
450 if (n == 0)
451 return PyLong_FromLong(0L);
452
453 if (little_endian) {
454 pstartbyte = bytes;
455 pendbyte = bytes + n - 1;
456 incr = 1;
457 }
458 else {
459 pstartbyte = bytes + n - 1;
460 pendbyte = bytes;
461 incr = -1;
462 }
463
464 if (is_signed)
465 is_signed = *pendbyte >= 0x80;
466
467 /* Compute numsignificantbytes. This consists of finding the most
468 significant byte. Leading 0 bytes are insignficant if the number
469 is positive, and leading 0xff bytes if negative. */
470 {
471 size_t i;
472 const unsigned char* p = pendbyte;
473 const int pincr = -incr; /* search MSB to LSB */
474 const unsigned char insignficant = is_signed ? 0xff : 0x00;
475
476 for (i = 0; i < n; ++i, p += pincr) {
477 if (*p != insignficant)
478 break;
479 }
480 numsignificantbytes = n - i;
481 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
482 actually has 2 significant bytes. OTOH, 0xff0001 ==
483 -0x00ffff, so we wouldn't *need* to bump it there; but we
484 do for 0xffff = -0x0001. To be safe without bothering to
485 check every case, bump it regardless. */
486 if (is_signed && numsignificantbytes < n)
487 ++numsignificantbytes;
488 }
489
490 /* How many Python long digits do we need? We have
491 8*numsignificantbytes bits, and each Python long digit has SHIFT
492 bits, so it's the ceiling of the quotient. */
493 ndigits = (numsignificantbytes * 8 + SHIFT - 1) / SHIFT;
494 if (ndigits > (size_t)INT_MAX)
495 return PyErr_NoMemory();
496 v = _PyLong_New((int)ndigits);
497 if (v == NULL)
498 return NULL;
499
500 /* Copy the bits over. The tricky parts are computing 2's-comp on
501 the fly for signed numbers, and dealing with the mismatch between
502 8-bit bytes and (probably) 15-bit Python digits.*/
503 {
504 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000505 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000506 twodigits accum = 0; /* sliding register */
507 unsigned int accumbits = 0; /* number of bits in accum */
508 const unsigned char* p = pstartbyte;
509
510 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000511 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000512 /* Compute correction for 2's comp, if needed. */
513 if (is_signed) {
514 thisbyte = (0xff ^ thisbyte) + carry;
515 carry = thisbyte >> 8;
516 thisbyte &= 0xff;
517 }
518 /* Because we're going LSB to MSB, thisbyte is
519 more significant than what's already in accum,
520 so needs to be prepended to accum. */
521 accum |= thisbyte << accumbits;
522 accumbits += 8;
523 if (accumbits >= SHIFT) {
524 /* There's enough to fill a Python digit. */
525 assert(idigit < (int)ndigits);
526 v->ob_digit[idigit] = (digit)(accum & MASK);
527 ++idigit;
528 accum >>= SHIFT;
529 accumbits -= SHIFT;
530 assert(accumbits < SHIFT);
531 }
532 }
533 assert(accumbits < SHIFT);
534 if (accumbits) {
535 assert(idigit < (int)ndigits);
536 v->ob_digit[idigit] = (digit)accum;
537 ++idigit;
538 }
539 }
540
541 v->ob_size = is_signed ? -idigit : idigit;
542 return (PyObject *)long_normalize(v);
543}
544
545int
546_PyLong_AsByteArray(PyLongObject* v,
547 unsigned char* bytes, size_t n,
548 int little_endian, int is_signed)
549{
550 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000551 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000552 twodigits accum; /* sliding register */
553 unsigned int accumbits; /* # bits in accum */
554 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
555 twodigits carry; /* for computing 2's-comp */
556 size_t j; /* # bytes filled */
557 unsigned char* p; /* pointer to next byte in bytes */
558 int pincr; /* direction to move p */
559
560 assert(v != NULL && PyLong_Check(v));
561
562 if (v->ob_size < 0) {
563 ndigits = -(v->ob_size);
564 if (!is_signed) {
565 PyErr_SetString(PyExc_TypeError,
566 "can't convert negative long to unsigned");
567 return -1;
568 }
569 do_twos_comp = 1;
570 }
571 else {
572 ndigits = v->ob_size;
573 do_twos_comp = 0;
574 }
575
576 if (little_endian) {
577 p = bytes;
578 pincr = 1;
579 }
580 else {
581 p = bytes + n - 1;
582 pincr = -1;
583 }
584
Tim Peters898cf852001-06-13 20:50:08 +0000585 /* Copy over all the Python digits.
586 It's crucial that every Python digit except for the MSD contribute
587 exactly SHIFT bits to the total, so first assert that the long is
588 normalized. */
589 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000590 j = 0;
591 accum = 0;
592 accumbits = 0;
593 carry = do_twos_comp ? 1 : 0;
594 for (i = 0; i < ndigits; ++i) {
595 twodigits thisdigit = v->ob_digit[i];
596 if (do_twos_comp) {
597 thisdigit = (thisdigit ^ MASK) + carry;
598 carry = thisdigit >> SHIFT;
599 thisdigit &= MASK;
600 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000601 /* Because we're going LSB to MSB, thisdigit is more
602 significant than what's already in accum, so needs to be
603 prepended to accum. */
604 accum |= thisdigit << accumbits;
Tim Petersede05092001-06-14 08:53:38 +0000605 accumbits += SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000606
Tim Petersede05092001-06-14 08:53:38 +0000607 /* The most-significant digit may be (probably is) at least
608 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000609 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000610 /* Count # of sign bits -- they needn't be stored,
611 * although for signed conversion we need later to
612 * make sure at least one sign bit gets stored.
613 * First shift conceptual sign bit to real sign bit.
614 */
615 stwodigits s = (stwodigits)(thisdigit <<
616 (8*sizeof(stwodigits) - SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000617 unsigned int nsignbits = 0;
Tim Petersede05092001-06-14 08:53:38 +0000618 while ((s < 0) == do_twos_comp && nsignbits < SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000619 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000620 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000621 }
Tim Petersede05092001-06-14 08:53:38 +0000622 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000623 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000624
Tim Peters2a9b3672001-06-11 21:23:58 +0000625 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000626 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000627 if (j >= n)
628 goto Overflow;
629 ++j;
630 *p = (unsigned char)(accum & 0xff);
631 p += pincr;
632 accumbits -= 8;
633 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000634 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000635 }
636
637 /* Store the straggler (if any). */
638 assert(accumbits < 8);
639 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000640 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000641 if (j >= n)
642 goto Overflow;
643 ++j;
644 if (do_twos_comp) {
645 /* Fill leading bits of the byte with sign bits
646 (appropriately pretending that the long had an
647 infinite supply of sign bits). */
648 accum |= (~(twodigits)0) << accumbits;
649 }
650 *p = (unsigned char)(accum & 0xff);
651 p += pincr;
652 }
Tim Peters05607ad2001-06-13 21:01:27 +0000653 else if (j == n && n > 0 && is_signed) {
654 /* The main loop filled the byte array exactly, so the code
655 just above didn't get to ensure there's a sign bit, and the
656 loop below wouldn't add one either. Make sure a sign bit
657 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000658 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000659 int sign_bit_set = msb >= 0x80;
660 assert(accumbits == 0);
661 if (sign_bit_set == do_twos_comp)
662 return 0;
663 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000664 goto Overflow;
665 }
Tim Peters05607ad2001-06-13 21:01:27 +0000666
667 /* Fill remaining bytes with copies of the sign bit. */
668 {
669 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
670 for ( ; j < n; ++j, p += pincr)
671 *p = signbyte;
672 }
673
Tim Peters2a9b3672001-06-11 21:23:58 +0000674 return 0;
675
676Overflow:
677 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
678 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000679
Tim Peters2a9b3672001-06-11 21:23:58 +0000680}
681
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000682double
683_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
684{
685/* NBITS_WANTED should be > the number of bits in a double's precision,
686 but small enough so that 2**NBITS_WANTED is within the normal double
687 range. nbitsneeded is set to 1 less than that because the most-significant
688 Python digit contains at least 1 significant bit, but we don't want to
689 bother counting them (catering to the worst case cheaply).
690
691 57 is one more than VAX-D double precision; I (Tim) don't know of a double
692 format with more precision than that; it's 1 larger so that we add in at
693 least one round bit to stand in for the ignored least-significant bits.
694*/
695#define NBITS_WANTED 57
696 PyLongObject *v;
697 double x;
698 const double multiplier = (double)(1L << SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000699 Py_ssize_t i;
700 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000701 int nbitsneeded;
702
703 if (vv == NULL || !PyLong_Check(vv)) {
704 PyErr_BadInternalCall();
705 return -1;
706 }
707 v = (PyLongObject *)vv;
708 i = v->ob_size;
709 sign = 1;
710 if (i < 0) {
711 sign = -1;
712 i = -(i);
713 }
714 else if (i == 0) {
715 *exponent = 0;
716 return 0.0;
717 }
718 --i;
719 x = (double)v->ob_digit[i];
720 nbitsneeded = NBITS_WANTED - 1;
721 /* Invariant: i Python digits remain unaccounted for. */
722 while (i > 0 && nbitsneeded > 0) {
723 --i;
724 x = x * multiplier + (double)v->ob_digit[i];
725 nbitsneeded -= SHIFT;
726 }
727 /* There are i digits we didn't shift in. Pretending they're all
728 zeroes, the true value is x * 2**(i*SHIFT). */
729 *exponent = i;
730 assert(x > 0.0);
731 return x * sign;
732#undef NBITS_WANTED
733}
734
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000735/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000736
737double
Tim Peters9f688bf2000-07-07 15:53:28 +0000738PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000739{
Thomas Wouters553489a2006-02-01 21:32:04 +0000740 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000741 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000742
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000743 if (vv == NULL || !PyLong_Check(vv)) {
744 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000745 return -1;
746 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000747 x = _PyLong_AsScaledDouble(vv, &e);
748 if (x == -1.0 && PyErr_Occurred())
749 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000750 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
751 set correctly after a successful _PyLong_AsScaledDouble() call */
752 assert(e >= 0);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000753 if (e > INT_MAX / SHIFT)
754 goto overflow;
755 errno = 0;
756 x = ldexp(x, e * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000757 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000758 goto overflow;
759 return x;
760
761overflow:
762 PyErr_SetString(PyExc_OverflowError,
763 "long int too large to convert to float");
764 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000765}
766
Guido van Rossum78694d91998-09-18 14:14:13 +0000767/* Create a new long (or int) object from a C pointer */
768
769PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000770PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000771{
Tim Peters70128a12001-06-16 08:48:40 +0000772#if SIZEOF_VOID_P <= SIZEOF_LONG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000773 if ((long)p < 0)
774 return PyLong_FromUnsignedLong((unsigned long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000775 return PyInt_FromLong((long)p);
776#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000777
Tim Peters70128a12001-06-16 08:48:40 +0000778#ifndef HAVE_LONG_LONG
779# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
780#endif
781#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000782# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000783#endif
784 /* optimize null pointers */
785 if (p == NULL)
786 return PyInt_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000787 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000788
789#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000790}
791
792/* Get a C pointer from a long object (or an int object in some cases) */
793
794void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000795PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000796{
797 /* This function will allow int or long objects. If vv is neither,
798 then the PyLong_AsLong*() functions will raise the exception:
799 PyExc_SystemError, "bad argument to internal function"
800 */
Tim Peters70128a12001-06-16 08:48:40 +0000801#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000802 long x;
803
Tim Peters70128a12001-06-16 08:48:40 +0000804 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000805 x = PyInt_AS_LONG(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000806 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000807 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000808 else
809 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000810#else
Tim Peters70128a12001-06-16 08:48:40 +0000811
812#ifndef HAVE_LONG_LONG
813# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
814#endif
815#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000816# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000817#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000818 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000819
Tim Peters70128a12001-06-16 08:48:40 +0000820 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000821 x = PyInt_AS_LONG(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000822 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000823 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000824 else
825 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000826
827#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000828
829 if (x == -1 && PyErr_Occurred())
830 return NULL;
831 return (void *)x;
832}
833
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000834#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000835
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000836/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000837 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000838 */
839
Tim Peterscf37dfc2001-06-14 18:42:50 +0000840#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000841
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000842/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000843
844PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000845PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000846{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000847 PyLongObject *v;
848 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
849 int ndigits = 0;
850 int negative = 0;
851
852 if (ival < 0) {
853 ival = -ival;
854 negative = 1;
855 }
856
857 /* Count the number of Python digits.
858 We used to pick 5 ("big enough for anything"), but that's a
859 waste of time and space given that 5*15 = 75 bits are rarely
860 needed. */
861 t = (unsigned PY_LONG_LONG)ival;
862 while (t) {
863 ++ndigits;
864 t >>= SHIFT;
865 }
866 v = _PyLong_New(ndigits);
867 if (v != NULL) {
868 digit *p = v->ob_digit;
869 v->ob_size = negative ? -ndigits : ndigits;
870 t = (unsigned PY_LONG_LONG)ival;
871 while (t) {
872 *p++ = (digit)(t & MASK);
873 t >>= SHIFT;
874 }
875 }
876 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000877}
878
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000879/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000880
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000881PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000882PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000883{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000884 PyLongObject *v;
885 unsigned PY_LONG_LONG t;
886 int ndigits = 0;
887
888 /* Count the number of Python digits. */
889 t = (unsigned PY_LONG_LONG)ival;
890 while (t) {
891 ++ndigits;
892 t >>= SHIFT;
893 }
894 v = _PyLong_New(ndigits);
895 if (v != NULL) {
896 digit *p = v->ob_digit;
897 v->ob_size = ndigits;
898 while (ival) {
899 *p++ = (digit)(ival & MASK);
900 ival >>= SHIFT;
901 }
902 }
903 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000904}
905
Martin v. Löwis18e16552006-02-15 17:27:45 +0000906/* Create a new long int object from a C Py_ssize_t. */
907
908PyObject *
909_PyLong_FromSsize_t(Py_ssize_t ival)
910{
911 Py_ssize_t bytes = ival;
912 int one = 1;
913 return _PyLong_FromByteArray(
914 (unsigned char *)&bytes,
915 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
916}
917
918/* Create a new long int object from a C size_t. */
919
920PyObject *
921_PyLong_FromSize_t(size_t ival)
922{
923 size_t bytes = ival;
924 int one = 1;
925 return _PyLong_FromByteArray(
926 (unsigned char *)&bytes,
927 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
928}
929
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000930/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000931 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000932
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000933PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000934PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000935{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000936 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000937 int one = 1;
938 int res;
939
Tim Petersd38b1c72001-09-30 05:09:37 +0000940 if (vv == NULL) {
941 PyErr_BadInternalCall();
942 return -1;
943 }
944 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000945 PyNumberMethods *nb;
946 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000947 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000948 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000949 if ((nb = vv->ob_type->tp_as_number) == NULL ||
950 nb->nb_int == NULL) {
951 PyErr_SetString(PyExc_TypeError, "an integer is required");
952 return -1;
953 }
954 io = (*nb->nb_int) (vv);
955 if (io == NULL)
956 return -1;
957 if (PyInt_Check(io)) {
958 bytes = PyInt_AsLong(io);
959 Py_DECREF(io);
960 return bytes;
961 }
962 if (PyLong_Check(io)) {
963 bytes = PyLong_AsLongLong(io);
964 Py_DECREF(io);
965 return bytes;
966 }
967 Py_DECREF(io);
968 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000969 return -1;
970 }
971
Tim Petersd1a7da62001-06-13 00:35:57 +0000972 res = _PyLong_AsByteArray(
973 (PyLongObject *)vv, (unsigned char *)&bytes,
974 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000975
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000976 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000977 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000978 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000979 else
980 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000981}
982
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000983/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000984 Return -1 and set an error if overflow occurs. */
985
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000986unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000987PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000988{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000989 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000990 int one = 1;
991 int res;
992
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000993 if (vv == NULL || !PyLong_Check(vv)) {
994 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000995 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000996 }
997
Tim Petersd1a7da62001-06-13 00:35:57 +0000998 res = _PyLong_AsByteArray(
999 (PyLongObject *)vv, (unsigned char *)&bytes,
1000 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001001
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001002 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001003 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001004 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001005 else
1006 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001007}
Tim Petersd1a7da62001-06-13 00:35:57 +00001008
Thomas Hellera4ea6032003-04-17 18:55:45 +00001009/* Get a C unsigned long int from a long int object, ignoring the high bits.
1010 Returns -1 and sets an error condition if an error occurs. */
1011
1012unsigned PY_LONG_LONG
1013PyLong_AsUnsignedLongLongMask(PyObject *vv)
1014{
1015 register PyLongObject *v;
1016 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001017 Py_ssize_t i;
1018 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001019
1020 if (vv == NULL || !PyLong_Check(vv)) {
1021 PyErr_BadInternalCall();
1022 return (unsigned long) -1;
1023 }
1024 v = (PyLongObject *)vv;
1025 i = v->ob_size;
1026 sign = 1;
1027 x = 0;
1028 if (i < 0) {
1029 sign = -1;
1030 i = -i;
1031 }
1032 while (--i >= 0) {
1033 x = (x << SHIFT) + v->ob_digit[i];
1034 }
1035 return x * sign;
1036}
Tim Petersd1a7da62001-06-13 00:35:57 +00001037#undef IS_LITTLE_ENDIAN
1038
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001039#endif /* HAVE_LONG_LONG */
1040
Neil Schemenauerba872e22001-01-04 01:46:03 +00001041
1042static int
1043convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001044 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001045 *a = (PyLongObject *) v;
1046 Py_INCREF(v);
1047 }
1048 else if (PyInt_Check(v)) {
1049 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1050 }
1051 else {
1052 return 0;
1053 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001054 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001055 *b = (PyLongObject *) w;
1056 Py_INCREF(w);
1057 }
1058 else if (PyInt_Check(w)) {
1059 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1060 }
1061 else {
1062 Py_DECREF(*a);
1063 return 0;
1064 }
1065 return 1;
1066}
1067
1068#define CONVERT_BINOP(v, w, a, b) \
1069 if (!convert_binop(v, w, a, b)) { \
1070 Py_INCREF(Py_NotImplemented); \
1071 return Py_NotImplemented; \
1072 }
1073
Tim Peters877a2122002-08-12 05:09:36 +00001074/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1075 * is modified in place, by adding y to it. Carries are propagated as far as
1076 * x[m-1], and the remaining carry (0 or 1) is returned.
1077 */
1078static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001079v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001080{
1081 int i;
1082 digit carry = 0;
1083
1084 assert(m >= n);
1085 for (i = 0; i < n; ++i) {
1086 carry += x[i] + y[i];
1087 x[i] = carry & MASK;
1088 carry >>= SHIFT;
1089 assert((carry & 1) == carry);
1090 }
1091 for (; carry && i < m; ++i) {
1092 carry += x[i];
1093 x[i] = carry & MASK;
1094 carry >>= SHIFT;
1095 assert((carry & 1) == carry);
1096 }
1097 return carry;
1098}
1099
1100/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1101 * is modified in place, by subtracting y from it. Borrows are propagated as
1102 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1103 */
1104static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001105v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001106{
1107 int i;
1108 digit borrow = 0;
1109
1110 assert(m >= n);
1111 for (i = 0; i < n; ++i) {
1112 borrow = x[i] - y[i] - borrow;
1113 x[i] = borrow & MASK;
1114 borrow >>= SHIFT;
1115 borrow &= 1; /* keep only 1 sign bit */
1116 }
1117 for (; borrow && i < m; ++i) {
1118 borrow = x[i] - borrow;
1119 x[i] = borrow & MASK;
1120 borrow >>= SHIFT;
1121 borrow &= 1;
1122 }
1123 return borrow;
1124}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001125
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001126/* Multiply by a single digit, ignoring the sign. */
1127
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001128static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001129mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001130{
1131 return muladd1(a, n, (digit)0);
1132}
1133
1134/* Multiply by a single digit and add a single digit, ignoring the sign. */
1135
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001136static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001137muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001138{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001139 Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001140 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001141 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001142 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001143
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001144 if (z == NULL)
1145 return NULL;
1146 for (i = 0; i < size_a; ++i) {
1147 carry += (twodigits)a->ob_digit[i] * n;
Guido van Rossum2095d241997-04-09 19:41:24 +00001148 z->ob_digit[i] = (digit) (carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001149 carry >>= SHIFT;
1150 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001151 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001152 return long_normalize(z);
1153}
1154
Tim Peters212e6142001-07-14 12:23:19 +00001155/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1156 in pout, and returning the remainder. pin and pout point at the LSD.
1157 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1158 long_format, but that should be done with great care since longs are
1159 immutable. */
1160
1161static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001162inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001163{
1164 twodigits rem = 0;
1165
1166 assert(n > 0 && n <= MASK);
1167 pin += size;
1168 pout += size;
1169 while (--size >= 0) {
1170 digit hi;
1171 rem = (rem << SHIFT) + *--pin;
1172 *--pout = hi = (digit)(rem / n);
1173 rem -= hi * n;
1174 }
1175 return (digit)rem;
1176}
1177
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001178/* Divide a long integer by a digit, returning both the quotient
1179 (as function result) and the remainder (through *prem).
1180 The sign of a is ignored; n should not be zero. */
1181
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001182static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001183divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001184{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001185 const Py_ssize_t size = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001186 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001187
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001188 assert(n > 0 && n <= MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001189 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001190 if (z == NULL)
1191 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001192 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001193 return long_normalize(z);
1194}
1195
1196/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001197 Return a string object.
Fred Drake121ee271999-12-23 15:41:28 +00001198 If base is 8 or 16, add the proper prefix '0' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001199
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001200static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001201long_format(PyObject *aa, int base, int addL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001202{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001203 register PyLongObject *a = (PyLongObject *)aa;
1204 PyStringObject *str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001205 Py_ssize_t i;
1206 const Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001207 char *p;
1208 int bits;
1209 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001210
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001211 if (a == NULL || !PyLong_Check(a)) {
1212 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001213 return NULL;
1214 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001215 assert(base >= 2 && base <= 36);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001216
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001217 /* Compute a rough upper bound for the length of the string */
1218 i = base;
1219 bits = 0;
1220 while (i > 1) {
1221 ++bits;
1222 i >>= 1;
1223 }
Fred Drake121ee271999-12-23 15:41:28 +00001224 i = 5 + (addL ? 1 : 0) + (size_a*SHIFT + bits-1) / bits;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001225 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001226 if (str == NULL)
1227 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001228 p = PyString_AS_STRING(str) + i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001229 *p = '\0';
Fred Drake121ee271999-12-23 15:41:28 +00001230 if (addL)
1231 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001232 if (a->ob_size < 0)
1233 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001234
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001235 if (a->ob_size == 0) {
1236 *--p = '0';
1237 }
1238 else if ((base & (base - 1)) == 0) {
1239 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001240 twodigits accum = 0;
1241 int accumbits = 0; /* # of bits in accum */
1242 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001243 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001244 while ((i >>= 1) > 1)
1245 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001246
1247 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001248 accum |= (twodigits)a->ob_digit[i] << accumbits;
Tim Peters586b2e32001-07-15 09:11:14 +00001249 accumbits += SHIFT;
1250 assert(accumbits >= basebits);
1251 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001252 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001253 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001254 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001255 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001256 accumbits -= basebits;
1257 accum >>= basebits;
1258 } while (i < size_a-1 ? accumbits >= basebits :
1259 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001260 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001261 }
1262 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001263 /* Not 0, and base not a power of 2. Divide repeatedly by
1264 base, but for speed use the highest power of base that
1265 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001266 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001267 digit *pin = a->ob_digit;
1268 PyLongObject *scratch;
1269 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001270 digit powbase = base; /* powbase == base ** power */
1271 int power = 1;
1272 for (;;) {
1273 unsigned long newpow = powbase * (unsigned long)base;
1274 if (newpow >> SHIFT) /* doesn't fit in a digit */
1275 break;
1276 powbase = (digit)newpow;
1277 ++power;
1278 }
Tim Peters212e6142001-07-14 12:23:19 +00001279
1280 /* Get a scratch area for repeated division. */
1281 scratch = _PyLong_New(size);
1282 if (scratch == NULL) {
1283 Py_DECREF(str);
1284 return NULL;
1285 }
1286
1287 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001288 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001289 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001290 digit rem = inplace_divrem1(scratch->ob_digit,
1291 pin, size, powbase);
1292 pin = scratch->ob_digit; /* no need to use a again */
1293 if (pin[size - 1] == 0)
1294 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001295 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001296 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001297 Py_DECREF(str);
1298 return NULL;
1299 })
Tim Peters212e6142001-07-14 12:23:19 +00001300
1301 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001302 assert(ntostore > 0);
1303 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001304 digit nextrem = (digit)(rem / base);
1305 char c = (char)(rem - nextrem * base);
1306 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001307 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001308 *--p = c;
1309 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001310 --ntostore;
1311 /* Termination is a bit delicate: must not
1312 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001313 remaining quotient and rem are both 0. */
1314 } while (ntostore && (size || rem));
1315 } while (size != 0);
1316 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001317 }
1318
Guido van Rossum2c475421992-08-14 15:13:07 +00001319 if (base == 8) {
1320 if (size_a != 0)
1321 *--p = '0';
1322 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001323 else if (base == 16) {
1324 *--p = 'x';
1325 *--p = '0';
1326 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001327 else if (base != 10) {
1328 *--p = '#';
1329 *--p = '0' + base%10;
1330 if (base > 10)
1331 *--p = '0' + base/10;
1332 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001333 if (sign)
1334 *--p = sign;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001335 if (p != PyString_AS_STRING(str)) {
1336 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001337 assert(p > q);
1338 do {
1339 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001340 q--;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001341 _PyString_Resize((PyObject **)&str,
1342 (int) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001343 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001344 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001345}
1346
Thomas Wouters477c8d52006-05-27 19:21:47 +00001347/* Table of digit values for 8-bit string -> integer conversion.
1348 * '0' maps to 0, ..., '9' maps to 9.
1349 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1350 * All other indices map to 37.
1351 * Note that when converting a base B string, a char c is a legitimate
1352 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1353 */
1354int _PyLong_DigitValue[256] = {
1355 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1356 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1357 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1358 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1359 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1360 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1361 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1362 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1363 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1364 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1365 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1366 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1367 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1368 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1369 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1370 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1371};
1372
1373/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001374 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1375 * non-digit (which may be *str!). A normalized long is returned.
1376 * The point to this routine is that it takes time linear in the number of
1377 * string characters.
1378 */
1379static PyLongObject *
1380long_from_binary_base(char **str, int base)
1381{
1382 char *p = *str;
1383 char *start = p;
1384 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001385 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001386 PyLongObject *z;
1387 twodigits accum;
1388 int bits_in_accum;
1389 digit *pdigit;
1390
1391 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1392 n = base;
1393 for (bits_per_char = -1; n; ++bits_per_char)
1394 n >>= 1;
1395 /* n <- total # of bits needed, while setting p to end-of-string */
1396 n = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001397 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001398 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001399 *str = p;
Tim Peters1a3b19a2003-02-02 17:33:53 +00001400 n = (p - start) * bits_per_char;
1401 if (n / bits_per_char != p - start) {
1402 PyErr_SetString(PyExc_ValueError,
1403 "long string too large to convert");
1404 return NULL;
1405 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001406 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1407 n = (n + SHIFT - 1) / SHIFT;
1408 z = _PyLong_New(n);
1409 if (z == NULL)
1410 return NULL;
1411 /* Read string from right, and fill in long from left; i.e.,
1412 * from least to most significant in both.
1413 */
1414 accum = 0;
1415 bits_in_accum = 0;
1416 pdigit = z->ob_digit;
1417 while (--p >= start) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001418 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001419 assert(k >= 0 && k < base);
1420 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001421 bits_in_accum += bits_per_char;
1422 if (bits_in_accum >= SHIFT) {
1423 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001424 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001425 accum >>= SHIFT;
1426 bits_in_accum -= SHIFT;
1427 assert(bits_in_accum < SHIFT);
1428 }
1429 }
1430 if (bits_in_accum) {
1431 assert(bits_in_accum <= SHIFT);
1432 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001433 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001434 }
1435 while (pdigit - z->ob_digit < n)
1436 *pdigit++ = 0;
1437 return long_normalize(z);
1438}
1439
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001440PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001441PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001442{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001443 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001444 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001445 PyLongObject *z;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001446 PyObject *strobj, *strrepr;
1447 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001448
Guido van Rossum472c04f1996-12-05 21:57:21 +00001449 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001450 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001451 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001452 return NULL;
1453 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001454 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001455 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001456 if (*str == '+')
1457 ++str;
1458 else if (*str == '-') {
1459 ++str;
1460 sign = -1;
1461 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001462 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001463 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001464 if (base == 0) {
1465 if (str[0] != '0')
1466 base = 10;
1467 else if (str[1] == 'x' || str[1] == 'X')
1468 base = 16;
1469 else
1470 base = 8;
1471 }
1472 if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
1473 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001474
Guido van Rossume6762971998-06-22 03:54:46 +00001475 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001476 if ((base & (base - 1)) == 0)
1477 z = long_from_binary_base(&str, base);
1478 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001479/***
1480Binary bases can be converted in time linear in the number of digits, because
1481Python's representation base is binary. Other bases (including decimal!) use
1482the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001483
Thomas Wouters477c8d52006-05-27 19:21:47 +00001484First some math: the largest integer that can be expressed in N base-B digits
1485is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1486case number of Python digits needed to hold it is the smallest integer n s.t.
1487
1488 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1489 BASE**n >= B**N [taking logs to base BASE]
1490 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1491
1492The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1493this quickly. A Python long with that much space is reserved near the start,
1494and the result is computed into it.
1495
1496The input string is actually treated as being in base base**i (i.e., i digits
1497are processed at a time), where two more static arrays hold:
1498
1499 convwidth_base[base] = the largest integer i such that base**i <= BASE
1500 convmultmax_base[base] = base ** convwidth_base[base]
1501
1502The first of these is the largest i such that i consecutive input digits
1503must fit in a single Python digit. The second is effectively the input
1504base we're really using.
1505
1506Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1507convmultmax_base[base], the result is "simply"
1508
1509 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1510
1511where B = convmultmax_base[base].
1512***/
1513 register twodigits c; /* current input character */
1514 Py_ssize_t size_z;
1515 int i;
1516 int convwidth;
1517 twodigits convmultmax, convmult;
1518 digit *pz, *pzstop;
1519 char* scan;
1520
1521 static double log_base_BASE[37] = {0.0e0,};
1522 static int convwidth_base[37] = {0,};
1523 static twodigits convmultmax_base[37] = {0,};
1524
1525 if (log_base_BASE[base] == 0.0) {
1526 twodigits convmax = base;
1527 int i = 1;
1528
1529 log_base_BASE[base] = log((double)base) /
1530 log((double)BASE);
1531 for (;;) {
1532 twodigits next = convmax * base;
1533 if (next > BASE)
1534 break;
1535 convmax = next;
1536 ++i;
1537 }
1538 convmultmax_base[base] = convmax;
1539 assert(i > 0);
1540 convwidth_base[base] = i;
1541 }
1542
1543 /* Find length of the string of numeric characters. */
1544 scan = str;
1545 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1546 ++scan;
1547
1548 /* Create a long object that can contain the largest possible
1549 * integer with this base and length. Note that there's no
1550 * need to initialize z->ob_digit -- no slot is read up before
1551 * being stored into.
1552 */
1553 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1554 assert(size_z > 0);
1555 z = _PyLong_New(size_z);
1556 if (z == NULL)
1557 return NULL;
1558 z->ob_size = 0;
1559
1560 /* `convwidth` consecutive input digits are treated as a single
1561 * digit in base `convmultmax`.
1562 */
1563 convwidth = convwidth_base[base];
1564 convmultmax = convmultmax_base[base];
1565
1566 /* Work ;-) */
1567 while (str < scan) {
1568 /* grab up to convwidth digits from the input string */
1569 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1570 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1571 c = (twodigits)(c * base +
1572 _PyLong_DigitValue[Py_CHARMASK(*str)]);
1573 assert(c < BASE);
1574 }
1575
1576 convmult = convmultmax;
1577 /* Calculate the shift only if we couldn't get
1578 * convwidth digits.
1579 */
1580 if (i != convwidth) {
1581 convmult = base;
1582 for ( ; i > 1; --i)
1583 convmult *= base;
1584 }
1585
1586 /* Multiply z by convmult, and add c. */
1587 pz = z->ob_digit;
1588 pzstop = pz + z->ob_size;
1589 for (; pz < pzstop; ++pz) {
1590 c += (twodigits)*pz * convmult;
1591 *pz = (digit)(c & MASK);
1592 c >>= SHIFT;
1593 }
1594 /* carry off the current end? */
1595 if (c) {
1596 assert(c < BASE);
1597 assert(z->ob_size < size_z);
1598 *pz = (digit)c;
1599 ++z->ob_size;
1600 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001601 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001602 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001603 if (z == NULL)
1604 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001605 if (str == start)
1606 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001607 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001608 z->ob_size = -(z->ob_size);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001609 if (*str == 'L' || *str == 'l')
1610 str++;
1611 while (*str && isspace(Py_CHARMASK(*str)))
1612 str++;
1613 if (*str != '\0')
1614 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001615 if (pend)
1616 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001617 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001618
1619 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001620 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001621 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1622 strobj = PyString_FromStringAndSize(orig_str, slen);
1623 if (strobj == NULL)
1624 return NULL;
1625 strrepr = PyObject_Repr(strobj);
1626 Py_DECREF(strobj);
1627 if (strrepr == NULL)
1628 return NULL;
1629 PyErr_Format(PyExc_ValueError,
1630 "invalid literal for long() with base %d: %s",
1631 base, PyString_AS_STRING(strrepr));
1632 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001633 return NULL;
1634}
1635
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001636#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001637PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001638PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001639{
Walter Dörwald07e14762002-11-06 16:15:14 +00001640 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001641 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001642
Walter Dörwald07e14762002-11-06 16:15:14 +00001643 if (buffer == NULL)
1644 return NULL;
1645
1646 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1647 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001648 return NULL;
1649 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001650 result = PyLong_FromString(buffer, NULL, base);
1651 PyMem_FREE(buffer);
1652 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001653}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001654#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001655
Tim Peters9f688bf2000-07-07 15:53:28 +00001656/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001657static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001658 (PyLongObject *, PyLongObject *, PyLongObject **);
1659static PyObject *long_pos(PyLongObject *);
1660static int long_divrem(PyLongObject *, PyLongObject *,
1661 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001662
1663/* Long division with remainder, top-level routine */
1664
Guido van Rossume32e0141992-01-19 16:31:05 +00001665static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001666long_divrem(PyLongObject *a, PyLongObject *b,
1667 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001668{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001669 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001670 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001671
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001672 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001673 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001674 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001675 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001676 }
1677 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001678 (size_a == size_b &&
1679 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001680 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001681 *pdiv = _PyLong_New(0);
1682 Py_INCREF(a);
1683 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001684 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001685 }
1686 if (size_b == 1) {
1687 digit rem = 0;
1688 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001689 if (z == NULL)
1690 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001691 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001692 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001693 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001694 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001695 if (z == NULL)
1696 return -1;
1697 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001698 /* Set the signs.
1699 The quotient z has the sign of a*b;
1700 the remainder r has the sign of a,
1701 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001702 if ((a->ob_size < 0) != (b->ob_size < 0))
1703 z->ob_size = -(z->ob_size);
1704 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1705 (*prem)->ob_size = -((*prem)->ob_size);
1706 *pdiv = z;
1707 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001708}
1709
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001710/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001711
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001712static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001713x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001714{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001715 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00001716 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001717 PyLongObject *v = mul1(v1, d);
1718 PyLongObject *w = mul1(w1, d);
1719 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001720 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001721
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001722 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001723 Py_XDECREF(v);
1724 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001725 return NULL;
1726 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001727
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001728 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001729 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001730 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001731
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001732 size_v = ABS(v->ob_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001733 k = size_v - size_w;
1734 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001735
Thomas Wouters477c8d52006-05-27 19:21:47 +00001736 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001737 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1738 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001739 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001740 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001741
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001742 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001743 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001744 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001745 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001746 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001747 if (vj == w->ob_digit[size_w-1])
1748 q = MASK;
1749 else
1750 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
1751 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001752
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001753 while (w->ob_digit[size_w-2]*q >
1754 ((
1755 ((twodigits)vj << SHIFT)
1756 + v->ob_digit[j-1]
1757 - q*w->ob_digit[size_w-1]
1758 ) << SHIFT)
1759 + v->ob_digit[j-2])
1760 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001761
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001762 for (i = 0; i < size_w && i+k < size_v; ++i) {
1763 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00001764 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001765 carry += v->ob_digit[i+k] - z
1766 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001767 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001768 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
1769 carry, SHIFT);
1770 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001771 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001772
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001773 if (i+k < size_v) {
1774 carry += v->ob_digit[i+k];
1775 v->ob_digit[i+k] = 0;
1776 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001777
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001778 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001779 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001780 else {
1781 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001782 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001783 carry = 0;
1784 for (i = 0; i < size_w && i+k < size_v; ++i) {
1785 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001786 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001787 carry = Py_ARITHMETIC_RIGHT_SHIFT(
1788 BASE_TWODIGITS_TYPE,
1789 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001790 }
1791 }
1792 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001793
Guido van Rossumc206c761995-01-10 15:23:19 +00001794 if (a == NULL)
1795 *prem = NULL;
1796 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001797 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001798 *prem = divrem1(v, d, &d);
1799 /* d receives the (unused) remainder */
1800 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001801 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001802 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001803 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001804 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001805 Py_DECREF(v);
1806 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001807 return a;
1808}
1809
1810/* Methods */
1811
1812static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001813long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001814{
Guido van Rossum9475a232001-10-05 20:51:39 +00001815 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001816}
1817
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001818static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001819long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001820{
Fred Drake121ee271999-12-23 15:41:28 +00001821 return long_format(v, 10, 1);
1822}
1823
1824static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001825long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001826{
1827 return long_format(v, 10, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001828}
1829
1830static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001831long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001832{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001833 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001834
Guido van Rossumc6913e71991-11-19 20:26:46 +00001835 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001836 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001837 sign = 0;
1838 else
1839 sign = a->ob_size - b->ob_size;
1840 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001841 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001842 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001843 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1844 ;
1845 if (i < 0)
1846 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001847 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001848 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001849 if (a->ob_size < 0)
1850 sign = -sign;
1851 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001852 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001853 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001854}
1855
Guido van Rossum9bfef441993-03-29 10:43:31 +00001856static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001857long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001858{
1859 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001860 Py_ssize_t i;
1861 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001862
1863 /* This is designed so that Python ints and longs with the
1864 same value hash to the same value, otherwise comparisons
1865 of mapping keys will turn out weird */
1866 i = v->ob_size;
1867 sign = 1;
1868 x = 0;
1869 if (i < 0) {
1870 sign = -1;
1871 i = -(i);
1872 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001873#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001874 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001875 /* Force a native long #-bits (32 or 64) circular shift */
1876 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001877 x += v->ob_digit[i];
1878 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001879#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00001880 x = x * sign;
1881 if (x == -1)
1882 x = -2;
1883 return x;
1884}
1885
1886
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001887/* Add the absolute values of two long integers. */
1888
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001889static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001890x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001891{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001892 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001893 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001894 int i;
1895 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001896
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001897 /* Ensure a is the larger of the two: */
1898 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001899 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001900 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001901 size_a = size_b;
1902 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001903 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001904 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001905 if (z == NULL)
1906 return NULL;
1907 for (i = 0; i < size_b; ++i) {
1908 carry += a->ob_digit[i] + b->ob_digit[i];
1909 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001910 carry >>= SHIFT;
1911 }
1912 for (; i < size_a; ++i) {
1913 carry += a->ob_digit[i];
1914 z->ob_digit[i] = carry & MASK;
1915 carry >>= SHIFT;
1916 }
1917 z->ob_digit[i] = carry;
1918 return long_normalize(z);
1919}
1920
1921/* Subtract the absolute values of two integers. */
1922
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001923static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001924x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001925{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001926 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001927 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001928 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001929 int sign = 1;
1930 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001931
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001932 /* Ensure a is the larger of the two: */
1933 if (size_a < size_b) {
1934 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001935 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001936 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001937 size_a = size_b;
1938 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001939 }
1940 else if (size_a == size_b) {
1941 /* Find highest digit where a and b differ: */
1942 i = size_a;
1943 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1944 ;
1945 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001946 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001947 if (a->ob_digit[i] < b->ob_digit[i]) {
1948 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001949 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001950 }
1951 size_a = size_b = i+1;
1952 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001953 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001954 if (z == NULL)
1955 return NULL;
1956 for (i = 0; i < size_b; ++i) {
1957 /* The following assumes unsigned arithmetic
1958 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001959 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001960 z->ob_digit[i] = borrow & MASK;
1961 borrow >>= SHIFT;
1962 borrow &= 1; /* Keep only one sign bit */
1963 }
1964 for (; i < size_a; ++i) {
1965 borrow = a->ob_digit[i] - borrow;
1966 z->ob_digit[i] = borrow & MASK;
1967 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00001968 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001969 }
1970 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001971 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001972 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001973 return long_normalize(z);
1974}
1975
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001976static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001977long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001978{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001979 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00001980
Neil Schemenauerba872e22001-01-04 01:46:03 +00001981 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1982
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001983 if (a->ob_size < 0) {
1984 if (b->ob_size < 0) {
1985 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001986 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001987 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001988 }
1989 else
1990 z = x_sub(b, a);
1991 }
1992 else {
1993 if (b->ob_size < 0)
1994 z = x_sub(a, b);
1995 else
1996 z = x_add(a, b);
1997 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001998 Py_DECREF(a);
1999 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002000 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002001}
2002
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002003static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002004long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002005{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002006 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002007
Neil Schemenauerba872e22001-01-04 01:46:03 +00002008 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2009
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002010 if (a->ob_size < 0) {
2011 if (b->ob_size < 0)
2012 z = x_sub(a, b);
2013 else
2014 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002015 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002016 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002017 }
2018 else {
2019 if (b->ob_size < 0)
2020 z = x_add(a, b);
2021 else
2022 z = x_sub(a, b);
2023 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002024 Py_DECREF(a);
2025 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002026 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002027}
2028
Tim Peters5af4e6c2002-08-12 02:31:19 +00002029/* Grade school multiplication, ignoring the signs.
2030 * Returns the absolute value of the product, or NULL if error.
2031 */
2032static PyLongObject *
2033x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002034{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002035 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002036 Py_ssize_t size_a = ABS(a->ob_size);
2037 Py_ssize_t size_b = ABS(b->ob_size);
2038 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002039
Tim Peters5af4e6c2002-08-12 02:31:19 +00002040 z = _PyLong_New(size_a + size_b);
2041 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002042 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002043
2044 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002045 if (a == b) {
2046 /* Efficient squaring per HAC, Algorithm 14.16:
2047 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2048 * Gives slightly less than a 2x speedup when a == b,
2049 * via exploiting that each entry in the multiplication
2050 * pyramid appears twice (except for the size_a squares).
2051 */
2052 for (i = 0; i < size_a; ++i) {
2053 twodigits carry;
2054 twodigits f = a->ob_digit[i];
2055 digit *pz = z->ob_digit + (i << 1);
2056 digit *pa = a->ob_digit + i + 1;
2057 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002058
Tim Peters0973b992004-08-29 22:16:50 +00002059 SIGCHECK({
2060 Py_DECREF(z);
2061 return NULL;
2062 })
2063
2064 carry = *pz + f * f;
2065 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002066 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002067 assert(carry <= MASK);
2068
2069 /* Now f is added in twice in each column of the
2070 * pyramid it appears. Same as adding f<<1 once.
2071 */
2072 f <<= 1;
2073 while (pa < paend) {
2074 carry += *pz + *pa++ * f;
2075 *pz++ = (digit)(carry & MASK);
2076 carry >>= SHIFT;
2077 assert(carry <= (MASK << 1));
2078 }
2079 if (carry) {
2080 carry += *pz;
2081 *pz++ = (digit)(carry & MASK);
2082 carry >>= SHIFT;
2083 }
2084 if (carry)
2085 *pz += (digit)(carry & MASK);
2086 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002087 }
Tim Peters0973b992004-08-29 22:16:50 +00002088 }
2089 else { /* a is not the same as b -- gradeschool long mult */
2090 for (i = 0; i < size_a; ++i) {
2091 twodigits carry = 0;
2092 twodigits f = a->ob_digit[i];
2093 digit *pz = z->ob_digit + i;
2094 digit *pb = b->ob_digit;
2095 digit *pbend = b->ob_digit + size_b;
2096
2097 SIGCHECK({
2098 Py_DECREF(z);
2099 return NULL;
2100 })
2101
2102 while (pb < pbend) {
2103 carry += *pz + *pb++ * f;
2104 *pz++ = (digit)(carry & MASK);
2105 carry >>= SHIFT;
2106 assert(carry <= MASK);
2107 }
2108 if (carry)
2109 *pz += (digit)(carry & MASK);
2110 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002111 }
2112 }
Tim Peters44121a62002-08-12 06:17:58 +00002113 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002114}
2115
2116/* A helper for Karatsuba multiplication (k_mul).
2117 Takes a long "n" and an integer "size" representing the place to
2118 split, and sets low and high such that abs(n) == (high << size) + low,
2119 viewing the shift as being by digits. The sign bit is ignored, and
2120 the return values are >= 0.
2121 Returns 0 on success, -1 on failure.
2122*/
2123static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002124kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002125{
2126 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002127 Py_ssize_t size_lo, size_hi;
2128 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002129
2130 size_lo = MIN(size_n, size);
2131 size_hi = size_n - size_lo;
2132
2133 if ((hi = _PyLong_New(size_hi)) == NULL)
2134 return -1;
2135 if ((lo = _PyLong_New(size_lo)) == NULL) {
2136 Py_DECREF(hi);
2137 return -1;
2138 }
2139
2140 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2141 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2142
2143 *high = long_normalize(hi);
2144 *low = long_normalize(lo);
2145 return 0;
2146}
2147
Tim Peters60004642002-08-12 22:01:34 +00002148static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2149
Tim Peters5af4e6c2002-08-12 02:31:19 +00002150/* Karatsuba multiplication. Ignores the input signs, and returns the
2151 * absolute value of the product (or NULL if error).
2152 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2153 */
2154static PyLongObject *
2155k_mul(PyLongObject *a, PyLongObject *b)
2156{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002157 Py_ssize_t asize = ABS(a->ob_size);
2158 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002159 PyLongObject *ah = NULL;
2160 PyLongObject *al = NULL;
2161 PyLongObject *bh = NULL;
2162 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002163 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002164 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002165 Py_ssize_t shift; /* the number of digits we split off */
2166 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002167
Tim Peters5af4e6c2002-08-12 02:31:19 +00002168 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2169 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2170 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002171 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002172 * By picking X to be a power of 2, "*X" is just shifting, and it's
2173 * been reduced to 3 multiplies on numbers half the size.
2174 */
2175
Tim Petersfc07e562002-08-12 02:54:10 +00002176 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002177 * is largest.
2178 */
Tim Peters738eda72002-08-12 15:08:20 +00002179 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002180 t1 = a;
2181 a = b;
2182 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002183
2184 i = asize;
2185 asize = bsize;
2186 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002187 }
2188
2189 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002190 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2191 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002192 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002193 return _PyLong_New(0);
2194 else
2195 return x_mul(a, b);
2196 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002197
Tim Peters60004642002-08-12 22:01:34 +00002198 /* If a is small compared to b, splitting on b gives a degenerate
2199 * case with ah==0, and Karatsuba may be (even much) less efficient
2200 * than "grade school" then. However, we can still win, by viewing
2201 * b as a string of "big digits", each of width a->ob_size. That
2202 * leads to a sequence of balanced calls to k_mul.
2203 */
2204 if (2 * asize <= bsize)
2205 return k_lopsided_mul(a, b);
2206
Tim Petersd6974a52002-08-13 20:37:51 +00002207 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002208 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002209 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002210 assert(ah->ob_size > 0); /* the split isn't degenerate */
2211
Tim Peters0973b992004-08-29 22:16:50 +00002212 if (a == b) {
2213 bh = ah;
2214 bl = al;
2215 Py_INCREF(bh);
2216 Py_INCREF(bl);
2217 }
2218 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002219
Tim Petersd64c1de2002-08-12 17:36:03 +00002220 /* The plan:
2221 * 1. Allocate result space (asize + bsize digits: that's always
2222 * enough).
2223 * 2. Compute ah*bh, and copy into result at 2*shift.
2224 * 3. Compute al*bl, and copy into result at 0. Note that this
2225 * can't overlap with #2.
2226 * 4. Subtract al*bl from the result, starting at shift. This may
2227 * underflow (borrow out of the high digit), but we don't care:
2228 * we're effectively doing unsigned arithmetic mod
2229 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2230 * borrows and carries out of the high digit can be ignored.
2231 * 5. Subtract ah*bh from the result, starting at shift.
2232 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2233 * at shift.
2234 */
2235
2236 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002237 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002238 if (ret == NULL) goto fail;
2239#ifdef Py_DEBUG
2240 /* Fill with trash, to catch reference to uninitialized digits. */
2241 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2242#endif
Tim Peters44121a62002-08-12 06:17:58 +00002243
Tim Petersd64c1de2002-08-12 17:36:03 +00002244 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002245 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2246 assert(t1->ob_size >= 0);
2247 assert(2*shift + t1->ob_size <= ret->ob_size);
2248 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2249 t1->ob_size * sizeof(digit));
2250
2251 /* Zero-out the digits higher than the ah*bh copy. */
2252 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002253 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002254 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002255 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002256
Tim Petersd64c1de2002-08-12 17:36:03 +00002257 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002258 if ((t2 = k_mul(al, bl)) == NULL) {
2259 Py_DECREF(t1);
2260 goto fail;
2261 }
2262 assert(t2->ob_size >= 0);
2263 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2264 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002265
2266 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002267 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002268 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002269 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002270
Tim Petersd64c1de2002-08-12 17:36:03 +00002271 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2272 * because it's fresher in cache.
2273 */
Tim Peters738eda72002-08-12 15:08:20 +00002274 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002275 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002276 Py_DECREF(t2);
2277
Tim Petersd64c1de2002-08-12 17:36:03 +00002278 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002279 Py_DECREF(t1);
2280
Tim Petersd64c1de2002-08-12 17:36:03 +00002281 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002282 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2283 Py_DECREF(ah);
2284 Py_DECREF(al);
2285 ah = al = NULL;
2286
Tim Peters0973b992004-08-29 22:16:50 +00002287 if (a == b) {
2288 t2 = t1;
2289 Py_INCREF(t2);
2290 }
2291 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002292 Py_DECREF(t1);
2293 goto fail;
2294 }
2295 Py_DECREF(bh);
2296 Py_DECREF(bl);
2297 bh = bl = NULL;
2298
Tim Peters738eda72002-08-12 15:08:20 +00002299 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002300 Py_DECREF(t1);
2301 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002302 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002303 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002304
Tim Petersd6974a52002-08-13 20:37:51 +00002305 /* Add t3. It's not obvious why we can't run out of room here.
2306 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002307 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002308 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002309 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002310
Tim Peters5af4e6c2002-08-12 02:31:19 +00002311 return long_normalize(ret);
2312
2313 fail:
2314 Py_XDECREF(ret);
2315 Py_XDECREF(ah);
2316 Py_XDECREF(al);
2317 Py_XDECREF(bh);
2318 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002319 return NULL;
2320}
2321
Tim Petersd6974a52002-08-13 20:37:51 +00002322/* (*) Why adding t3 can't "run out of room" above.
2323
Tim Petersab86c2b2002-08-15 20:06:00 +00002324Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2325to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002326
Tim Petersab86c2b2002-08-15 20:06:00 +000023271. For any integer i, i = c(i/2) + f(i/2). In particular,
2328 bsize = c(bsize/2) + f(bsize/2).
23292. shift = f(bsize/2)
23303. asize <= bsize
23314. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2332 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002333
Tim Petersab86c2b2002-08-15 20:06:00 +00002334We allocated asize + bsize result digits, and add t3 into them at an offset
2335of shift. This leaves asize+bsize-shift allocated digit positions for t3
2336to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2337asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002338
Tim Petersab86c2b2002-08-15 20:06:00 +00002339bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2340at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002341
Tim Petersab86c2b2002-08-15 20:06:00 +00002342If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2343digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2344most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002345
Tim Petersab86c2b2002-08-15 20:06:00 +00002346The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002347
Tim Petersab86c2b2002-08-15 20:06:00 +00002348 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002349
Tim Petersab86c2b2002-08-15 20:06:00 +00002350and we have asize + c(bsize/2) available digit positions. We need to show
2351this is always enough. An instance of c(bsize/2) cancels out in both, so
2352the question reduces to whether asize digits is enough to hold
2353(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2354then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2355asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2356digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2357asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002358c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2359is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2360bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002361
Tim Peters48d52c02002-08-14 17:07:32 +00002362Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2363clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2364ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002365*/
2366
Tim Peters60004642002-08-12 22:01:34 +00002367/* b has at least twice the digits of a, and a is big enough that Karatsuba
2368 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2369 * of slices, each with a->ob_size digits, and multiply the slices by a,
2370 * one at a time. This gives k_mul balanced inputs to work with, and is
2371 * also cache-friendly (we compute one double-width slice of the result
2372 * at a time, then move on, never bactracking except for the helpful
2373 * single-width slice overlap between successive partial sums).
2374 */
2375static PyLongObject *
2376k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2377{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002378 const Py_ssize_t asize = ABS(a->ob_size);
2379 Py_ssize_t bsize = ABS(b->ob_size);
2380 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002381 PyLongObject *ret;
2382 PyLongObject *bslice = NULL;
2383
2384 assert(asize > KARATSUBA_CUTOFF);
2385 assert(2 * asize <= bsize);
2386
2387 /* Allocate result space, and zero it out. */
2388 ret = _PyLong_New(asize + bsize);
2389 if (ret == NULL)
2390 return NULL;
2391 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2392
2393 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002394 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002395 if (bslice == NULL)
2396 goto fail;
2397
2398 nbdone = 0;
2399 while (bsize > 0) {
2400 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002401 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002402
2403 /* Multiply the next slice of b by a. */
2404 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2405 nbtouse * sizeof(digit));
2406 bslice->ob_size = nbtouse;
2407 product = k_mul(a, bslice);
2408 if (product == NULL)
2409 goto fail;
2410
2411 /* Add into result. */
2412 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2413 product->ob_digit, product->ob_size);
2414 Py_DECREF(product);
2415
2416 bsize -= nbtouse;
2417 nbdone += nbtouse;
2418 }
2419
2420 Py_DECREF(bslice);
2421 return long_normalize(ret);
2422
2423 fail:
2424 Py_DECREF(ret);
2425 Py_XDECREF(bslice);
2426 return NULL;
2427}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002428
2429static PyObject *
2430long_mul(PyLongObject *v, PyLongObject *w)
2431{
2432 PyLongObject *a, *b, *z;
2433
2434 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002435 Py_INCREF(Py_NotImplemented);
2436 return Py_NotImplemented;
2437 }
2438
Tim Petersd64c1de2002-08-12 17:36:03 +00002439 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002440 /* Negate if exactly one of the inputs is negative. */
2441 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002442 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002443 Py_DECREF(a);
2444 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002445 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002446}
2447
Guido van Rossume32e0141992-01-19 16:31:05 +00002448/* The / and % operators are now defined in terms of divmod().
2449 The expression a mod b has the value a - b*floor(a/b).
2450 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002451 |a| by |b|, with the sign of a. This is also expressed
2452 as a - b*trunc(a/b), if trunc truncates towards zero.
2453 Some examples:
2454 a b a rem b a mod b
2455 13 10 3 3
2456 -13 10 -3 7
2457 13 -10 3 -7
2458 -13 -10 -3 -3
2459 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002460 have different signs. We then subtract one from the 'div'
2461 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002462
Tim Peters47e52ee2004-08-30 02:44:38 +00002463/* Compute
2464 * *pdiv, *pmod = divmod(v, w)
2465 * NULL can be passed for pdiv or pmod, in which case that part of
2466 * the result is simply thrown away. The caller owns a reference to
2467 * each of these it requests (does not pass NULL for).
2468 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002469static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002470l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002471 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002472{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002473 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002474
Guido van Rossume32e0141992-01-19 16:31:05 +00002475 if (long_divrem(v, w, &div, &mod) < 0)
2476 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002477 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2478 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002479 PyLongObject *temp;
2480 PyLongObject *one;
2481 temp = (PyLongObject *) long_add(mod, w);
2482 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002483 mod = temp;
2484 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002485 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002486 return -1;
2487 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002488 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002489 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002490 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2491 Py_DECREF(mod);
2492 Py_DECREF(div);
2493 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002494 return -1;
2495 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002496 Py_DECREF(one);
2497 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002498 div = temp;
2499 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002500 if (pdiv != NULL)
2501 *pdiv = div;
2502 else
2503 Py_DECREF(div);
2504
2505 if (pmod != NULL)
2506 *pmod = mod;
2507 else
2508 Py_DECREF(mod);
2509
Guido van Rossume32e0141992-01-19 16:31:05 +00002510 return 0;
2511}
2512
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002513static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002514long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002515{
Tim Peters47e52ee2004-08-30 02:44:38 +00002516 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002517
2518 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002519 if (l_divmod(a, b, &div, NULL) < 0)
2520 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002521 Py_DECREF(a);
2522 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002523 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002524}
2525
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002526static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002527long_true_divide(PyObject *v, PyObject *w)
2528{
Tim Peterse2a60002001-09-04 06:17:36 +00002529 PyLongObject *a, *b;
2530 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002531 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002532
2533 CONVERT_BINOP(v, w, &a, &b);
2534 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2535 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002536 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2537 Py_DECREF(a);
2538 Py_DECREF(b);
2539 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002540 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002541 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2542 but should really be set correctly after sucessful calls to
2543 _PyLong_AsScaledDouble() */
2544 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002545
2546 if (bd == 0.0) {
2547 PyErr_SetString(PyExc_ZeroDivisionError,
2548 "long division or modulo by zero");
2549 return NULL;
2550 }
2551
2552 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2553 ad /= bd; /* overflow/underflow impossible here */
2554 aexp -= bexp;
2555 if (aexp > INT_MAX / SHIFT)
2556 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002557 else if (aexp < -(INT_MAX / SHIFT))
2558 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002559 errno = 0;
2560 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002561 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002562 goto overflow;
2563 return PyFloat_FromDouble(ad);
2564
2565overflow:
2566 PyErr_SetString(PyExc_OverflowError,
2567 "long/long too large for a float");
2568 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002569
Tim Peters20dab9f2001-09-04 05:31:47 +00002570}
2571
2572static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002573long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002574{
Tim Peters47e52ee2004-08-30 02:44:38 +00002575 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002576
2577 CONVERT_BINOP(v, w, &a, &b);
2578
Tim Peters47e52ee2004-08-30 02:44:38 +00002579 if (l_divmod(a, b, NULL, &mod) < 0)
2580 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002581 Py_DECREF(a);
2582 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002583 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002584}
2585
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002586static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002587long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002588{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002589 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002590 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002591
2592 CONVERT_BINOP(v, w, &a, &b);
2593
2594 if (l_divmod(a, b, &div, &mod) < 0) {
2595 Py_DECREF(a);
2596 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002597 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002598 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002599 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002600 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002601 PyTuple_SetItem(z, 0, (PyObject *) div);
2602 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002603 }
2604 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002605 Py_DECREF(div);
2606 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002607 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002608 Py_DECREF(a);
2609 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002610 return z;
2611}
2612
Tim Peters47e52ee2004-08-30 02:44:38 +00002613/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002614static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002615long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002616{
Tim Peters47e52ee2004-08-30 02:44:38 +00002617 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2618 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002619
Tim Peters47e52ee2004-08-30 02:44:38 +00002620 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002621 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002622 PyLongObject *temp = NULL;
2623
2624 /* 5-ary values. If the exponent is large enough, table is
2625 * precomputed so that table[i] == a**i % c for i in range(32).
2626 */
2627 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2628 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2629
2630 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002631 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002632 if (PyLong_Check(x)) {
2633 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002634 Py_INCREF(x);
2635 }
Tim Petersde7990b2005-07-17 23:45:23 +00002636 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002637 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002638 if (c == NULL)
2639 goto Error;
2640 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002641 else if (x == Py_None)
2642 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002643 else {
2644 Py_DECREF(a);
2645 Py_DECREF(b);
2646 Py_INCREF(Py_NotImplemented);
2647 return Py_NotImplemented;
2648 }
Tim Peters4c483c42001-09-05 06:24:58 +00002649
Tim Peters47e52ee2004-08-30 02:44:38 +00002650 if (b->ob_size < 0) { /* if exponent is negative */
2651 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002652 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002653 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002654 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002655 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002656 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002657 /* else return a float. This works because we know
2658 that this calls float_pow() which converts its
2659 arguments to double. */
2660 Py_DECREF(a);
2661 Py_DECREF(b);
2662 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002663 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002664 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002665
2666 if (c) {
2667 /* if modulus == 0:
2668 raise ValueError() */
2669 if (c->ob_size == 0) {
2670 PyErr_SetString(PyExc_ValueError,
2671 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002672 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002673 }
2674
2675 /* if modulus < 0:
2676 negativeOutput = True
2677 modulus = -modulus */
2678 if (c->ob_size < 0) {
2679 negativeOutput = 1;
2680 temp = (PyLongObject *)_PyLong_Copy(c);
2681 if (temp == NULL)
2682 goto Error;
2683 Py_DECREF(c);
2684 c = temp;
2685 temp = NULL;
2686 c->ob_size = - c->ob_size;
2687 }
2688
2689 /* if modulus == 1:
2690 return 0 */
2691 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
2692 z = (PyLongObject *)PyLong_FromLong(0L);
2693 goto Done;
2694 }
2695
2696 /* if base < 0:
2697 base = base % modulus
2698 Having the base positive just makes things easier. */
2699 if (a->ob_size < 0) {
2700 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002701 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002702 Py_DECREF(a);
2703 a = temp;
2704 temp = NULL;
2705 }
2706 }
2707
2708 /* At this point a, b, and c are guaranteed non-negative UNLESS
2709 c is NULL, in which case a may be negative. */
2710
2711 z = (PyLongObject *)PyLong_FromLong(1L);
2712 if (z == NULL)
2713 goto Error;
2714
2715 /* Perform a modular reduction, X = X % c, but leave X alone if c
2716 * is NULL.
2717 */
2718#define REDUCE(X) \
2719 if (c != NULL) { \
2720 if (l_divmod(X, c, NULL, &temp) < 0) \
2721 goto Error; \
2722 Py_XDECREF(X); \
2723 X = temp; \
2724 temp = NULL; \
2725 }
2726
2727 /* Multiply two values, then reduce the result:
2728 result = X*Y % c. If c is NULL, skip the mod. */
2729#define MULT(X, Y, result) \
2730{ \
2731 temp = (PyLongObject *)long_mul(X, Y); \
2732 if (temp == NULL) \
2733 goto Error; \
2734 Py_XDECREF(result); \
2735 result = temp; \
2736 temp = NULL; \
2737 REDUCE(result) \
2738}
2739
2740 if (b->ob_size <= FIVEARY_CUTOFF) {
2741 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2742 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
2743 for (i = b->ob_size - 1; i >= 0; --i) {
2744 digit bi = b->ob_digit[i];
2745
2746 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
2747 MULT(z, z, z)
2748 if (bi & j)
2749 MULT(z, a, z)
2750 }
2751 }
2752 }
2753 else {
2754 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2755 Py_INCREF(z); /* still holds 1L */
2756 table[0] = z;
2757 for (i = 1; i < 32; ++i)
2758 MULT(table[i-1], a, table[i])
2759
2760 for (i = b->ob_size - 1; i >= 0; --i) {
2761 const digit bi = b->ob_digit[i];
2762
2763 for (j = SHIFT - 5; j >= 0; j -= 5) {
2764 const int index = (bi >> j) & 0x1f;
2765 for (k = 0; k < 5; ++k)
2766 MULT(z, z, z)
2767 if (index)
2768 MULT(z, table[index], z)
2769 }
2770 }
2771 }
2772
2773 if (negativeOutput && (z->ob_size != 0)) {
2774 temp = (PyLongObject *)long_sub(z, c);
2775 if (temp == NULL)
2776 goto Error;
2777 Py_DECREF(z);
2778 z = temp;
2779 temp = NULL;
2780 }
2781 goto Done;
2782
2783 Error:
2784 if (z != NULL) {
2785 Py_DECREF(z);
2786 z = NULL;
2787 }
2788 /* fall through */
2789 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00002790 if (b->ob_size > FIVEARY_CUTOFF) {
2791 for (i = 0; i < 32; ++i)
2792 Py_XDECREF(table[i]);
2793 }
Tim Petersde7990b2005-07-17 23:45:23 +00002794 Py_DECREF(a);
2795 Py_DECREF(b);
2796 Py_XDECREF(c);
2797 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002798 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002799}
2800
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002801static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002802long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002803{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002804 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002805 PyLongObject *x;
2806 PyLongObject *w;
2807 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002808 if (w == NULL)
2809 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002810 x = (PyLongObject *) long_add(v, w);
2811 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002812 if (x == NULL)
2813 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00002814 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002815 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002816}
2817
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002818static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002819long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002820{
Tim Peters69c2de32001-09-11 22:31:33 +00002821 if (PyLong_CheckExact(v)) {
2822 Py_INCREF(v);
2823 return (PyObject *)v;
2824 }
2825 else
2826 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002827}
2828
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002829static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002830long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002831{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002832 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002833 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002834 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002835 Py_INCREF(v);
2836 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002837 }
Tim Peters69c2de32001-09-11 22:31:33 +00002838 z = (PyLongObject *)_PyLong_Copy(v);
2839 if (z != NULL)
2840 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002841 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002842}
2843
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002844static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002845long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002846{
2847 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002848 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002849 else
2850 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002851}
2852
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002853static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002854long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002855{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002856 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002857}
2858
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002859static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002860long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002861{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002862 PyLongObject *a, *b;
2863 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002864 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002865 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002866 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002867
Neil Schemenauerba872e22001-01-04 01:46:03 +00002868 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2869
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002870 if (a->ob_size < 0) {
2871 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002872 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002873 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002874 if (a1 == NULL)
2875 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002876 a2 = (PyLongObject *) long_rshift(a1, b);
2877 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002878 if (a2 == NULL)
2879 goto rshift_error;
2880 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002881 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002882 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002883 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002884
Neil Schemenauerba872e22001-01-04 01:46:03 +00002885 shiftby = PyLong_AsLong((PyObject *)b);
2886 if (shiftby == -1L && PyErr_Occurred())
2887 goto rshift_error;
2888 if (shiftby < 0) {
2889 PyErr_SetString(PyExc_ValueError,
2890 "negative shift count");
2891 goto rshift_error;
2892 }
2893 wordshift = shiftby / SHIFT;
2894 newsize = ABS(a->ob_size) - wordshift;
2895 if (newsize <= 0) {
2896 z = _PyLong_New(0);
2897 Py_DECREF(a);
2898 Py_DECREF(b);
2899 return (PyObject *)z;
2900 }
2901 loshift = shiftby % SHIFT;
2902 hishift = SHIFT - loshift;
2903 lomask = ((digit)1 << hishift) - 1;
2904 himask = MASK ^ lomask;
2905 z = _PyLong_New(newsize);
2906 if (z == NULL)
2907 goto rshift_error;
2908 if (a->ob_size < 0)
2909 z->ob_size = -(z->ob_size);
2910 for (i = 0, j = wordshift; i < newsize; i++, j++) {
2911 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
2912 if (i+1 < newsize)
2913 z->ob_digit[i] |=
2914 (a->ob_digit[j+1] << hishift) & himask;
2915 }
2916 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002917 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002918rshift_error:
2919 Py_DECREF(a);
2920 Py_DECREF(b);
2921 return (PyObject *) z;
2922
Guido van Rossumc6913e71991-11-19 20:26:46 +00002923}
2924
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002925static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002926long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002927{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002928 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002929 PyLongObject *a, *b;
2930 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002931 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002932 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002933 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002934
Neil Schemenauerba872e22001-01-04 01:46:03 +00002935 CONVERT_BINOP(v, w, &a, &b);
2936
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002937 shiftby = PyLong_AsLong((PyObject *)b);
2938 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00002939 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002940 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002941 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002942 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002943 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002944 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002945 PyErr_SetString(PyExc_ValueError,
2946 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002947 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002948 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002949 /* wordshift, remshift = divmod(shiftby, SHIFT) */
2950 wordshift = (int)shiftby / SHIFT;
2951 remshift = (int)shiftby - wordshift * SHIFT;
2952
2953 oldsize = ABS(a->ob_size);
2954 newsize = oldsize + wordshift;
2955 if (remshift)
2956 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002957 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002958 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002959 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002960 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002961 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002962 for (i = 0; i < wordshift; i++)
2963 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002964 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002965 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00002966 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002967 z->ob_digit[i] = (digit)(accum & MASK);
2968 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002969 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002970 if (remshift)
2971 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002972 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002973 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002974 z = long_normalize(z);
2975lshift_error:
2976 Py_DECREF(a);
2977 Py_DECREF(b);
2978 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002979}
2980
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002981
2982/* Bitwise and/xor/or operations */
2983
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002984static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002985long_bitwise(PyLongObject *a,
2986 int op, /* '&', '|', '^' */
2987 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002988{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002989 digit maska, maskb; /* 0 or MASK */
2990 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002991 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002992 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002993 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00002994 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002995 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002996
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002997 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002998 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002999 if (a == NULL)
3000 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003001 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003002 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003003 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003004 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003005 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003006 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003007 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003008 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003009 if (b == NULL) {
3010 Py_DECREF(a);
3011 return NULL;
3012 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003013 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003014 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003015 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003016 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003017 maskb = 0;
3018 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003019
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003020 negz = 0;
3021 switch (op) {
3022 case '^':
3023 if (maska != maskb) {
3024 maska ^= MASK;
3025 negz = -1;
3026 }
3027 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003028 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003029 if (maska && maskb) {
3030 op = '|';
3031 maska ^= MASK;
3032 maskb ^= MASK;
3033 negz = -1;
3034 }
3035 break;
3036 case '|':
3037 if (maska || maskb) {
3038 op = '&';
3039 maska ^= MASK;
3040 maskb ^= MASK;
3041 negz = -1;
3042 }
3043 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003044 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003045
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003046 /* JRH: The original logic here was to allocate the result value (z)
3047 as the longer of the two operands. However, there are some cases
3048 where the result is guaranteed to be shorter than that: AND of two
3049 positives, OR of two negatives: use the shorter number. AND with
3050 mixed signs: use the positive number. OR with mixed signs: use the
3051 negative number. After the transformations above, op will be '&'
3052 iff one of these cases applies, and mask will be non-0 for operands
3053 whose length should be ignored.
3054 */
3055
3056 size_a = a->ob_size;
3057 size_b = b->ob_size;
3058 size_z = op == '&'
3059 ? (maska
3060 ? size_b
3061 : (maskb ? size_a : MIN(size_a, size_b)))
3062 : MAX(size_a, size_b);
3063 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003064 if (z == NULL) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003065 Py_XDECREF(a);
3066 Py_XDECREF(b);
3067 Py_XDECREF(z);
3068 return NULL;
3069 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003070
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003071 for (i = 0; i < size_z; ++i) {
3072 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3073 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3074 switch (op) {
3075 case '&': z->ob_digit[i] = diga & digb; break;
3076 case '|': z->ob_digit[i] = diga | digb; break;
3077 case '^': z->ob_digit[i] = diga ^ digb; break;
3078 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003079 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003080
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003081 Py_DECREF(a);
3082 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003083 z = long_normalize(z);
3084 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003085 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003086 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003087 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003088 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003089}
3090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003091static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003092long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003093{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003094 PyLongObject *a, *b;
3095 PyObject *c;
3096 CONVERT_BINOP(v, w, &a, &b);
3097 c = long_bitwise(a, '&', b);
3098 Py_DECREF(a);
3099 Py_DECREF(b);
3100 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003101}
3102
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003103static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003104long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003105{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003106 PyLongObject *a, *b;
3107 PyObject *c;
3108 CONVERT_BINOP(v, w, &a, &b);
3109 c = long_bitwise(a, '^', b);
3110 Py_DECREF(a);
3111 Py_DECREF(b);
3112 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003113}
3114
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003115static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003116long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003117{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003118 PyLongObject *a, *b;
3119 PyObject *c;
3120 CONVERT_BINOP(v, w, &a, &b);
3121 c = long_bitwise(a, '|', b);
3122 Py_DECREF(a);
3123 Py_DECREF(b);
3124 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003125}
3126
Guido van Rossum234f9421993-06-17 12:35:49 +00003127static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003128long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003129{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003130 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003131 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003132 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003133 return 0;
3134 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003135 else if (PyLong_Check(*pw)) {
3136 Py_INCREF(*pv);
3137 Py_INCREF(*pw);
3138 return 0;
3139 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003140 return 1; /* Can't do it */
3141}
3142
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003143static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003144long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003145{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003146 if (PyLong_CheckExact(v))
3147 Py_INCREF(v);
3148 else
3149 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003150 return v;
3151}
3152
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003153static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003154long_int(PyObject *v)
3155{
3156 long x;
3157 x = PyLong_AsLong(v);
3158 if (PyErr_Occurred()) {
3159 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3160 PyErr_Clear();
3161 if (PyLong_CheckExact(v)) {
3162 Py_INCREF(v);
3163 return v;
3164 }
3165 else
3166 return _PyLong_Copy((PyLongObject *)v);
3167 }
3168 else
3169 return NULL;
3170 }
3171 return PyInt_FromLong(x);
3172}
3173
3174static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003175long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003176{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003177 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003178 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003179 if (result == -1.0 && PyErr_Occurred())
3180 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003181 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003182}
3183
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003184static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003185long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003186{
Fred Drake121ee271999-12-23 15:41:28 +00003187 return long_format(v, 8, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003188}
3189
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003190static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003191long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003192{
Fred Drake121ee271999-12-23 15:41:28 +00003193 return long_format(v, 16, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003194}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003195
3196static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003197long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003198
Tim Peters6d6c1a32001-08-02 04:15:00 +00003199static PyObject *
3200long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3201{
3202 PyObject *x = NULL;
3203 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003204 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205
Guido van Rossumbef14172001-08-29 15:47:46 +00003206 if (type != &PyLong_Type)
3207 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3209 &x, &base))
3210 return NULL;
3211 if (x == NULL)
3212 return PyLong_FromLong(0L);
3213 if (base == -909)
3214 return PyNumber_Long(x);
3215 else if (PyString_Check(x))
3216 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003217#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218 else if (PyUnicode_Check(x))
3219 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3220 PyUnicode_GET_SIZE(x),
3221 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003222#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003223 else {
3224 PyErr_SetString(PyExc_TypeError,
3225 "long() can't convert non-string with explicit base");
3226 return NULL;
3227 }
3228}
3229
Guido van Rossumbef14172001-08-29 15:47:46 +00003230/* Wimpy, slow approach to tp_new calls for subtypes of long:
3231 first create a regular long from whatever arguments we got,
3232 then allocate a subtype instance and initialize it from
3233 the regular long. The regular long is then thrown away.
3234*/
3235static PyObject *
3236long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3237{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003238 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003239 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003240
3241 assert(PyType_IsSubtype(type, &PyLong_Type));
3242 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3243 if (tmp == NULL)
3244 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003245 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003246 n = tmp->ob_size;
3247 if (n < 0)
3248 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003249 newobj = (PyLongObject *)type->tp_alloc(type, n);
3250 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003251 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003252 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003253 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003254 assert(PyLong_Check(newobj));
3255 newobj->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003256 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003257 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003258 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003259 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003260}
3261
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003262static PyObject *
3263long_getnewargs(PyLongObject *v)
3264{
3265 return Py_BuildValue("(N)", _PyLong_Copy(v));
3266}
3267
3268static PyMethodDef long_methods[] = {
3269 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3270 {NULL, NULL} /* sentinel */
3271};
3272
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003273PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003274"long(x[, base]) -> integer\n\
3275\n\
3276Convert a string or number to a long integer, if possible. A floating\n\
3277point argument will be truncated towards zero (this does not include a\n\
3278string representation of a floating point number!) When converting a\n\
3279string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003280converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003281
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003282static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003283 (binaryfunc) long_add, /*nb_add*/
3284 (binaryfunc) long_sub, /*nb_subtract*/
3285 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003286 long_mod, /*nb_remainder*/
3287 long_divmod, /*nb_divmod*/
3288 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003289 (unaryfunc) long_neg, /*nb_negative*/
3290 (unaryfunc) long_pos, /*tp_positive*/
3291 (unaryfunc) long_abs, /*tp_absolute*/
3292 (inquiry) long_nonzero, /*tp_nonzero*/
3293 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003294 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003295 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003296 long_and, /*nb_and*/
3297 long_xor, /*nb_xor*/
3298 long_or, /*nb_or*/
3299 long_coerce, /*nb_coerce*/
3300 long_int, /*nb_int*/
3301 long_long, /*nb_long*/
3302 long_float, /*nb_float*/
3303 long_oct, /*nb_oct*/
3304 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003305 0, /* nb_inplace_add */
3306 0, /* nb_inplace_subtract */
3307 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003308 0, /* nb_inplace_remainder */
3309 0, /* nb_inplace_power */
3310 0, /* nb_inplace_lshift */
3311 0, /* nb_inplace_rshift */
3312 0, /* nb_inplace_and */
3313 0, /* nb_inplace_xor */
3314 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003315 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003316 long_true_divide, /* nb_true_divide */
3317 0, /* nb_inplace_floor_divide */
3318 0, /* nb_inplace_true_divide */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003319 long_index, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003320};
3321
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003322PyTypeObject PyLong_Type = {
3323 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324 0, /* ob_size */
3325 "long", /* tp_name */
3326 sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
3327 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003328 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329 0, /* tp_print */
3330 0, /* tp_getattr */
3331 0, /* tp_setattr */
3332 (cmpfunc)long_compare, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003333 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003334 &long_as_number, /* tp_as_number */
3335 0, /* tp_as_sequence */
3336 0, /* tp_as_mapping */
3337 (hashfunc)long_hash, /* tp_hash */
3338 0, /* tp_call */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003339 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003340 PyObject_GenericGetAttr, /* tp_getattro */
3341 0, /* tp_setattro */
3342 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003343 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3344 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003345 long_doc, /* tp_doc */
3346 0, /* tp_traverse */
3347 0, /* tp_clear */
3348 0, /* tp_richcompare */
3349 0, /* tp_weaklistoffset */
3350 0, /* tp_iter */
3351 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003352 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003353 0, /* tp_members */
3354 0, /* tp_getset */
3355 0, /* tp_base */
3356 0, /* tp_dict */
3357 0, /* tp_descr_get */
3358 0, /* tp_descr_set */
3359 0, /* tp_dictoffset */
3360 0, /* tp_init */
3361 0, /* tp_alloc */
3362 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003363 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003364};