blob: e4e8859038e310cc4e3c1c2c33e4473b9a517270 [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"
Mark Dickinsonefc82f72009-03-20 15:51:55 +00009#include "structseq.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +000010
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000011#include <ctype.h>
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000012#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000013
Tim Peters5af4e6c2002-08-12 02:31:19 +000014/* For long multiplication, use the O(N**2) school algorithm unless
15 * both operands contain more than KARATSUBA_CUTOFF digits (this
Christian Heimes7f39c9f2008-01-25 12:18:43 +000016 * being an internal Python long digit, in base PyLong_BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000017 */
Tim Peters0973b992004-08-29 22:16:50 +000018#define KARATSUBA_CUTOFF 70
19#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000020
Tim Peters47e52ee2004-08-30 02:44:38 +000021/* For exponentiation, use the binary left-to-right algorithm
22 * unless the exponent contains more than FIVEARY_CUTOFF digits.
23 * In that case, do 5 bits at a time. The potential drawback is that
24 * a table of 2**5 intermediate results is computed.
25 */
26#define FIVEARY_CUTOFF 8
27
Guido van Rossume32e0141992-01-19 16:31:05 +000028#define ABS(x) ((x) < 0 ? -(x) : (x))
29
Tim Peters5af4e6c2002-08-12 02:31:19 +000030#undef MIN
31#undef MAX
32#define MAX(x, y) ((x) < (y) ? (y) : (x))
33#define MIN(x, y) ((x) > (y) ? (y) : (x))
34
Guido van Rossumc0b618a1997-05-02 03:12:38 +000035#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000036 if (--_Py_Ticker < 0) { \
37 _Py_Ticker = _Py_CheckInterval; \
Tim Petersd89fc222006-05-25 22:28:46 +000038 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000039 }
40
Guido van Rossumedcc38a1991-05-05 20:09:44 +000041/* Normalize (remove leading zeros from) a long int object.
42 Doesn't attempt to free the storage--in most cases, due to the nature
43 of the algorithms used, this could save at most be one word anyway. */
44
Guido van Rossumc0b618a1997-05-02 03:12:38 +000045static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000046long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000047{
Christian Heimese93237d2007-12-19 02:37:44 +000048 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +000049 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000050
Guido van Rossumedcc38a1991-05-05 20:09:44 +000051 while (i > 0 && v->ob_digit[i-1] == 0)
52 --i;
53 if (i != j)
Christian Heimese93237d2007-12-19 02:37:44 +000054 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +000055 return v;
56}
57
58/* Allocate a new long int object with size digits.
59 Return NULL and set exception if we run out of memory. */
60
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000061#define MAX_LONG_DIGITS \
62 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
63
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000065_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000066{
Mark Dickinsonbcf6b182009-02-15 15:48:39 +000067 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000068 PyErr_SetString(PyExc_OverflowError,
69 "too many digits in integer");
Martin v. Löwis18e16552006-02-15 17:27:45 +000070 return NULL;
71 }
Christian Heimes4956d2b2008-01-18 19:12:56 +000072 /* coverity[ampersand_in_size] */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000073 /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect
74 overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000076}
77
Tim Peters64b5ce32001-09-10 20:52:51 +000078PyObject *
79_PyLong_Copy(PyLongObject *src)
80{
81 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +000082 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000083
84 assert(src != NULL);
85 i = src->ob_size;
86 if (i < 0)
87 i = -(i);
88 result = _PyLong_New(i);
89 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +000090 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +000091 while (--i >= 0)
92 result->ob_digit[i] = src->ob_digit[i];
93 }
94 return (PyObject *)result;
95}
96
Guido van Rossumedcc38a1991-05-05 20:09:44 +000097/* Create a new long int object from a C long int */
98
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000100PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000101{
Tim Petersce9de2f2001-06-14 04:56:19 +0000102 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000103 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000104 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
105 int ndigits = 0;
106 int negative = 0;
107
108 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000109 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
110 ANSI C says that the result of -ival is undefined when ival
111 == LONG_MIN. Hence the following workaround. */
112 abs_ival = (unsigned long)(-1-ival) + 1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000113 negative = 1;
114 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000115 else {
116 abs_ival = (unsigned long)ival;
117 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000118
119 /* Count the number of Python digits.
120 We used to pick 5 ("big enough for anything"), but that's a
121 waste of time and space given that 5*15 = 75 bits are rarely
122 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000123 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000124 while (t) {
125 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000126 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000127 }
128 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000129 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000130 digit *p = v->ob_digit;
131 v->ob_size = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000132 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000133 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000134 *p++ = (digit)(t & PyLong_MASK);
135 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000136 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000137 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000139}
140
Guido van Rossum53756b11997-01-03 17:14:46 +0000141/* Create a new long int object from a C unsigned long int */
142
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000144PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000145{
Tim Petersce9de2f2001-06-14 04:56:19 +0000146 PyLongObject *v;
147 unsigned long t;
148 int ndigits = 0;
149
150 /* Count the number of Python digits. */
151 t = (unsigned long)ival;
152 while (t) {
153 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000154 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000155 }
156 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000157 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000158 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000159 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000160 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000161 *p++ = (digit)(ival & PyLong_MASK);
162 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000163 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000164 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000166}
167
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000168/* Create a new long int object from a C double */
169
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000172{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000174 double frac;
175 int i, ndig, expo, neg;
176 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000177 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000178 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonb6467572008-08-04 21:30:09 +0000179 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000180 return NULL;
181 }
Christian Heimes8267d1d2008-01-04 00:37:34 +0000182 if (Py_IS_NAN(dval)) {
Mark Dickinsonb6467572008-08-04 21:30:09 +0000183 PyErr_SetString(PyExc_ValueError,
184 "cannot convert float NaN to integer");
185 return NULL;
Christian Heimes8267d1d2008-01-04 00:37:34 +0000186 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000187 if (dval < 0.0) {
188 neg = 1;
189 dval = -dval;
190 }
191 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
192 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000193 return PyLong_FromLong(0L);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000194 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000196 if (v == NULL)
197 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000198 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000199 for (i = ndig; --i >= 0; ) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000200 digit bits = (digit)frac;
201 v->ob_digit[i] = bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000202 frac = frac - (double)bits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000203 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000204 }
205 if (neg)
Christian Heimese93237d2007-12-19 02:37:44 +0000206 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000207 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000208}
209
Armin Rigo7ccbca92006-10-04 12:17:45 +0000210/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
211 * anything about what happens when a signed integer operation overflows,
212 * and some compilers think they're doing you a favor by being "clever"
213 * then. The bit pattern for the largest postive signed long is
214 * (unsigned long)LONG_MAX, and for the smallest negative signed long
215 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
216 * However, some other compilers warn about applying unary minus to an
217 * unsigned operand. Hence the weird "0-".
218 */
219#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
220#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
221
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000222/* Get a C long int from a long int object.
223 Returns -1 and sets an error condition if overflow occurs. */
224
225long
Tim Peters9f688bf2000-07-07 15:53:28 +0000226PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000227{
Guido van Rossumf7531811998-05-26 14:33:37 +0000228 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000229 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000230 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000231 Py_ssize_t i;
232 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000233
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 if (vv == NULL || !PyLong_Check(vv)) {
Guido van Rossum7e35d572001-09-15 03:14:32 +0000235 if (vv != NULL && PyInt_Check(vv))
236 return PyInt_AsLong(vv);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000237 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238 return -1;
239 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000241 i = v->ob_size;
242 sign = 1;
243 x = 0;
244 if (i < 0) {
245 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000246 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000247 }
248 while (--i >= 0) {
249 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000250 x = (x << PyLong_SHIFT) + v->ob_digit[i];
251 if ((x >> PyLong_SHIFT) != prev)
Guido van Rossumf7531811998-05-26 14:33:37 +0000252 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000253 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000254 /* Haven't lost any bits, but casting to long requires extra care
255 * (see comment above).
256 */
257 if (x <= (unsigned long)LONG_MAX) {
258 return (long)x * sign;
259 }
260 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
261 return LONG_MIN;
262 }
263 /* else overflow */
Guido van Rossumf7531811998-05-26 14:33:37 +0000264
265 overflow:
266 PyErr_SetString(PyExc_OverflowError,
Skip Montanarobafedec2001-09-13 19:05:30 +0000267 "long int too large to convert to int");
Guido van Rossumf7531811998-05-26 14:33:37 +0000268 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000269}
270
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000271/* Get a Py_ssize_t from a long int object.
272 Returns -1 and sets an error condition if overflow occurs. */
273
274Py_ssize_t
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000275PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000276 register PyLongObject *v;
277 size_t x, prev;
278 Py_ssize_t i;
279 int sign;
280
281 if (vv == NULL || !PyLong_Check(vv)) {
282 PyErr_BadInternalCall();
283 return -1;
284 }
285 v = (PyLongObject *)vv;
286 i = v->ob_size;
287 sign = 1;
288 x = 0;
289 if (i < 0) {
290 sign = -1;
291 i = -(i);
292 }
293 while (--i >= 0) {
294 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000295 x = (x << PyLong_SHIFT) + v->ob_digit[i];
296 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000297 goto overflow;
298 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000299 /* Haven't lost any bits, but casting to a signed type requires
300 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000301 */
Armin Rigo7ccbca92006-10-04 12:17:45 +0000302 if (x <= (size_t)PY_SSIZE_T_MAX) {
303 return (Py_ssize_t)x * sign;
304 }
305 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
306 return PY_SSIZE_T_MIN;
307 }
308 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000309
310 overflow:
311 PyErr_SetString(PyExc_OverflowError,
312 "long int too large to convert to int");
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000313 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000314}
315
Guido van Rossumd8c80482002-08-13 00:24:58 +0000316/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000317 Returns -1 and sets an error condition if overflow occurs. */
318
319unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000320PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000321{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000322 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000323 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000324 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000325
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000327 if (vv != NULL && PyInt_Check(vv)) {
328 long val = PyInt_AsLong(vv);
329 if (val < 0) {
330 PyErr_SetString(PyExc_OverflowError,
331 "can't convert negative value to unsigned long");
332 return (unsigned long) -1;
333 }
334 return val;
335 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000336 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000337 return (unsigned long) -1;
338 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000340 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000341 x = 0;
342 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000344 "can't convert negative value to unsigned long");
345 return (unsigned long) -1;
346 }
347 while (--i >= 0) {
348 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000349 x = (x << PyLong_SHIFT) + v->ob_digit[i];
350 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000351 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000352 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000353 return (unsigned long) -1;
354 }
355 }
356 return x;
357}
358
Thomas Hellera4ea6032003-04-17 18:55:45 +0000359/* Get a C unsigned long int from a long int object, ignoring the high bits.
360 Returns -1 and sets an error condition if an error occurs. */
361
362unsigned long
363PyLong_AsUnsignedLongMask(PyObject *vv)
364{
365 register PyLongObject *v;
366 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000367 Py_ssize_t i;
368 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000369
370 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000371 if (vv != NULL && PyInt_Check(vv))
372 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000373 PyErr_BadInternalCall();
374 return (unsigned long) -1;
375 }
376 v = (PyLongObject *)vv;
377 i = v->ob_size;
378 sign = 1;
379 x = 0;
380 if (i < 0) {
381 sign = -1;
382 i = -i;
383 }
384 while (--i >= 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000385 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000386 }
387 return x * sign;
388}
389
Tim Peters5b8132f2003-01-31 15:52:05 +0000390int
391_PyLong_Sign(PyObject *vv)
392{
393 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000394
395 assert(v != NULL);
396 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000397
Christian Heimese93237d2007-12-19 02:37:44 +0000398 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000399}
400
Tim Petersbaefd9e2003-01-28 20:37:45 +0000401size_t
402_PyLong_NumBits(PyObject *vv)
403{
404 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000405 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000406 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000407
408 assert(v != NULL);
409 assert(PyLong_Check(v));
Christian Heimese93237d2007-12-19 02:37:44 +0000410 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000411 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
412 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000413 digit msd = v->ob_digit[ndigits - 1];
414
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000415 result = (ndigits - 1) * PyLong_SHIFT;
416 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000417 goto Overflow;
418 do {
419 ++result;
420 if (result == 0)
421 goto Overflow;
422 msd >>= 1;
423 } while (msd);
424 }
425 return result;
426
427Overflow:
428 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
429 "to express in a platform size_t");
430 return (size_t)-1;
431}
432
Tim Peters2a9b3672001-06-11 21:23:58 +0000433PyObject *
434_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
435 int little_endian, int is_signed)
436{
437 const unsigned char* pstartbyte;/* LSB of bytes */
438 int incr; /* direction to move pstartbyte */
439 const unsigned char* pendbyte; /* MSB of bytes */
440 size_t numsignificantbytes; /* number of bytes that matter */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000441 Py_ssize_t ndigits; /* number of Python long digits */
Tim Peters2a9b3672001-06-11 21:23:58 +0000442 PyLongObject* v; /* result */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000443 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000444
445 if (n == 0)
446 return PyLong_FromLong(0L);
447
448 if (little_endian) {
449 pstartbyte = bytes;
450 pendbyte = bytes + n - 1;
451 incr = 1;
452 }
453 else {
454 pstartbyte = bytes + n - 1;
455 pendbyte = bytes;
456 incr = -1;
457 }
458
459 if (is_signed)
460 is_signed = *pendbyte >= 0x80;
461
462 /* Compute numsignificantbytes. This consists of finding the most
463 significant byte. Leading 0 bytes are insignficant if the number
464 is positive, and leading 0xff bytes if negative. */
465 {
466 size_t i;
467 const unsigned char* p = pendbyte;
468 const int pincr = -incr; /* search MSB to LSB */
469 const unsigned char insignficant = is_signed ? 0xff : 0x00;
470
471 for (i = 0; i < n; ++i, p += pincr) {
472 if (*p != insignficant)
473 break;
474 }
475 numsignificantbytes = n - i;
476 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
477 actually has 2 significant bytes. OTOH, 0xff0001 ==
478 -0x00ffff, so we wouldn't *need* to bump it there; but we
479 do for 0xffff = -0x0001. To be safe without bothering to
480 check every case, bump it regardless. */
481 if (is_signed && numsignificantbytes < n)
482 ++numsignificantbytes;
483 }
484
485 /* How many Python long digits do we need? We have
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000486 8*numsignificantbytes bits, and each Python long digit has
487 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
488 /* catch overflow before it happens */
489 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
490 PyErr_SetString(PyExc_OverflowError,
491 "byte array too long to convert to int");
492 return NULL;
493 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000494 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000495 v = _PyLong_New(ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000496 if (v == NULL)
497 return NULL;
498
499 /* Copy the bits over. The tricky parts are computing 2's-comp on
500 the fly for signed numbers, and dealing with the mismatch between
501 8-bit bytes and (probably) 15-bit Python digits.*/
502 {
503 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000504 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000505 twodigits accum = 0; /* sliding register */
506 unsigned int accumbits = 0; /* number of bits in accum */
507 const unsigned char* p = pstartbyte;
508
509 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000510 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000511 /* Compute correction for 2's comp, if needed. */
512 if (is_signed) {
513 thisbyte = (0xff ^ thisbyte) + carry;
514 carry = thisbyte >> 8;
515 thisbyte &= 0xff;
516 }
517 /* Because we're going LSB to MSB, thisbyte is
518 more significant than what's already in accum,
519 so needs to be prepended to accum. */
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000520 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000521 accumbits += 8;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000522 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000523 /* There's enough to fill a Python digit. */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000524 assert(idigit < ndigits);
525 v->ob_digit[idigit] = (digit)(accum &
526 PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000527 ++idigit;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000528 accum >>= PyLong_SHIFT;
529 accumbits -= PyLong_SHIFT;
530 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000531 }
532 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000533 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000534 if (accumbits) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000535 assert(idigit < ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000536 v->ob_digit[idigit] = (digit)accum;
537 ++idigit;
538 }
539 }
540
Christian Heimese93237d2007-12-19 02:37:44 +0000541 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000542 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{
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000550 Py_ssize_t 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 */
Mark Dickinson1afe6dd2009-01-25 22:12:31 +0000555 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000556 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
Christian Heimese93237d2007-12-19 02:37:44 +0000562 if (Py_SIZE(v) < 0) {
563 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000564 if (!is_signed) {
Mark Dickinson4015f622009-02-10 15:46:50 +0000565 PyErr_SetString(PyExc_OverflowError,
Tim Peters2a9b3672001-06-11 21:23:58 +0000566 "can't convert negative long to unsigned");
567 return -1;
568 }
569 do_twos_comp = 1;
570 }
571 else {
Christian Heimese93237d2007-12-19 02:37:44 +0000572 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000573 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
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000587 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000588 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) {
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000595 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000596 if (do_twos_comp) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000597 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
598 carry = thisdigit >> PyLong_SHIFT;
599 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000600 }
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. */
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000604 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000605
Tim Petersede05092001-06-14 08:53:38 +0000606 /* The most-significant digit may be (probably is) at least
607 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000608 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000609 /* Count # of sign bits -- they needn't be stored,
610 * although for signed conversion we need later to
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000611 * make sure at least one sign bit gets stored. */
612 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
613 thisdigit;
614 while (s != 0) {
615 s >>= 1;
616 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000617 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000618 }
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000619 else
620 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000621
Tim Peters2a9b3672001-06-11 21:23:58 +0000622 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000623 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000624 if (j >= n)
625 goto Overflow;
626 ++j;
627 *p = (unsigned char)(accum & 0xff);
628 p += pincr;
629 accumbits -= 8;
630 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000631 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000632 }
633
634 /* Store the straggler (if any). */
635 assert(accumbits < 8);
636 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000637 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000638 if (j >= n)
639 goto Overflow;
640 ++j;
641 if (do_twos_comp) {
642 /* Fill leading bits of the byte with sign bits
643 (appropriately pretending that the long had an
644 infinite supply of sign bits). */
645 accum |= (~(twodigits)0) << accumbits;
646 }
647 *p = (unsigned char)(accum & 0xff);
648 p += pincr;
649 }
Tim Peters05607ad2001-06-13 21:01:27 +0000650 else if (j == n && n > 0 && is_signed) {
651 /* The main loop filled the byte array exactly, so the code
652 just above didn't get to ensure there's a sign bit, and the
653 loop below wouldn't add one either. Make sure a sign bit
654 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000655 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000656 int sign_bit_set = msb >= 0x80;
657 assert(accumbits == 0);
658 if (sign_bit_set == do_twos_comp)
659 return 0;
660 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000661 goto Overflow;
662 }
Tim Peters05607ad2001-06-13 21:01:27 +0000663
664 /* Fill remaining bytes with copies of the sign bit. */
665 {
666 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
667 for ( ; j < n; ++j, p += pincr)
668 *p = signbyte;
669 }
670
Tim Peters2a9b3672001-06-11 21:23:58 +0000671 return 0;
672
673Overflow:
674 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
675 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000676
Tim Peters2a9b3672001-06-11 21:23:58 +0000677}
678
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000679double
680_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
681{
682/* NBITS_WANTED should be > the number of bits in a double's precision,
683 but small enough so that 2**NBITS_WANTED is within the normal double
684 range. nbitsneeded is set to 1 less than that because the most-significant
685 Python digit contains at least 1 significant bit, but we don't want to
686 bother counting them (catering to the worst case cheaply).
687
688 57 is one more than VAX-D double precision; I (Tim) don't know of a double
689 format with more precision than that; it's 1 larger so that we add in at
690 least one round bit to stand in for the ignored least-significant bits.
691*/
692#define NBITS_WANTED 57
693 PyLongObject *v;
694 double x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000695 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000696 Py_ssize_t i;
697 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000698 int nbitsneeded;
699
700 if (vv == NULL || !PyLong_Check(vv)) {
701 PyErr_BadInternalCall();
702 return -1;
703 }
704 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000705 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000706 sign = 1;
707 if (i < 0) {
708 sign = -1;
709 i = -(i);
710 }
711 else if (i == 0) {
712 *exponent = 0;
713 return 0.0;
714 }
715 --i;
716 x = (double)v->ob_digit[i];
717 nbitsneeded = NBITS_WANTED - 1;
718 /* Invariant: i Python digits remain unaccounted for. */
719 while (i > 0 && nbitsneeded > 0) {
720 --i;
721 x = x * multiplier + (double)v->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000722 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000723 }
724 /* There are i digits we didn't shift in. Pretending they're all
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000725 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000726 *exponent = i;
727 assert(x > 0.0);
728 return x * sign;
729#undef NBITS_WANTED
730}
731
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000732/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000733
734double
Tim Peters9f688bf2000-07-07 15:53:28 +0000735PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000736{
Thomas Wouters553489a2006-02-01 21:32:04 +0000737 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000738 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000739
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000740 if (vv == NULL || !PyLong_Check(vv)) {
741 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000742 return -1;
743 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000744 x = _PyLong_AsScaledDouble(vv, &e);
745 if (x == -1.0 && PyErr_Occurred())
746 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000747 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
748 set correctly after a successful _PyLong_AsScaledDouble() call */
749 assert(e >= 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000750 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000751 goto overflow;
752 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000753 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000754 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000755 goto overflow;
756 return x;
757
758overflow:
759 PyErr_SetString(PyExc_OverflowError,
760 "long int too large to convert to float");
761 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000762}
763
Guido van Rossum78694d91998-09-18 14:14:13 +0000764/* Create a new long (or int) object from a C pointer */
765
766PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000767PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000768{
Tim Peters70128a12001-06-16 08:48:40 +0000769#if SIZEOF_VOID_P <= SIZEOF_LONG
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000770 if ((long)p < 0)
771 return PyLong_FromUnsignedLong((unsigned long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000772 return PyInt_FromLong((long)p);
773#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000774
Tim Peters70128a12001-06-16 08:48:40 +0000775#ifndef HAVE_LONG_LONG
776# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
777#endif
778#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000779# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000780#endif
781 /* optimize null pointers */
782 if (p == NULL)
783 return PyInt_FromLong(0);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000784 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000785
786#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000787}
788
789/* Get a C pointer from a long object (or an int object in some cases) */
790
791void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000792PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000793{
794 /* This function will allow int or long objects. If vv is neither,
795 then the PyLong_AsLong*() functions will raise the exception:
796 PyExc_SystemError, "bad argument to internal function"
797 */
Tim Peters70128a12001-06-16 08:48:40 +0000798#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000799 long x;
800
Tim Peters70128a12001-06-16 08:48:40 +0000801 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000802 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000803 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000804 x = PyLong_AsLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000805 else
806 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000807#else
Tim Peters70128a12001-06-16 08:48:40 +0000808
809#ifndef HAVE_LONG_LONG
810# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
811#endif
812#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000813# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000814#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000815 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000816
Tim Peters70128a12001-06-16 08:48:40 +0000817 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000818 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000819 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000820 x = PyLong_AsLongLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000821 else
822 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000823
824#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000825
826 if (x == -1 && PyErr_Occurred())
827 return NULL;
828 return (void *)x;
829}
830
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000831#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000832
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000833/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000834 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000835 */
836
Tim Peterscf37dfc2001-06-14 18:42:50 +0000837#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000838
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000839/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000840
841PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000842PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000843{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000844 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000845 unsigned PY_LONG_LONG abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000846 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
847 int ndigits = 0;
848 int negative = 0;
849
850 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000851 /* avoid signed overflow on negation; see comments
852 in PyLong_FromLong above. */
853 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000854 negative = 1;
855 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000856 else {
857 abs_ival = (unsigned PY_LONG_LONG)ival;
858 }
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000859
860 /* Count the number of Python digits.
861 We used to pick 5 ("big enough for anything"), but that's a
862 waste of time and space given that 5*15 = 75 bits are rarely
863 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000864 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000865 while (t) {
866 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000867 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000868 }
869 v = _PyLong_New(ndigits);
870 if (v != NULL) {
871 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000872 Py_SIZE(v) = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000873 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000874 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000875 *p++ = (digit)(t & PyLong_MASK);
876 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000877 }
878 }
879 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000880}
881
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000882/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000883
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000884PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000885PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000886{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000887 PyLongObject *v;
888 unsigned PY_LONG_LONG t;
889 int ndigits = 0;
890
891 /* Count the number of Python digits. */
892 t = (unsigned PY_LONG_LONG)ival;
893 while (t) {
894 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000895 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000896 }
897 v = _PyLong_New(ndigits);
898 if (v != NULL) {
899 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000900 Py_SIZE(v) = ndigits;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000901 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000902 *p++ = (digit)(ival & PyLong_MASK);
903 ival >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000904 }
905 }
906 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000907}
908
Martin v. Löwis18e16552006-02-15 17:27:45 +0000909/* Create a new long int object from a C Py_ssize_t. */
910
911PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000912PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000913{
914 Py_ssize_t bytes = ival;
915 int one = 1;
916 return _PyLong_FromByteArray(
917 (unsigned char *)&bytes,
Kristján Valur Jónssonf0303942007-05-03 20:27:03 +0000918 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000919}
920
921/* Create a new long int object from a C size_t. */
922
923PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000924PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000925{
926 size_t bytes = ival;
927 int one = 1;
928 return _PyLong_FromByteArray(
929 (unsigned char *)&bytes,
930 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
931}
932
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000933/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000934 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000935
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000936PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000937PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000938{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000939 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000940 int one = 1;
941 int res;
942
Tim Petersd38b1c72001-09-30 05:09:37 +0000943 if (vv == NULL) {
944 PyErr_BadInternalCall();
945 return -1;
946 }
947 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000948 PyNumberMethods *nb;
949 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000950 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000951 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000952 if ((nb = vv->ob_type->tp_as_number) == NULL ||
953 nb->nb_int == NULL) {
954 PyErr_SetString(PyExc_TypeError, "an integer is required");
955 return -1;
956 }
957 io = (*nb->nb_int) (vv);
958 if (io == NULL)
959 return -1;
960 if (PyInt_Check(io)) {
961 bytes = PyInt_AsLong(io);
962 Py_DECREF(io);
963 return bytes;
964 }
965 if (PyLong_Check(io)) {
966 bytes = PyLong_AsLongLong(io);
967 Py_DECREF(io);
968 return bytes;
969 }
970 Py_DECREF(io);
971 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000972 return -1;
973 }
974
Tim Petersd1a7da62001-06-13 00:35:57 +0000975 res = _PyLong_AsByteArray(
976 (PyLongObject *)vv, (unsigned char *)&bytes,
977 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000978
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000979 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000980 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000981 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000982 else
983 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000984}
985
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000986/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000987 Return -1 and set an error if overflow occurs. */
988
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000989unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000990PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000991{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000992 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000993 int one = 1;
994 int res;
995
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000996 if (vv == NULL || !PyLong_Check(vv)) {
997 PyErr_BadInternalCall();
Skip Montanaro429433b2006-04-18 00:35:43 +0000998 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000999 }
1000
Tim Petersd1a7da62001-06-13 00:35:57 +00001001 res = _PyLong_AsByteArray(
1002 (PyLongObject *)vv, (unsigned char *)&bytes,
1003 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001004
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001005 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001006 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001007 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001008 else
1009 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001010}
Tim Petersd1a7da62001-06-13 00:35:57 +00001011
Thomas Hellera4ea6032003-04-17 18:55:45 +00001012/* Get a C unsigned long int from a long int object, ignoring the high bits.
1013 Returns -1 and sets an error condition if an error occurs. */
1014
1015unsigned PY_LONG_LONG
1016PyLong_AsUnsignedLongLongMask(PyObject *vv)
1017{
1018 register PyLongObject *v;
1019 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001020 Py_ssize_t i;
1021 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001022
1023 if (vv == NULL || !PyLong_Check(vv)) {
1024 PyErr_BadInternalCall();
1025 return (unsigned long) -1;
1026 }
1027 v = (PyLongObject *)vv;
1028 i = v->ob_size;
1029 sign = 1;
1030 x = 0;
1031 if (i < 0) {
1032 sign = -1;
1033 i = -i;
1034 }
1035 while (--i >= 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001036 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001037 }
1038 return x * sign;
1039}
Tim Petersd1a7da62001-06-13 00:35:57 +00001040#undef IS_LITTLE_ENDIAN
1041
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001042#endif /* HAVE_LONG_LONG */
1043
Neil Schemenauerba872e22001-01-04 01:46:03 +00001044
1045static int
1046convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001047 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001048 *a = (PyLongObject *) v;
1049 Py_INCREF(v);
1050 }
1051 else if (PyInt_Check(v)) {
1052 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1053 }
1054 else {
1055 return 0;
1056 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001057 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001058 *b = (PyLongObject *) w;
1059 Py_INCREF(w);
1060 }
1061 else if (PyInt_Check(w)) {
1062 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1063 }
1064 else {
1065 Py_DECREF(*a);
1066 return 0;
1067 }
1068 return 1;
1069}
1070
1071#define CONVERT_BINOP(v, w, a, b) \
1072 if (!convert_binop(v, w, a, b)) { \
1073 Py_INCREF(Py_NotImplemented); \
1074 return Py_NotImplemented; \
1075 }
1076
Tim Peters877a2122002-08-12 05:09:36 +00001077/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1078 * is modified in place, by adding y to it. Carries are propagated as far as
1079 * x[m-1], and the remaining carry (0 or 1) is returned.
1080 */
1081static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001082v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001083{
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001084 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001085 digit carry = 0;
1086
1087 assert(m >= n);
1088 for (i = 0; i < n; ++i) {
1089 carry += x[i] + y[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001090 x[i] = carry & PyLong_MASK;
1091 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001092 assert((carry & 1) == carry);
1093 }
1094 for (; carry && i < m; ++i) {
1095 carry += x[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001096 x[i] = carry & PyLong_MASK;
1097 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001098 assert((carry & 1) == carry);
1099 }
1100 return carry;
1101}
1102
1103/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1104 * is modified in place, by subtracting y from it. Borrows are propagated as
1105 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1106 */
1107static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001108v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001109{
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001110 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001111 digit borrow = 0;
1112
1113 assert(m >= n);
1114 for (i = 0; i < n; ++i) {
1115 borrow = x[i] - y[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001116 x[i] = borrow & PyLong_MASK;
1117 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001118 borrow &= 1; /* keep only 1 sign bit */
1119 }
1120 for (; borrow && i < m; ++i) {
1121 borrow = x[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001122 x[i] = borrow & PyLong_MASK;
1123 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001124 borrow &= 1;
1125 }
1126 return borrow;
1127}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001128
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001129/* Multiply by a single digit, ignoring the sign. */
1130
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001131static PyLongObject *
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00001132mul1(PyLongObject *a, digit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001133{
Christian Heimese93237d2007-12-19 02:37:44 +00001134 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001135 PyLongObject *z = _PyLong_New(size_a+1);
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00001136 twodigits carry = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001137 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001138
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001139 if (z == NULL)
1140 return NULL;
1141 for (i = 0; i < size_a; ++i) {
1142 carry += (twodigits)a->ob_digit[i] * n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001143 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1144 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001145 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001146 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001147 return long_normalize(z);
1148}
1149
Tim Peters212e6142001-07-14 12:23:19 +00001150/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1151 in pout, and returning the remainder. pin and pout point at the LSD.
1152 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Eric Smith5e527eb2008-02-10 01:36:53 +00001153 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001154 immutable. */
1155
1156static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001157inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001158{
1159 twodigits rem = 0;
1160
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001161 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001162 pin += size;
1163 pout += size;
1164 while (--size >= 0) {
1165 digit hi;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001166 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001167 *--pout = hi = (digit)(rem / n);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001168 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001169 }
1170 return (digit)rem;
1171}
1172
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001173/* Divide a long integer by a digit, returning both the quotient
1174 (as function result) and the remainder (through *prem).
1175 The sign of a is ignored; n should not be zero. */
1176
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001177static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001178divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001179{
Christian Heimese93237d2007-12-19 02:37:44 +00001180 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001181 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001182
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001183 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001184 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001185 if (z == NULL)
1186 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001187 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001188 return long_normalize(z);
1189}
1190
Eric Smith5e527eb2008-02-10 01:36:53 +00001191/* Convert the long to a string object with given base,
1192 appending a base prefix of 0[box] if base is 2, 8 or 16.
1193 Add a trailing "L" if addL is non-zero.
1194 If newstyle is zero, then use the pre-2.6 behavior of octal having
1195 a leading "0", instead of the prefix "0o" */
1196PyAPI_FUNC(PyObject *)
1197_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001198{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001199 register PyLongObject *a = (PyLongObject *)aa;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001200 PyStringObject *str;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001201 Py_ssize_t i, j, sz;
Neal Norwitzc09efa82006-07-23 07:53:14 +00001202 Py_ssize_t size_a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001203 char *p;
1204 int bits;
1205 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001206
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001207 if (a == NULL || !PyLong_Check(a)) {
1208 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001209 return NULL;
1210 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001211 assert(base >= 2 && base <= 36);
Christian Heimese93237d2007-12-19 02:37:44 +00001212 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001213
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001214 /* Compute a rough upper bound for the length of the string */
1215 i = base;
1216 bits = 0;
1217 while (i > 1) {
1218 ++bits;
1219 i >>= 1;
1220 }
Armin Rigo7ccbca92006-10-04 12:17:45 +00001221 i = 5 + (addL ? 1 : 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001222 j = size_a*PyLong_SHIFT + bits-1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001223 sz = i + j / bits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001224 if (j / PyLong_SHIFT < size_a || sz < i) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00001225 PyErr_SetString(PyExc_OverflowError,
1226 "long is too large to format");
1227 return NULL;
1228 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001229 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001230 if (str == NULL)
1231 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001232 p = PyString_AS_STRING(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001233 *p = '\0';
Fred Drake121ee271999-12-23 15:41:28 +00001234 if (addL)
1235 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001236 if (a->ob_size < 0)
1237 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001238
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001239 if (a->ob_size == 0) {
1240 *--p = '0';
1241 }
1242 else if ((base & (base - 1)) == 0) {
1243 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001244 twodigits accum = 0;
1245 int accumbits = 0; /* # of bits in accum */
1246 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001247 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001248 while ((i >>= 1) > 1)
1249 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001250
1251 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001252 accum |= (twodigits)a->ob_digit[i] << accumbits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001253 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001254 assert(accumbits >= basebits);
1255 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001256 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001257 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001258 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001259 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001260 accumbits -= basebits;
1261 accum >>= basebits;
1262 } while (i < size_a-1 ? accumbits >= basebits :
1263 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001264 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001265 }
1266 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001267 /* Not 0, and base not a power of 2. Divide repeatedly by
1268 base, but for speed use the highest power of base that
1269 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001270 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001271 digit *pin = a->ob_digit;
1272 PyLongObject *scratch;
1273 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001274 digit powbase = base; /* powbase == base ** power */
1275 int power = 1;
1276 for (;;) {
Mark Dickinsonb6464872009-02-25 20:29:50 +00001277 twodigits newpow = powbase * (twodigits)base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001278 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001279 break;
1280 powbase = (digit)newpow;
1281 ++power;
1282 }
Tim Peters212e6142001-07-14 12:23:19 +00001283
1284 /* Get a scratch area for repeated division. */
1285 scratch = _PyLong_New(size);
1286 if (scratch == NULL) {
1287 Py_DECREF(str);
1288 return NULL;
1289 }
1290
1291 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001292 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001293 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001294 digit rem = inplace_divrem1(scratch->ob_digit,
1295 pin, size, powbase);
1296 pin = scratch->ob_digit; /* no need to use a again */
1297 if (pin[size - 1] == 0)
1298 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001299 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001300 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001301 Py_DECREF(str);
1302 return NULL;
1303 })
Tim Peters212e6142001-07-14 12:23:19 +00001304
1305 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001306 assert(ntostore > 0);
1307 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001308 digit nextrem = (digit)(rem / base);
1309 char c = (char)(rem - nextrem * base);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001310 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001311 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001312 *--p = c;
1313 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001314 --ntostore;
1315 /* Termination is a bit delicate: must not
1316 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001317 remaining quotient and rem are both 0. */
1318 } while (ntostore && (size || rem));
1319 } while (size != 0);
1320 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001321 }
1322
Eric Smith5e527eb2008-02-10 01:36:53 +00001323 if (base == 2) {
1324 *--p = 'b';
1325 *--p = '0';
1326 }
1327 else if (base == 8) {
1328 if (newstyle) {
1329 *--p = 'o';
Guido van Rossum2c475421992-08-14 15:13:07 +00001330 *--p = '0';
Eric Smith5e527eb2008-02-10 01:36:53 +00001331 }
1332 else
1333 if (size_a != 0)
1334 *--p = '0';
Guido van Rossum2c475421992-08-14 15:13:07 +00001335 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001336 else if (base == 16) {
1337 *--p = 'x';
1338 *--p = '0';
1339 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001340 else if (base != 10) {
1341 *--p = '#';
1342 *--p = '0' + base%10;
1343 if (base > 10)
1344 *--p = '0' + base/10;
1345 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001346 if (sign)
1347 *--p = sign;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001348 if (p != PyString_AS_STRING(str)) {
1349 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001350 assert(p > q);
1351 do {
1352 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001353 q--;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001354 _PyString_Resize((PyObject **)&str,
1355 (Py_ssize_t) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001356 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001357 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001358}
1359
Tim Petersda53afa2006-05-25 17:34:03 +00001360/* Table of digit values for 8-bit string -> integer conversion.
1361 * '0' maps to 0, ..., '9' maps to 9.
1362 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1363 * All other indices map to 37.
1364 * Note that when converting a base B string, a char c is a legitimate
1365 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1366 */
1367int _PyLong_DigitValue[256] = {
Tim Peters696cf432006-05-24 21:10:40 +00001368 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 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1372 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1373 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1374 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1375 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1376 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1377 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1378 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1379 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1380 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1381 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1382 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1383 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Tim Peters696cf432006-05-24 21:10:40 +00001384};
1385
1386/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001387 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1388 * non-digit (which may be *str!). A normalized long is returned.
1389 * The point to this routine is that it takes time linear in the number of
1390 * string characters.
1391 */
1392static PyLongObject *
1393long_from_binary_base(char **str, int base)
1394{
1395 char *p = *str;
1396 char *start = p;
1397 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001398 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001399 PyLongObject *z;
1400 twodigits accum;
1401 int bits_in_accum;
1402 digit *pdigit;
1403
1404 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1405 n = base;
1406 for (bits_per_char = -1; n; ++bits_per_char)
1407 n >>= 1;
1408 /* n <- total # of bits needed, while setting p to end-of-string */
1409 n = 0;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001410 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001411 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001412 *str = p;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001413 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1414 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001415 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001416 PyErr_SetString(PyExc_ValueError,
1417 "long string too large to convert");
1418 return NULL;
1419 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001420 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001421 z = _PyLong_New(n);
1422 if (z == NULL)
1423 return NULL;
1424 /* Read string from right, and fill in long from left; i.e.,
1425 * from least to most significant in both.
1426 */
1427 accum = 0;
1428 bits_in_accum = 0;
1429 pdigit = z->ob_digit;
1430 while (--p >= start) {
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001431 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001432 assert(k >= 0 && k < base);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001433 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001434 bits_in_accum += bits_per_char;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001435 if (bits_in_accum >= PyLong_SHIFT) {
1436 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001437 assert(pdigit - z->ob_digit <= n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001438 accum >>= PyLong_SHIFT;
1439 bits_in_accum -= PyLong_SHIFT;
1440 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001441 }
1442 }
1443 if (bits_in_accum) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001444 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001445 *pdigit++ = (digit)accum;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001446 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001447 }
1448 while (pdigit - z->ob_digit < n)
1449 *pdigit++ = 0;
1450 return long_normalize(z);
1451}
1452
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001453PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001454PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001455{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001456 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001457 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001458 PyLongObject *z;
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001459 PyObject *strobj, *strrepr;
1460 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001461
Guido van Rossum472c04f1996-12-05 21:57:21 +00001462 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001463 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001464 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001465 return NULL;
1466 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001467 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001468 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001469 if (*str == '+')
1470 ++str;
1471 else if (*str == '-') {
1472 ++str;
1473 sign = -1;
1474 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001475 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001476 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001477 if (base == 0) {
Eric Smith9ff19b52008-03-17 17:32:20 +00001478 /* No base given. Deduce the base from the contents
1479 of the string */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001480 if (str[0] != '0')
1481 base = 10;
1482 else if (str[1] == 'x' || str[1] == 'X')
1483 base = 16;
Eric Smith9ff19b52008-03-17 17:32:20 +00001484 else if (str[1] == 'o' || str[1] == 'O')
1485 base = 8;
1486 else if (str[1] == 'b' || str[1] == 'B')
1487 base = 2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001488 else
Eric Smith9ff19b52008-03-17 17:32:20 +00001489 /* "old" (C-style) octal literal, still valid in
1490 2.x, although illegal in 3.x */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001491 base = 8;
1492 }
Eric Smith9ff19b52008-03-17 17:32:20 +00001493 /* Whether or not we were deducing the base, skip leading chars
1494 as needed */
1495 if (str[0] == '0' &&
1496 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1497 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1498 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001499 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001500
Guido van Rossume6762971998-06-22 03:54:46 +00001501 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001502 if ((base & (base - 1)) == 0)
1503 z = long_from_binary_base(&str, base);
1504 else {
Tim Peters696cf432006-05-24 21:10:40 +00001505/***
1506Binary bases can be converted in time linear in the number of digits, because
1507Python's representation base is binary. Other bases (including decimal!) use
1508the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001509
Tim Peters696cf432006-05-24 21:10:40 +00001510First some math: the largest integer that can be expressed in N base-B digits
1511is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1512case number of Python digits needed to hold it is the smallest integer n s.t.
1513
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001514 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1515 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1516 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001517
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001518The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
Tim Peters696cf432006-05-24 21:10:40 +00001519this quickly. A Python long with that much space is reserved near the start,
1520and the result is computed into it.
1521
1522The input string is actually treated as being in base base**i (i.e., i digits
1523are processed at a time), where two more static arrays hold:
1524
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001525 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
Tim Peters696cf432006-05-24 21:10:40 +00001526 convmultmax_base[base] = base ** convwidth_base[base]
1527
1528The first of these is the largest i such that i consecutive input digits
1529must fit in a single Python digit. The second is effectively the input
1530base we're really using.
1531
1532Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1533convmultmax_base[base], the result is "simply"
1534
1535 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1536
1537where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001538
1539Error analysis: as above, the number of Python digits `n` needed is worst-
1540case
1541
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001542 n >= N * log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001543
1544where `N` is the number of input digits in base `B`. This is computed via
1545
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001546 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001547
1548below. Two numeric concerns are how much space this can waste, and whether
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001549the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
Tim Peters9faa3ed2006-05-30 15:53:34 +00001550which is the default (and it's unlikely anyone changes that).
1551
1552Waste isn't a problem: provided the first input digit isn't 0, the difference
1553between the worst-case input with N digits and the smallest input with N
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001554digits is about a factor of B, but B is small compared to PyLong_BASE so at most
Tim Peters9faa3ed2006-05-30 15:53:34 +00001555one allocated Python digit can remain unused on that count. If
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001556N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001557and adding 1 returns a result 1 larger than necessary. However, that can't
1558happen: whenever B is a power of 2, long_from_binary_base() is called
1559instead, and it's impossible for B**i to be an integer power of 2**15 when
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001560B is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be
Tim Peters9faa3ed2006-05-30 15:53:34 +00001561an exact integer when B is not a power of 2, since B**i has a prime factor
1562other than 2 in that case, but (2**15)**j's only prime factor is 2).
1563
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001564The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001565is a little bit larger than an exact integer, but due to roundoff errors (in
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001566computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001567yields a numeric result a little less than that integer. Unfortunately, "how
1568close can a transcendental function get to an integer over some range?"
1569questions are generally theoretically intractable. Computer analysis via
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001570continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
Tim Peters9faa3ed2006-05-30 15:53:34 +00001571fractions, giving a sequence i/j of "the best" rational approximations. Then
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001572j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001573we can get very close to being in trouble, but very rarely. For example,
157476573 is a denominator in one of the continued-fraction approximations to
1575log(10)/log(2**15), and indeed:
1576
1577 >>> log(10)/log(2**15)*76573
1578 16958.000000654003
1579
1580is very close to an integer. If we were working with IEEE single-precision,
1581rounding errors could kill us. Finding worst cases in IEEE double-precision
1582requires better-than-double-precision log() functions, and Tim didn't bother.
1583Instead the code checks to see whether the allocated space is enough as each
1584new Python digit is added, and copies the whole thing to a larger long if not.
1585This should happen extremely rarely, and in fact I don't have a test case
1586that triggers it(!). Instead the code was tested by artificially allocating
1587just 1 digit at the start, so that the copying code was exercised for every
1588digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001589***/
1590 register twodigits c; /* current input character */
1591 Py_ssize_t size_z;
1592 int i;
1593 int convwidth;
1594 twodigits convmultmax, convmult;
1595 digit *pz, *pzstop;
1596 char* scan;
1597
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001598 static double log_base_PyLong_BASE[37] = {0.0e0,};
Tim Peters696cf432006-05-24 21:10:40 +00001599 static int convwidth_base[37] = {0,};
1600 static twodigits convmultmax_base[37] = {0,};
1601
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001602 if (log_base_PyLong_BASE[base] == 0.0) {
Tim Peters696cf432006-05-24 21:10:40 +00001603 twodigits convmax = base;
1604 int i = 1;
1605
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001606 log_base_PyLong_BASE[base] = log((double)base) /
1607 log((double)PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001608 for (;;) {
1609 twodigits next = convmax * base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001610 if (next > PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001611 break;
1612 convmax = next;
1613 ++i;
1614 }
1615 convmultmax_base[base] = convmax;
1616 assert(i > 0);
1617 convwidth_base[base] = i;
1618 }
1619
1620 /* Find length of the string of numeric characters. */
1621 scan = str;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001622 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Tim Peters696cf432006-05-24 21:10:40 +00001623 ++scan;
1624
1625 /* Create a long object that can contain the largest possible
1626 * integer with this base and length. Note that there's no
1627 * need to initialize z->ob_digit -- no slot is read up before
1628 * being stored into.
1629 */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001630 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001631 /* Uncomment next line to test exceedingly rare copy code */
1632 /* size_z = 1; */
Tim Peters696cf432006-05-24 21:10:40 +00001633 assert(size_z > 0);
1634 z = _PyLong_New(size_z);
1635 if (z == NULL)
1636 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00001637 Py_SIZE(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001638
1639 /* `convwidth` consecutive input digits are treated as a single
1640 * digit in base `convmultmax`.
1641 */
1642 convwidth = convwidth_base[base];
1643 convmultmax = convmultmax_base[base];
1644
1645 /* Work ;-) */
1646 while (str < scan) {
1647 /* grab up to convwidth digits from the input string */
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001648 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Tim Peters696cf432006-05-24 21:10:40 +00001649 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1650 c = (twodigits)(c * base +
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001651 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001652 assert(c < PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001653 }
1654
1655 convmult = convmultmax;
1656 /* Calculate the shift only if we couldn't get
1657 * convwidth digits.
1658 */
1659 if (i != convwidth) {
1660 convmult = base;
1661 for ( ; i > 1; --i)
1662 convmult *= base;
1663 }
1664
1665 /* Multiply z by convmult, and add c. */
1666 pz = z->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +00001667 pzstop = pz + Py_SIZE(z);
Tim Peters696cf432006-05-24 21:10:40 +00001668 for (; pz < pzstop; ++pz) {
1669 c += (twodigits)*pz * convmult;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001670 *pz = (digit)(c & PyLong_MASK);
1671 c >>= PyLong_SHIFT;
Tim Peters696cf432006-05-24 21:10:40 +00001672 }
1673 /* carry off the current end? */
1674 if (c) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001675 assert(c < PyLong_BASE);
Christian Heimese93237d2007-12-19 02:37:44 +00001676 if (Py_SIZE(z) < size_z) {
Tim Peters9faa3ed2006-05-30 15:53:34 +00001677 *pz = (digit)c;
Christian Heimese93237d2007-12-19 02:37:44 +00001678 ++Py_SIZE(z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001679 }
1680 else {
1681 PyLongObject *tmp;
1682 /* Extremely rare. Get more space. */
Christian Heimese93237d2007-12-19 02:37:44 +00001683 assert(Py_SIZE(z) == size_z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001684 tmp = _PyLong_New(size_z + 1);
1685 if (tmp == NULL) {
1686 Py_DECREF(z);
1687 return NULL;
1688 }
1689 memcpy(tmp->ob_digit,
1690 z->ob_digit,
1691 sizeof(digit) * size_z);
1692 Py_DECREF(z);
1693 z = tmp;
1694 z->ob_digit[size_z] = (digit)c;
1695 ++size_z;
1696 }
Tim Peters696cf432006-05-24 21:10:40 +00001697 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001698 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001699 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001700 if (z == NULL)
1701 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001702 if (str == start)
1703 goto onError;
Tim Peters696cf432006-05-24 21:10:40 +00001704 if (sign < 0)
Christian Heimese93237d2007-12-19 02:37:44 +00001705 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001706 if (*str == 'L' || *str == 'l')
1707 str++;
1708 while (*str && isspace(Py_CHARMASK(*str)))
1709 str++;
1710 if (*str != '\0')
1711 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001712 if (pend)
1713 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001714 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001715
1716 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001717 Py_XDECREF(z);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001718 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001719 strobj = PyString_FromStringAndSize(orig_str, slen);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001720 if (strobj == NULL)
1721 return NULL;
1722 strrepr = PyObject_Repr(strobj);
1723 Py_DECREF(strobj);
1724 if (strrepr == NULL)
1725 return NULL;
1726 PyErr_Format(PyExc_ValueError,
1727 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001728 base, PyString_AS_STRING(strrepr));
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001729 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001730 return NULL;
1731}
1732
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001733#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001734PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001735PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001736{
Walter Dörwald07e14762002-11-06 16:15:14 +00001737 PyObject *result;
Anthony Baxter377be112006-04-11 06:54:30 +00001738 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001739
Walter Dörwald07e14762002-11-06 16:15:14 +00001740 if (buffer == NULL)
1741 return NULL;
1742
1743 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1744 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001745 return NULL;
1746 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001747 result = PyLong_FromString(buffer, NULL, base);
1748 PyMem_FREE(buffer);
1749 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001750}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001751#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001752
Tim Peters9f688bf2000-07-07 15:53:28 +00001753/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001754static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001755 (PyLongObject *, PyLongObject *, PyLongObject **);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001756static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001757
1758/* Long division with remainder, top-level routine */
1759
Guido van Rossume32e0141992-01-19 16:31:05 +00001760static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001761long_divrem(PyLongObject *a, PyLongObject *b,
1762 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001763{
Christian Heimese93237d2007-12-19 02:37:44 +00001764 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001765 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001766
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001767 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001768 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001769 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001770 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001771 }
1772 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001773 (size_a == size_b &&
1774 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001775 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001776 *pdiv = _PyLong_New(0);
Georg Brandlc02e1312007-04-11 17:16:24 +00001777 if (*pdiv == NULL)
1778 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001779 Py_INCREF(a);
1780 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001781 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001782 }
1783 if (size_b == 1) {
1784 digit rem = 0;
1785 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001786 if (z == NULL)
1787 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001788 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Georg Brandlc02e1312007-04-11 17:16:24 +00001789 if (*prem == NULL) {
1790 Py_DECREF(z);
1791 return -1;
1792 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001793 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001794 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001795 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001796 if (z == NULL)
1797 return -1;
1798 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001799 /* Set the signs.
1800 The quotient z has the sign of a*b;
1801 the remainder r has the sign of a,
1802 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001803 if ((a->ob_size < 0) != (b->ob_size < 0))
1804 z->ob_size = -(z->ob_size);
1805 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1806 (*prem)->ob_size = -((*prem)->ob_size);
1807 *pdiv = z;
1808 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001809}
1810
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001811/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001812
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001813static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001814x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001815{
Christian Heimese93237d2007-12-19 02:37:44 +00001816 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001817 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001818 PyLongObject *v = mul1(v1, d);
1819 PyLongObject *w = mul1(w1, d);
1820 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001821 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001822
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001823 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001824 Py_XDECREF(v);
1825 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001826 return NULL;
1827 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001828
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001829 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimese93237d2007-12-19 02:37:44 +00001830 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
1831 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001832
Christian Heimese93237d2007-12-19 02:37:44 +00001833 size_v = ABS(Py_SIZE(v));
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001834 k = size_v - size_w;
1835 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001836
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001837 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001838 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1839 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001840 stwodigits carry = 0;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001841 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001842
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001843 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001844 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001845 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001846 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001847 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001848 if (vj == w->ob_digit[size_w-1])
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001849 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001850 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001851 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001852 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001853
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001854 while (w->ob_digit[size_w-2]*q >
1855 ((
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001856 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001857 + v->ob_digit[j-1]
1858 - q*w->ob_digit[size_w-1]
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001859 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001860 + v->ob_digit[j-2])
1861 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001862
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001863 for (i = 0; i < size_w && i+k < size_v; ++i) {
1864 twodigits z = w->ob_digit[i] * q;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001865 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001866 carry += v->ob_digit[i+k] - z
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001867 + ((twodigits)zz << PyLong_SHIFT);
1868 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
1869 carry = Py_ARITHMETIC_RIGHT_SHIFT(PyLong_BASE_TWODIGITS_TYPE,
1870 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00001871 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001872 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001873
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001874 if (i+k < size_v) {
1875 carry += v->ob_digit[i+k];
1876 v->ob_digit[i+k] = 0;
1877 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001878
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001879 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001880 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001881 else {
1882 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001883 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001884 carry = 0;
1885 for (i = 0; i < size_w && i+k < size_v; ++i) {
1886 carry += v->ob_digit[i+k] + w->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001887 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001888 carry = Py_ARITHMETIC_RIGHT_SHIFT(
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001889 PyLong_BASE_TWODIGITS_TYPE,
1890 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001891 }
1892 }
1893 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001894
Guido van Rossumc206c761995-01-10 15:23:19 +00001895 if (a == NULL)
1896 *prem = NULL;
1897 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001898 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001899 *prem = divrem1(v, d, &d);
1900 /* d receives the (unused) remainder */
1901 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001902 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001903 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001904 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001905 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001906 Py_DECREF(v);
1907 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001908 return a;
1909}
1910
1911/* Methods */
1912
1913static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001914long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001915{
Christian Heimese93237d2007-12-19 02:37:44 +00001916 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001917}
1918
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001919static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001920long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001921{
Eric Smith5e527eb2008-02-10 01:36:53 +00001922 return _PyLong_Format(v, 10, 1, 0);
Fred Drake121ee271999-12-23 15:41:28 +00001923}
1924
1925static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001926long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001927{
Eric Smith5e527eb2008-02-10 01:36:53 +00001928 return _PyLong_Format(v, 10, 0, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001929}
1930
1931static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001932long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001933{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001934 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001935
Christian Heimese93237d2007-12-19 02:37:44 +00001936 if (Py_SIZE(a) != Py_SIZE(b)) {
1937 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001938 sign = 0;
1939 else
Christian Heimese93237d2007-12-19 02:37:44 +00001940 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001941 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001942 else {
Christian Heimese93237d2007-12-19 02:37:44 +00001943 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001944 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1945 ;
1946 if (i < 0)
1947 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001948 else {
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00001949 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimese93237d2007-12-19 02:37:44 +00001950 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001951 sign = -sign;
1952 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001953 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001954 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001955}
1956
Guido van Rossum9bfef441993-03-29 10:43:31 +00001957static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001958long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001959{
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00001960 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001961 Py_ssize_t i;
1962 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001963
1964 /* This is designed so that Python ints and longs with the
1965 same value hash to the same value, otherwise comparisons
1966 of mapping keys will turn out weird */
1967 i = v->ob_size;
1968 sign = 1;
1969 x = 0;
1970 if (i < 0) {
1971 sign = -1;
1972 i = -(i);
1973 }
Mark Dickinsona0eae032009-01-26 21:40:08 +00001974 /* The following loop produces a C unsigned long x such that x is
1975 congruent to the absolute value of v modulo ULONG_MAX. The
1976 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00001977 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001978 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00001979 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001980 x += v->ob_digit[i];
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00001981 /* If the addition above overflowed we compensate by
1982 incrementing. This preserves the value modulo
1983 ULONG_MAX. */
1984 if (x < v->ob_digit[i])
Facundo Batistad544df72007-09-19 15:10:06 +00001985 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001986 }
1987 x = x * sign;
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00001988 if (x == (unsigned long)-1)
1989 x = (unsigned long)-2;
1990 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001991}
1992
1993
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001994/* Add the absolute values of two long integers. */
1995
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001996static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001997x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001998{
Christian Heimese93237d2007-12-19 02:37:44 +00001999 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002000 PyLongObject *z;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00002001 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002002 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002003
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004 /* Ensure a is the larger of the two: */
2005 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002006 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002007 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002008 size_a = size_b;
2009 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002010 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002011 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002012 if (z == NULL)
2013 return NULL;
2014 for (i = 0; i < size_b; ++i) {
2015 carry += a->ob_digit[i] + b->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002016 z->ob_digit[i] = carry & PyLong_MASK;
2017 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002018 }
2019 for (; i < size_a; ++i) {
2020 carry += a->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002021 z->ob_digit[i] = carry & PyLong_MASK;
2022 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002023 }
2024 z->ob_digit[i] = carry;
2025 return long_normalize(z);
2026}
2027
2028/* Subtract the absolute values of two integers. */
2029
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002030static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002031x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002032{
Christian Heimese93237d2007-12-19 02:37:44 +00002033 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002034 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002035 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002036 int sign = 1;
2037 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002038
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002039 /* Ensure a is the larger of the two: */
2040 if (size_a < size_b) {
2041 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002042 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002043 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002044 size_a = size_b;
2045 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002046 }
2047 else if (size_a == size_b) {
2048 /* Find highest digit where a and b differ: */
2049 i = size_a;
2050 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2051 ;
2052 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002053 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002054 if (a->ob_digit[i] < b->ob_digit[i]) {
2055 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002056 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057 }
2058 size_a = size_b = i+1;
2059 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002060 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002061 if (z == NULL)
2062 return NULL;
2063 for (i = 0; i < size_b; ++i) {
2064 /* The following assumes unsigned arithmetic
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002065 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002066 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002067 z->ob_digit[i] = borrow & PyLong_MASK;
2068 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002069 borrow &= 1; /* Keep only one sign bit */
2070 }
2071 for (; i < size_a; ++i) {
2072 borrow = a->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002073 z->ob_digit[i] = borrow & PyLong_MASK;
2074 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002075 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002076 }
2077 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002078 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002079 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002080 return long_normalize(z);
2081}
2082
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002083static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002084long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002085{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002086 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002087
Neil Schemenauerba872e22001-01-04 01:46:03 +00002088 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2089
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090 if (a->ob_size < 0) {
2091 if (b->ob_size < 0) {
2092 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002093 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002094 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002095 }
2096 else
2097 z = x_sub(b, a);
2098 }
2099 else {
2100 if (b->ob_size < 0)
2101 z = x_sub(a, b);
2102 else
2103 z = x_add(a, b);
2104 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002105 Py_DECREF(a);
2106 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002107 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002108}
2109
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002110static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002111long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002112{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002113 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002114
Neil Schemenauerba872e22001-01-04 01:46:03 +00002115 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2116
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002117 if (a->ob_size < 0) {
2118 if (b->ob_size < 0)
2119 z = x_sub(a, b);
2120 else
2121 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002122 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002123 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002124 }
2125 else {
2126 if (b->ob_size < 0)
2127 z = x_add(a, b);
2128 else
2129 z = x_sub(a, b);
2130 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002131 Py_DECREF(a);
2132 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002133 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002134}
2135
Tim Peters5af4e6c2002-08-12 02:31:19 +00002136/* Grade school multiplication, ignoring the signs.
2137 * Returns the absolute value of the product, or NULL if error.
2138 */
2139static PyLongObject *
2140x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002141{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002142 PyLongObject *z;
Christian Heimese93237d2007-12-19 02:37:44 +00002143 Py_ssize_t size_a = ABS(Py_SIZE(a));
2144 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002145 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002146
Tim Peters5af4e6c2002-08-12 02:31:19 +00002147 z = _PyLong_New(size_a + size_b);
2148 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002149 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002150
Christian Heimese93237d2007-12-19 02:37:44 +00002151 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002152 if (a == b) {
2153 /* Efficient squaring per HAC, Algorithm 14.16:
2154 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2155 * Gives slightly less than a 2x speedup when a == b,
2156 * via exploiting that each entry in the multiplication
2157 * pyramid appears twice (except for the size_a squares).
2158 */
2159 for (i = 0; i < size_a; ++i) {
2160 twodigits carry;
2161 twodigits f = a->ob_digit[i];
2162 digit *pz = z->ob_digit + (i << 1);
2163 digit *pa = a->ob_digit + i + 1;
2164 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002165
Tim Peters0973b992004-08-29 22:16:50 +00002166 SIGCHECK({
2167 Py_DECREF(z);
2168 return NULL;
2169 })
2170
2171 carry = *pz + f * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002172 *pz++ = (digit)(carry & PyLong_MASK);
2173 carry >>= PyLong_SHIFT;
2174 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002175
2176 /* Now f is added in twice in each column of the
2177 * pyramid it appears. Same as adding f<<1 once.
2178 */
2179 f <<= 1;
2180 while (pa < paend) {
2181 carry += *pz + *pa++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002182 *pz++ = (digit)(carry & PyLong_MASK);
2183 carry >>= PyLong_SHIFT;
2184 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002185 }
2186 if (carry) {
2187 carry += *pz;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002188 *pz++ = (digit)(carry & PyLong_MASK);
2189 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002190 }
2191 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002192 *pz += (digit)(carry & PyLong_MASK);
2193 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002194 }
Tim Peters0973b992004-08-29 22:16:50 +00002195 }
2196 else { /* a is not the same as b -- gradeschool long mult */
2197 for (i = 0; i < size_a; ++i) {
2198 twodigits carry = 0;
2199 twodigits f = a->ob_digit[i];
2200 digit *pz = z->ob_digit + i;
2201 digit *pb = b->ob_digit;
2202 digit *pbend = b->ob_digit + size_b;
2203
2204 SIGCHECK({
2205 Py_DECREF(z);
2206 return NULL;
2207 })
2208
2209 while (pb < pbend) {
2210 carry += *pz + *pb++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002211 *pz++ = (digit)(carry & PyLong_MASK);
2212 carry >>= PyLong_SHIFT;
2213 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002214 }
2215 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002216 *pz += (digit)(carry & PyLong_MASK);
2217 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002218 }
2219 }
Tim Peters44121a62002-08-12 06:17:58 +00002220 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002221}
2222
2223/* A helper for Karatsuba multiplication (k_mul).
2224 Takes a long "n" and an integer "size" representing the place to
2225 split, and sets low and high such that abs(n) == (high << size) + low,
2226 viewing the shift as being by digits. The sign bit is ignored, and
2227 the return values are >= 0.
2228 Returns 0 on success, -1 on failure.
2229*/
2230static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002231kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002232{
2233 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002234 Py_ssize_t size_lo, size_hi;
Christian Heimese93237d2007-12-19 02:37:44 +00002235 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002236
2237 size_lo = MIN(size_n, size);
2238 size_hi = size_n - size_lo;
2239
2240 if ((hi = _PyLong_New(size_hi)) == NULL)
2241 return -1;
2242 if ((lo = _PyLong_New(size_lo)) == NULL) {
2243 Py_DECREF(hi);
2244 return -1;
2245 }
2246
2247 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2248 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2249
2250 *high = long_normalize(hi);
2251 *low = long_normalize(lo);
2252 return 0;
2253}
2254
Tim Peters60004642002-08-12 22:01:34 +00002255static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2256
Tim Peters5af4e6c2002-08-12 02:31:19 +00002257/* Karatsuba multiplication. Ignores the input signs, and returns the
2258 * absolute value of the product (or NULL if error).
2259 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2260 */
2261static PyLongObject *
2262k_mul(PyLongObject *a, PyLongObject *b)
2263{
Christian Heimese93237d2007-12-19 02:37:44 +00002264 Py_ssize_t asize = ABS(Py_SIZE(a));
2265 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002266 PyLongObject *ah = NULL;
2267 PyLongObject *al = NULL;
2268 PyLongObject *bh = NULL;
2269 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002270 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002271 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002272 Py_ssize_t shift; /* the number of digits we split off */
2273 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002274
Tim Peters5af4e6c2002-08-12 02:31:19 +00002275 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2276 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2277 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002278 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002279 * By picking X to be a power of 2, "*X" is just shifting, and it's
2280 * been reduced to 3 multiplies on numbers half the size.
2281 */
2282
Tim Petersfc07e562002-08-12 02:54:10 +00002283 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002284 * is largest.
2285 */
Tim Peters738eda72002-08-12 15:08:20 +00002286 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002287 t1 = a;
2288 a = b;
2289 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002290
2291 i = asize;
2292 asize = bsize;
2293 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002294 }
2295
2296 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002297 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2298 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002299 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002300 return _PyLong_New(0);
2301 else
2302 return x_mul(a, b);
2303 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002304
Tim Peters60004642002-08-12 22:01:34 +00002305 /* If a is small compared to b, splitting on b gives a degenerate
2306 * case with ah==0, and Karatsuba may be (even much) less efficient
2307 * than "grade school" then. However, we can still win, by viewing
2308 * b as a string of "big digits", each of width a->ob_size. That
2309 * leads to a sequence of balanced calls to k_mul.
2310 */
2311 if (2 * asize <= bsize)
2312 return k_lopsided_mul(a, b);
2313
Tim Petersd6974a52002-08-13 20:37:51 +00002314 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002315 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002316 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002317 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002318
Tim Peters0973b992004-08-29 22:16:50 +00002319 if (a == b) {
2320 bh = ah;
2321 bl = al;
2322 Py_INCREF(bh);
2323 Py_INCREF(bl);
2324 }
2325 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002326
Tim Petersd64c1de2002-08-12 17:36:03 +00002327 /* The plan:
2328 * 1. Allocate result space (asize + bsize digits: that's always
2329 * enough).
2330 * 2. Compute ah*bh, and copy into result at 2*shift.
2331 * 3. Compute al*bl, and copy into result at 0. Note that this
2332 * can't overlap with #2.
2333 * 4. Subtract al*bl from the result, starting at shift. This may
2334 * underflow (borrow out of the high digit), but we don't care:
2335 * we're effectively doing unsigned arithmetic mod
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002336 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
Tim Petersd64c1de2002-08-12 17:36:03 +00002337 * borrows and carries out of the high digit can be ignored.
2338 * 5. Subtract ah*bh from the result, starting at shift.
2339 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2340 * at shift.
2341 */
2342
2343 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002344 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002345 if (ret == NULL) goto fail;
2346#ifdef Py_DEBUG
2347 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002348 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002349#endif
Tim Peters44121a62002-08-12 06:17:58 +00002350
Tim Petersd64c1de2002-08-12 17:36:03 +00002351 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002352 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002353 assert(Py_SIZE(t1) >= 0);
2354 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002355 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimese93237d2007-12-19 02:37:44 +00002356 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002357
2358 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimese93237d2007-12-19 02:37:44 +00002359 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002360 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002361 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002362 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002363
Tim Petersd64c1de2002-08-12 17:36:03 +00002364 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002365 if ((t2 = k_mul(al, bl)) == NULL) {
2366 Py_DECREF(t1);
2367 goto fail;
2368 }
Christian Heimese93237d2007-12-19 02:37:44 +00002369 assert(Py_SIZE(t2) >= 0);
2370 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2371 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002372
2373 /* Zero out remaining digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002374 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002375 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002376 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002377
Tim Petersd64c1de2002-08-12 17:36:03 +00002378 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2379 * because it's fresher in cache.
2380 */
Christian Heimese93237d2007-12-19 02:37:44 +00002381 i = Py_SIZE(ret) - shift; /* # digits after shift */
2382 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002383 Py_DECREF(t2);
2384
Christian Heimese93237d2007-12-19 02:37:44 +00002385 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002386 Py_DECREF(t1);
2387
Tim Petersd64c1de2002-08-12 17:36:03 +00002388 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002389 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2390 Py_DECREF(ah);
2391 Py_DECREF(al);
2392 ah = al = NULL;
2393
Tim Peters0973b992004-08-29 22:16:50 +00002394 if (a == b) {
2395 t2 = t1;
2396 Py_INCREF(t2);
2397 }
2398 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002399 Py_DECREF(t1);
2400 goto fail;
2401 }
2402 Py_DECREF(bh);
2403 Py_DECREF(bl);
2404 bh = bl = NULL;
2405
Tim Peters738eda72002-08-12 15:08:20 +00002406 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002407 Py_DECREF(t1);
2408 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002409 if (t3 == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002410 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002411
Tim Petersd6974a52002-08-13 20:37:51 +00002412 /* Add t3. It's not obvious why we can't run out of room here.
2413 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002414 */
Christian Heimese93237d2007-12-19 02:37:44 +00002415 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002416 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002417
Tim Peters5af4e6c2002-08-12 02:31:19 +00002418 return long_normalize(ret);
2419
2420 fail:
2421 Py_XDECREF(ret);
2422 Py_XDECREF(ah);
2423 Py_XDECREF(al);
2424 Py_XDECREF(bh);
2425 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002426 return NULL;
2427}
2428
Tim Petersd6974a52002-08-13 20:37:51 +00002429/* (*) Why adding t3 can't "run out of room" above.
2430
Tim Petersab86c2b2002-08-15 20:06:00 +00002431Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2432to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002433
Tim Petersab86c2b2002-08-15 20:06:00 +000024341. For any integer i, i = c(i/2) + f(i/2). In particular,
2435 bsize = c(bsize/2) + f(bsize/2).
24362. shift = f(bsize/2)
24373. asize <= bsize
24384. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2439 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002440
Tim Petersab86c2b2002-08-15 20:06:00 +00002441We allocated asize + bsize result digits, and add t3 into them at an offset
2442of shift. This leaves asize+bsize-shift allocated digit positions for t3
2443to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2444asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002445
Tim Petersab86c2b2002-08-15 20:06:00 +00002446bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2447at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002448
Tim Petersab86c2b2002-08-15 20:06:00 +00002449If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2450digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2451most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002452
Tim Petersab86c2b2002-08-15 20:06:00 +00002453The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002454
Tim Petersab86c2b2002-08-15 20:06:00 +00002455 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002456
Tim Petersab86c2b2002-08-15 20:06:00 +00002457and we have asize + c(bsize/2) available digit positions. We need to show
2458this is always enough. An instance of c(bsize/2) cancels out in both, so
2459the question reduces to whether asize digits is enough to hold
2460(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2461then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2462asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002463digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002464asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002465c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2466is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2467bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002468
Tim Peters48d52c02002-08-14 17:07:32 +00002469Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2470clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2471ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002472*/
2473
Tim Peters60004642002-08-12 22:01:34 +00002474/* b has at least twice the digits of a, and a is big enough that Karatsuba
2475 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2476 * of slices, each with a->ob_size digits, and multiply the slices by a,
2477 * one at a time. This gives k_mul balanced inputs to work with, and is
2478 * also cache-friendly (we compute one double-width slice of the result
2479 * at a time, then move on, never bactracking except for the helpful
2480 * single-width slice overlap between successive partial sums).
2481 */
2482static PyLongObject *
2483k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2484{
Christian Heimese93237d2007-12-19 02:37:44 +00002485 const Py_ssize_t asize = ABS(Py_SIZE(a));
2486 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002487 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002488 PyLongObject *ret;
2489 PyLongObject *bslice = NULL;
2490
2491 assert(asize > KARATSUBA_CUTOFF);
2492 assert(2 * asize <= bsize);
2493
2494 /* Allocate result space, and zero it out. */
2495 ret = _PyLong_New(asize + bsize);
2496 if (ret == NULL)
2497 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002498 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002499
2500 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002501 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002502 if (bslice == NULL)
2503 goto fail;
2504
2505 nbdone = 0;
2506 while (bsize > 0) {
2507 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002508 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002509
2510 /* Multiply the next slice of b by a. */
2511 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2512 nbtouse * sizeof(digit));
Christian Heimese93237d2007-12-19 02:37:44 +00002513 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002514 product = k_mul(a, bslice);
2515 if (product == NULL)
2516 goto fail;
2517
2518 /* Add into result. */
Christian Heimese93237d2007-12-19 02:37:44 +00002519 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2520 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002521 Py_DECREF(product);
2522
2523 bsize -= nbtouse;
2524 nbdone += nbtouse;
2525 }
2526
2527 Py_DECREF(bslice);
2528 return long_normalize(ret);
2529
2530 fail:
2531 Py_DECREF(ret);
2532 Py_XDECREF(bslice);
2533 return NULL;
2534}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002535
2536static PyObject *
2537long_mul(PyLongObject *v, PyLongObject *w)
2538{
2539 PyLongObject *a, *b, *z;
2540
2541 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002542 Py_INCREF(Py_NotImplemented);
2543 return Py_NotImplemented;
2544 }
2545
Tim Petersd64c1de2002-08-12 17:36:03 +00002546 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002547 /* Negate if exactly one of the inputs is negative. */
2548 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002549 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002550 Py_DECREF(a);
2551 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002552 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002553}
2554
Guido van Rossume32e0141992-01-19 16:31:05 +00002555/* The / and % operators are now defined in terms of divmod().
2556 The expression a mod b has the value a - b*floor(a/b).
2557 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002558 |a| by |b|, with the sign of a. This is also expressed
2559 as a - b*trunc(a/b), if trunc truncates towards zero.
2560 Some examples:
2561 a b a rem b a mod b
2562 13 10 3 3
2563 -13 10 -3 7
2564 13 -10 3 -7
2565 -13 -10 -3 -3
2566 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002567 have different signs. We then subtract one from the 'div'
2568 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002569
Tim Peters47e52ee2004-08-30 02:44:38 +00002570/* Compute
2571 * *pdiv, *pmod = divmod(v, w)
2572 * NULL can be passed for pdiv or pmod, in which case that part of
2573 * the result is simply thrown away. The caller owns a reference to
2574 * each of these it requests (does not pass NULL for).
2575 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002576static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002577l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002578 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002579{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002580 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002581
Guido van Rossume32e0141992-01-19 16:31:05 +00002582 if (long_divrem(v, w, &div, &mod) < 0)
2583 return -1;
Christian Heimese93237d2007-12-19 02:37:44 +00002584 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2585 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002586 PyLongObject *temp;
2587 PyLongObject *one;
2588 temp = (PyLongObject *) long_add(mod, w);
2589 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002590 mod = temp;
2591 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002592 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002593 return -1;
2594 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002595 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002596 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002597 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2598 Py_DECREF(mod);
2599 Py_DECREF(div);
2600 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002601 return -1;
2602 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002603 Py_DECREF(one);
2604 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002605 div = temp;
2606 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002607 if (pdiv != NULL)
2608 *pdiv = div;
2609 else
2610 Py_DECREF(div);
2611
2612 if (pmod != NULL)
2613 *pmod = mod;
2614 else
2615 Py_DECREF(mod);
2616
Guido van Rossume32e0141992-01-19 16:31:05 +00002617 return 0;
2618}
2619
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002620static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002621long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002622{
Tim Peters47e52ee2004-08-30 02:44:38 +00002623 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002624
2625 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002626 if (l_divmod(a, b, &div, NULL) < 0)
2627 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002628 Py_DECREF(a);
2629 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002630 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002631}
2632
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002633static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002634long_classic_div(PyObject *v, PyObject *w)
2635{
Tim Peters47e52ee2004-08-30 02:44:38 +00002636 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002637
2638 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002639 if (Py_DivisionWarningFlag &&
2640 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2641 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002642 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002643 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002644 Py_DECREF(a);
2645 Py_DECREF(b);
2646 return (PyObject *)div;
2647}
2648
2649static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002650long_true_divide(PyObject *v, PyObject *w)
2651{
Tim Peterse2a60002001-09-04 06:17:36 +00002652 PyLongObject *a, *b;
2653 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002654 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002655
2656 CONVERT_BINOP(v, w, &a, &b);
2657 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2658 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002659 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2660 Py_DECREF(a);
2661 Py_DECREF(b);
2662 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002663 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002664 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2665 but should really be set correctly after sucessful calls to
2666 _PyLong_AsScaledDouble() */
2667 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002668
2669 if (bd == 0.0) {
2670 PyErr_SetString(PyExc_ZeroDivisionError,
2671 "long division or modulo by zero");
2672 return NULL;
2673 }
2674
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002675 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002676 ad /= bd; /* overflow/underflow impossible here */
2677 aexp -= bexp;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002678 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002679 goto overflow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002680 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002681 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002682 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002683 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002684 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002685 goto overflow;
2686 return PyFloat_FromDouble(ad);
2687
2688overflow:
2689 PyErr_SetString(PyExc_OverflowError,
2690 "long/long too large for a float");
2691 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002692
Tim Peters20dab9f2001-09-04 05:31:47 +00002693}
2694
2695static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002696long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002697{
Tim Peters47e52ee2004-08-30 02:44:38 +00002698 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002699
2700 CONVERT_BINOP(v, w, &a, &b);
2701
Tim Peters47e52ee2004-08-30 02:44:38 +00002702 if (l_divmod(a, b, NULL, &mod) < 0)
2703 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002704 Py_DECREF(a);
2705 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002706 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002707}
2708
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002709static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002710long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002711{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002712 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002713 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002714
2715 CONVERT_BINOP(v, w, &a, &b);
2716
2717 if (l_divmod(a, b, &div, &mod) < 0) {
2718 Py_DECREF(a);
2719 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002720 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002721 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002722 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002723 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002724 PyTuple_SetItem(z, 0, (PyObject *) div);
2725 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002726 }
2727 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002728 Py_DECREF(div);
2729 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002730 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002731 Py_DECREF(a);
2732 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002733 return z;
2734}
2735
Tim Peters47e52ee2004-08-30 02:44:38 +00002736/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002737static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002738long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002739{
Tim Peters47e52ee2004-08-30 02:44:38 +00002740 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2741 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002742
Tim Peters47e52ee2004-08-30 02:44:38 +00002743 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002744 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002745 PyLongObject *temp = NULL;
2746
2747 /* 5-ary values. If the exponent is large enough, table is
2748 * precomputed so that table[i] == a**i % c for i in range(32).
2749 */
2750 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2751 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2752
2753 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002754 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002755 if (PyLong_Check(x)) {
2756 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002757 Py_INCREF(x);
2758 }
Tim Petersde7990b2005-07-17 23:45:23 +00002759 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002760 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002761 if (c == NULL)
2762 goto Error;
2763 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002764 else if (x == Py_None)
2765 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002766 else {
2767 Py_DECREF(a);
2768 Py_DECREF(b);
2769 Py_INCREF(Py_NotImplemented);
2770 return Py_NotImplemented;
2771 }
Tim Peters4c483c42001-09-05 06:24:58 +00002772
Christian Heimese93237d2007-12-19 02:37:44 +00002773 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00002774 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002775 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002776 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002777 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002778 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002779 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002780 /* else return a float. This works because we know
2781 that this calls float_pow() which converts its
2782 arguments to double. */
2783 Py_DECREF(a);
2784 Py_DECREF(b);
2785 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002786 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002787 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002788
2789 if (c) {
2790 /* if modulus == 0:
2791 raise ValueError() */
Christian Heimese93237d2007-12-19 02:37:44 +00002792 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002793 PyErr_SetString(PyExc_ValueError,
2794 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002795 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002796 }
2797
2798 /* if modulus < 0:
2799 negativeOutput = True
2800 modulus = -modulus */
Christian Heimese93237d2007-12-19 02:37:44 +00002801 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002802 negativeOutput = 1;
2803 temp = (PyLongObject *)_PyLong_Copy(c);
2804 if (temp == NULL)
2805 goto Error;
2806 Py_DECREF(c);
2807 c = temp;
2808 temp = NULL;
2809 c->ob_size = - c->ob_size;
2810 }
2811
2812 /* if modulus == 1:
2813 return 0 */
Christian Heimese93237d2007-12-19 02:37:44 +00002814 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002815 z = (PyLongObject *)PyLong_FromLong(0L);
2816 goto Done;
2817 }
2818
2819 /* if base < 0:
2820 base = base % modulus
2821 Having the base positive just makes things easier. */
Christian Heimese93237d2007-12-19 02:37:44 +00002822 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002823 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002824 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002825 Py_DECREF(a);
2826 a = temp;
2827 temp = NULL;
2828 }
2829 }
2830
2831 /* At this point a, b, and c are guaranteed non-negative UNLESS
2832 c is NULL, in which case a may be negative. */
2833
2834 z = (PyLongObject *)PyLong_FromLong(1L);
2835 if (z == NULL)
2836 goto Error;
2837
2838 /* Perform a modular reduction, X = X % c, but leave X alone if c
2839 * is NULL.
2840 */
2841#define REDUCE(X) \
2842 if (c != NULL) { \
2843 if (l_divmod(X, c, NULL, &temp) < 0) \
2844 goto Error; \
2845 Py_XDECREF(X); \
2846 X = temp; \
2847 temp = NULL; \
2848 }
2849
2850 /* Multiply two values, then reduce the result:
2851 result = X*Y % c. If c is NULL, skip the mod. */
2852#define MULT(X, Y, result) \
2853{ \
2854 temp = (PyLongObject *)long_mul(X, Y); \
2855 if (temp == NULL) \
2856 goto Error; \
2857 Py_XDECREF(result); \
2858 result = temp; \
2859 temp = NULL; \
2860 REDUCE(result) \
2861}
2862
Christian Heimese93237d2007-12-19 02:37:44 +00002863 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002864 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2865 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimese93237d2007-12-19 02:37:44 +00002866 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002867 digit bi = b->ob_digit[i];
2868
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00002869 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002870 MULT(z, z, z)
2871 if (bi & j)
2872 MULT(z, a, z)
2873 }
2874 }
2875 }
2876 else {
2877 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2878 Py_INCREF(z); /* still holds 1L */
2879 table[0] = z;
2880 for (i = 1; i < 32; ++i)
2881 MULT(table[i-1], a, table[i])
2882
Christian Heimese93237d2007-12-19 02:37:44 +00002883 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002884 const digit bi = b->ob_digit[i];
2885
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002886 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002887 const int index = (bi >> j) & 0x1f;
2888 for (k = 0; k < 5; ++k)
2889 MULT(z, z, z)
2890 if (index)
2891 MULT(z, table[index], z)
2892 }
2893 }
2894 }
2895
Christian Heimese93237d2007-12-19 02:37:44 +00002896 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002897 temp = (PyLongObject *)long_sub(z, c);
2898 if (temp == NULL)
2899 goto Error;
2900 Py_DECREF(z);
2901 z = temp;
2902 temp = NULL;
2903 }
2904 goto Done;
2905
2906 Error:
2907 if (z != NULL) {
2908 Py_DECREF(z);
2909 z = NULL;
2910 }
2911 /* fall through */
2912 Done:
Christian Heimese93237d2007-12-19 02:37:44 +00002913 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002914 for (i = 0; i < 32; ++i)
2915 Py_XDECREF(table[i]);
2916 }
Tim Petersde7990b2005-07-17 23:45:23 +00002917 Py_DECREF(a);
2918 Py_DECREF(b);
2919 Py_XDECREF(c);
2920 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002921 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002922}
2923
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002924static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002925long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002926{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002927 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002928 PyLongObject *x;
2929 PyLongObject *w;
2930 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002931 if (w == NULL)
2932 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002933 x = (PyLongObject *) long_add(v, w);
2934 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002935 if (x == NULL)
2936 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002937 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002938 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002939}
2940
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002941static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002942long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002943{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002944 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002945 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002946 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002947 Py_INCREF(v);
2948 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002949 }
Tim Peters69c2de32001-09-11 22:31:33 +00002950 z = (PyLongObject *)_PyLong_Copy(v);
2951 if (z != NULL)
2952 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002953 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002954}
2955
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002956static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002957long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002958{
2959 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002960 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002961 else
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002962 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002963}
2964
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002965static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002966long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002967{
Christian Heimese93237d2007-12-19 02:37:44 +00002968 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002969}
2970
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002971static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002972long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002973{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002974 PyLongObject *a, *b;
2975 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002976 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002977 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002978 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002979
Neil Schemenauerba872e22001-01-04 01:46:03 +00002980 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2981
Christian Heimese93237d2007-12-19 02:37:44 +00002982 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002983 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002984 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002985 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002986 if (a1 == NULL)
2987 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002988 a2 = (PyLongObject *) long_rshift(a1, b);
2989 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002990 if (a2 == NULL)
2991 goto rshift_error;
2992 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002993 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002994 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002995 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002996
Neil Schemenauerba872e22001-01-04 01:46:03 +00002997 shiftby = PyLong_AsLong((PyObject *)b);
2998 if (shiftby == -1L && PyErr_Occurred())
2999 goto rshift_error;
3000 if (shiftby < 0) {
3001 PyErr_SetString(PyExc_ValueError,
3002 "negative shift count");
3003 goto rshift_error;
3004 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003005 wordshift = shiftby / PyLong_SHIFT;
Christian Heimese93237d2007-12-19 02:37:44 +00003006 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003007 if (newsize <= 0) {
3008 z = _PyLong_New(0);
3009 Py_DECREF(a);
3010 Py_DECREF(b);
3011 return (PyObject *)z;
3012 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003013 loshift = shiftby % PyLong_SHIFT;
3014 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003015 lomask = ((digit)1 << hishift) - 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003016 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003017 z = _PyLong_New(newsize);
3018 if (z == NULL)
3019 goto rshift_error;
Christian Heimese93237d2007-12-19 02:37:44 +00003020 if (Py_SIZE(a) < 0)
3021 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003022 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3023 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3024 if (i+1 < newsize)
3025 z->ob_digit[i] |=
3026 (a->ob_digit[j+1] << hishift) & himask;
3027 }
3028 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003029 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003030rshift_error:
3031 Py_DECREF(a);
3032 Py_DECREF(b);
3033 return (PyObject *) z;
3034
Guido van Rossumc6913e71991-11-19 20:26:46 +00003035}
3036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003037static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003038long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003039{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003040 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003041 PyLongObject *a, *b;
3042 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003043 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003044 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003045 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003046
Neil Schemenauerba872e22001-01-04 01:46:03 +00003047 CONVERT_BINOP(v, w, &a, &b);
3048
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003049 shiftby = PyLong_AsLong((PyObject *)b);
3050 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003051 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003052 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003053 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003054 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003055 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003056 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003057 PyErr_SetString(PyExc_ValueError,
3058 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003059 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003060 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003061 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3062 wordshift = (int)shiftby / PyLong_SHIFT;
3063 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003064
3065 oldsize = ABS(a->ob_size);
3066 newsize = oldsize + wordshift;
3067 if (remshift)
3068 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003069 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003070 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003071 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003072 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003073 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003074 for (i = 0; i < wordshift; i++)
3075 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003076 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003077 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003078 accum |= (twodigits)a->ob_digit[j] << remshift;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003079 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3080 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003081 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003082 if (remshift)
3083 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003084 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003085 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003086 z = long_normalize(z);
3087lshift_error:
3088 Py_DECREF(a);
3089 Py_DECREF(b);
3090 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003091}
3092
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003093
3094/* Bitwise and/xor/or operations */
3095
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003096static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003097long_bitwise(PyLongObject *a,
3098 int op, /* '&', '|', '^' */
3099 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003100{
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003101 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003102 int negz;
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00003103 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003104 PyLongObject *z;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003105 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003106 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003107
Christian Heimese93237d2007-12-19 02:37:44 +00003108 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003109 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003110 if (a == NULL)
3111 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003112 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003113 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003114 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003115 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003116 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003117 }
Christian Heimese93237d2007-12-19 02:37:44 +00003118 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003119 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003120 if (b == NULL) {
3121 Py_DECREF(a);
3122 return NULL;
3123 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003124 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003125 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003126 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003127 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003128 maskb = 0;
3129 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003130
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003131 negz = 0;
3132 switch (op) {
3133 case '^':
3134 if (maska != maskb) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003135 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003136 negz = -1;
3137 }
3138 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003139 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003140 if (maska && maskb) {
3141 op = '|';
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003142 maska ^= PyLong_MASK;
3143 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003144 negz = -1;
3145 }
3146 break;
3147 case '|':
3148 if (maska || maskb) {
3149 op = '&';
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003150 maska ^= PyLong_MASK;
3151 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003152 negz = -1;
3153 }
3154 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003155 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003156
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003157 /* JRH: The original logic here was to allocate the result value (z)
3158 as the longer of the two operands. However, there are some cases
3159 where the result is guaranteed to be shorter than that: AND of two
3160 positives, OR of two negatives: use the shorter number. AND with
3161 mixed signs: use the positive number. OR with mixed signs: use the
3162 negative number. After the transformations above, op will be '&'
3163 iff one of these cases applies, and mask will be non-0 for operands
3164 whose length should be ignored.
3165 */
3166
Christian Heimese93237d2007-12-19 02:37:44 +00003167 size_a = Py_SIZE(a);
3168 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003169 size_z = op == '&'
3170 ? (maska
3171 ? size_b
3172 : (maskb ? size_a : MIN(size_a, size_b)))
3173 : MAX(size_a, size_b);
3174 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003175 if (z == NULL) {
Neal Norwitzef02b9e2006-07-16 02:00:32 +00003176 Py_DECREF(a);
3177 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003178 return NULL;
3179 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003180
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003181 for (i = 0; i < size_z; ++i) {
3182 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3183 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3184 switch (op) {
3185 case '&': z->ob_digit[i] = diga & digb; break;
3186 case '|': z->ob_digit[i] = diga | digb; break;
3187 case '^': z->ob_digit[i] = diga ^ digb; break;
3188 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003189 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003190
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003191 Py_DECREF(a);
3192 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003193 z = long_normalize(z);
3194 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003195 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003196 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003197 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003198 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003199}
3200
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003201static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003202long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003203{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003204 PyLongObject *a, *b;
3205 PyObject *c;
3206 CONVERT_BINOP(v, w, &a, &b);
3207 c = long_bitwise(a, '&', b);
3208 Py_DECREF(a);
3209 Py_DECREF(b);
3210 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003211}
3212
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003213static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003214long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003215{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003216 PyLongObject *a, *b;
3217 PyObject *c;
3218 CONVERT_BINOP(v, w, &a, &b);
3219 c = long_bitwise(a, '^', b);
3220 Py_DECREF(a);
3221 Py_DECREF(b);
3222 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003223}
3224
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003225static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003226long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003227{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003228 PyLongObject *a, *b;
3229 PyObject *c;
3230 CONVERT_BINOP(v, w, &a, &b);
3231 c = long_bitwise(a, '|', b);
3232 Py_DECREF(a);
3233 Py_DECREF(b);
3234 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003235}
3236
Guido van Rossum234f9421993-06-17 12:35:49 +00003237static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003238long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003239{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003240 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003241 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Georg Brandlc02e1312007-04-11 17:16:24 +00003242 if (*pw == NULL)
3243 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003244 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003245 return 0;
3246 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003247 else if (PyLong_Check(*pw)) {
3248 Py_INCREF(*pv);
3249 Py_INCREF(*pw);
3250 return 0;
3251 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003252 return 1; /* Can't do it */
3253}
3254
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003255static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003256long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003257{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003258 if (PyLong_CheckExact(v))
3259 Py_INCREF(v);
3260 else
3261 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003262 return v;
3263}
3264
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003265static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003266long_int(PyObject *v)
3267{
3268 long x;
3269 x = PyLong_AsLong(v);
3270 if (PyErr_Occurred()) {
3271 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3272 PyErr_Clear();
3273 if (PyLong_CheckExact(v)) {
3274 Py_INCREF(v);
3275 return v;
3276 }
3277 else
3278 return _PyLong_Copy((PyLongObject *)v);
3279 }
3280 else
3281 return NULL;
3282 }
3283 return PyInt_FromLong(x);
3284}
3285
3286static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003287long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003288{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003289 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003290 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003291 if (result == -1.0 && PyErr_Occurred())
3292 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003293 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003294}
3295
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003296static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003297long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003298{
Eric Smith5e527eb2008-02-10 01:36:53 +00003299 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003300}
3301
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003302static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003303long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003304{
Eric Smith5e527eb2008-02-10 01:36:53 +00003305 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003306}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003307
3308static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003309long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003310
Tim Peters6d6c1a32001-08-02 04:15:00 +00003311static PyObject *
3312long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3313{
3314 PyObject *x = NULL;
3315 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003316 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317
Guido van Rossumbef14172001-08-29 15:47:46 +00003318 if (type != &PyLong_Type)
3319 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003320 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3321 &x, &base))
3322 return NULL;
3323 if (x == NULL)
3324 return PyLong_FromLong(0L);
3325 if (base == -909)
3326 return PyNumber_Long(x);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003327 else if (PyString_Check(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003328 /* Since PyLong_FromString doesn't have a length parameter,
3329 * check here for possible NULs in the string. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003330 char *string = PyString_AS_STRING(x);
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003331 if (strlen(string) != (size_t)PyString_Size(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003332 /* create a repr() of the input string,
3333 * just like PyLong_FromString does. */
3334 PyObject *srepr;
3335 srepr = PyObject_Repr(x);
3336 if (srepr == NULL)
3337 return NULL;
3338 PyErr_Format(PyExc_ValueError,
3339 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003340 base, PyString_AS_STRING(srepr));
Georg Brandl00cd8182007-03-06 18:41:12 +00003341 Py_DECREF(srepr);
3342 return NULL;
3343 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003344 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Georg Brandl00cd8182007-03-06 18:41:12 +00003345 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003346#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003347 else if (PyUnicode_Check(x))
3348 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3349 PyUnicode_GET_SIZE(x),
3350 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003351#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352 else {
3353 PyErr_SetString(PyExc_TypeError,
3354 "long() can't convert non-string with explicit base");
3355 return NULL;
3356 }
3357}
3358
Guido van Rossumbef14172001-08-29 15:47:46 +00003359/* Wimpy, slow approach to tp_new calls for subtypes of long:
3360 first create a regular long from whatever arguments we got,
3361 then allocate a subtype instance and initialize it from
3362 the regular long. The regular long is then thrown away.
3363*/
3364static PyObject *
3365long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3366{
Anthony Baxter377be112006-04-11 06:54:30 +00003367 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003368 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003369
3370 assert(PyType_IsSubtype(type, &PyLong_Type));
3371 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3372 if (tmp == NULL)
3373 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003374 assert(PyLong_CheckExact(tmp));
Christian Heimese93237d2007-12-19 02:37:44 +00003375 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003376 if (n < 0)
3377 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00003378 newobj = (PyLongObject *)type->tp_alloc(type, n);
3379 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003380 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003381 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003382 }
Anthony Baxter377be112006-04-11 06:54:30 +00003383 assert(PyLong_Check(newobj));
Christian Heimese93237d2007-12-19 02:37:44 +00003384 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003385 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00003386 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003387 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00003388 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003389}
3390
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003391static PyObject *
3392long_getnewargs(PyLongObject *v)
3393{
3394 return Py_BuildValue("(N)", _PyLong_Copy(v));
3395}
3396
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003397static PyObject *
3398long_getN(PyLongObject *v, void *context) {
Jeffrey Yasskin5de250e2008-03-18 01:09:59 +00003399 return PyLong_FromLong((Py_intptr_t)context);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003400}
3401
Eric Smitha9f7d622008-02-17 19:46:49 +00003402static PyObject *
3403long__format__(PyObject *self, PyObject *args)
3404{
3405 PyObject *format_spec;
3406
3407 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3408 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00003409 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00003410 return _PyLong_FormatAdvanced(self,
3411 PyBytes_AS_STRING(format_spec),
3412 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003413 if (PyUnicode_Check(format_spec)) {
3414 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00003415 PyObject *result;
3416 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003417
Eric Smithdc13b792008-05-30 18:10:04 +00003418 if (str_spec == NULL)
3419 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00003420
Eric Smithdc13b792008-05-30 18:10:04 +00003421 result = _PyLong_FormatAdvanced(self,
3422 PyBytes_AS_STRING(str_spec),
3423 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003424
Eric Smithdc13b792008-05-30 18:10:04 +00003425 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003426 return result;
3427 }
3428 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
3429 return NULL;
3430}
3431
Robert Schuppenies51df0642008-06-01 16:16:17 +00003432static PyObject *
3433long_sizeof(PyLongObject *v)
3434{
3435 Py_ssize_t res;
3436
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003437 res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
Robert Schuppenies51df0642008-06-01 16:16:17 +00003438 return PyInt_FromSsize_t(res);
3439}
3440
Mark Dickinson1a707982008-12-17 16:14:37 +00003441static const unsigned char BitLengthTable[32] = {
3442 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
3443 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
3444};
3445
3446static PyObject *
3447long_bit_length(PyLongObject *v)
3448{
3449 PyLongObject *result, *x, *y;
3450 Py_ssize_t ndigits, msd_bits = 0;
3451 digit msd;
3452
3453 assert(v != NULL);
3454 assert(PyLong_Check(v));
3455
3456 ndigits = ABS(Py_SIZE(v));
3457 if (ndigits == 0)
3458 return PyInt_FromLong(0);
3459
3460 msd = v->ob_digit[ndigits-1];
3461 while (msd >= 32) {
3462 msd_bits += 6;
3463 msd >>= 6;
3464 }
3465 msd_bits += (long)(BitLengthTable[msd]);
3466
3467 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3468 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3469
3470 /* expression above may overflow; use Python integers instead */
3471 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3472 if (result == NULL)
3473 return NULL;
3474 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3475 if (x == NULL)
3476 goto error;
3477 y = (PyLongObject *)long_mul(result, x);
3478 Py_DECREF(x);
3479 if (y == NULL)
3480 goto error;
3481 Py_DECREF(result);
3482 result = y;
3483
3484 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3485 if (x == NULL)
3486 goto error;
3487 y = (PyLongObject *)long_add(result, x);
3488 Py_DECREF(x);
3489 if (y == NULL)
3490 goto error;
3491 Py_DECREF(result);
3492 result = y;
3493
3494 return (PyObject *)result;
3495
3496error:
3497 Py_DECREF(result);
3498 return NULL;
3499}
3500
3501PyDoc_STRVAR(long_bit_length_doc,
3502"long.bit_length() -> int or long\n\
3503\n\
3504Number of bits necessary to represent self in binary.\n\
3505>>> bin(37L)\n\
3506'0b100101'\n\
3507>>> (37L).bit_length()\n\
35086");
3509
Christian Heimes6f341092008-04-18 23:13:07 +00003510#if 0
3511static PyObject *
3512long_is_finite(PyObject *v)
3513{
3514 Py_RETURN_TRUE;
3515}
3516#endif
3517
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003518static PyMethodDef long_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003519 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3520 "Returns self, the complex conjugate of any long."},
Mark Dickinson1a707982008-12-17 16:14:37 +00003521 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3522 long_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00003523#if 0
3524 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3525 "Returns always True."},
3526#endif
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003527 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3528 "Truncating an Integral returns itself."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003529 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smitha9f7d622008-02-17 19:46:49 +00003530 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Robert Schuppenies51df0642008-06-01 16:16:17 +00003531 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00003532 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003533 {NULL, NULL} /* sentinel */
3534};
3535
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003536static PyGetSetDef long_getset[] = {
3537 {"real",
3538 (getter)long_long, (setter)NULL,
3539 "the real part of a complex number",
3540 NULL},
3541 {"imag",
3542 (getter)long_getN, (setter)NULL,
3543 "the imaginary part of a complex number",
3544 (void*)0},
3545 {"numerator",
3546 (getter)long_long, (setter)NULL,
3547 "the numerator of a rational number in lowest terms",
3548 NULL},
3549 {"denominator",
3550 (getter)long_getN, (setter)NULL,
3551 "the denominator of a rational number in lowest terms",
3552 (void*)1},
3553 {NULL} /* Sentinel */
3554};
3555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003556PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003557"long(x[, base]) -> integer\n\
3558\n\
3559Convert a string or number to a long integer, if possible. A floating\n\
3560point argument will be truncated towards zero (this does not include a\n\
3561string representation of a floating point number!) When converting a\n\
3562string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003563converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003564
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003565static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003566 (binaryfunc) long_add, /*nb_add*/
3567 (binaryfunc) long_sub, /*nb_subtract*/
3568 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00003569 long_classic_div, /*nb_divide*/
3570 long_mod, /*nb_remainder*/
3571 long_divmod, /*nb_divmod*/
3572 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003573 (unaryfunc) long_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003574 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003575 (unaryfunc) long_abs, /*tp_absolute*/
3576 (inquiry) long_nonzero, /*tp_nonzero*/
3577 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00003578 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003579 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00003580 long_and, /*nb_and*/
3581 long_xor, /*nb_xor*/
3582 long_or, /*nb_or*/
3583 long_coerce, /*nb_coerce*/
3584 long_int, /*nb_int*/
3585 long_long, /*nb_long*/
3586 long_float, /*nb_float*/
3587 long_oct, /*nb_oct*/
3588 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003589 0, /* nb_inplace_add */
3590 0, /* nb_inplace_subtract */
3591 0, /* nb_inplace_multiply */
3592 0, /* nb_inplace_divide */
3593 0, /* nb_inplace_remainder */
3594 0, /* nb_inplace_power */
3595 0, /* nb_inplace_lshift */
3596 0, /* nb_inplace_rshift */
3597 0, /* nb_inplace_and */
3598 0, /* nb_inplace_xor */
3599 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00003600 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003601 long_true_divide, /* nb_true_divide */
3602 0, /* nb_inplace_floor_divide */
3603 0, /* nb_inplace_true_divide */
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003604 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003605};
3606
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003607PyTypeObject PyLong_Type = {
3608 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609 0, /* ob_size */
3610 "long", /* tp_name */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003611 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003612 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003613 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614 0, /* tp_print */
3615 0, /* tp_getattr */
3616 0, /* tp_setattr */
3617 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003618 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619 &long_as_number, /* tp_as_number */
3620 0, /* tp_as_sequence */
3621 0, /* tp_as_mapping */
3622 (hashfunc)long_hash, /* tp_hash */
3623 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003624 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625 PyObject_GenericGetAttr, /* tp_getattro */
3626 0, /* tp_setattro */
3627 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003628 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003629 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630 long_doc, /* tp_doc */
3631 0, /* tp_traverse */
3632 0, /* tp_clear */
3633 0, /* tp_richcompare */
3634 0, /* tp_weaklistoffset */
3635 0, /* tp_iter */
3636 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003637 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003639 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003640 0, /* tp_base */
3641 0, /* tp_dict */
3642 0, /* tp_descr_get */
3643 0, /* tp_descr_set */
3644 0, /* tp_dictoffset */
3645 0, /* tp_init */
3646 0, /* tp_alloc */
3647 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003648 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003649};
Mark Dickinsonefc82f72009-03-20 15:51:55 +00003650
3651static PyTypeObject Long_InfoType;
3652
3653PyDoc_STRVAR(long_info__doc__,
3654"sys.long_info\n\
3655\n\
3656A struct sequence that holds information about Python's\n\
3657internal representation of integers. The attributes are read only.");
3658
3659static PyStructSequence_Field long_info_fields[] = {
3660 {"bits_per_digit", "size of a digit in bits"},
3661 {"sizeof_digit", "size in bytes of the C type used to "
3662 "represent a digit"},
3663 {NULL, NULL}
3664};
3665
3666static PyStructSequence_Desc long_info_desc = {
3667 "sys.long_info", /* name */
3668 long_info__doc__, /* doc */
3669 long_info_fields, /* fields */
3670 2 /* number of fields */
3671};
3672
3673PyObject *
3674PyLong_GetInfo(void)
3675{
3676 PyObject* long_info;
3677 int field = 0;
3678 long_info = PyStructSequence_New(&Long_InfoType);
3679 if (long_info == NULL)
3680 return NULL;
3681 PyStructSequence_SET_ITEM(long_info, field++, PyLong_FromLong(PyLong_SHIFT));
3682 PyStructSequence_SET_ITEM(long_info, field++, PyLong_FromLong(sizeof(digit)));
3683 if (PyErr_Occurred()) {
3684 Py_CLEAR(long_info);
3685 return NULL;
3686 }
3687 return long_info;
3688}
3689
3690int
3691_PyLong_Init(void)
3692{
3693 /* initialize long_info */
3694 if (Long_InfoType.tp_name == 0)
3695 PyStructSequence_InitType(&Long_InfoType, &long_info_desc);
3696 return 1;
3697}