blob: e1df9d9ef775d143dec76e0f9ccaf2c596e82eef [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Mark Dickinsonbd792642009-03-18 20:06:12 +00007#include "structseq.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
13#define NSMALLPOSINTS 257
14#endif
15#ifndef NSMALLNEGINTS
16#define NSMALLNEGINTS 5
17#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
20#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
33int quick_int_allocs, quick_neg_int_allocs;
34#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
39 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
41#ifdef COUNT_ALLOCS
42 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
46#endif
47 return v;
48}
49#define CHECK_SMALL_INT(ival) \
50 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
Mark Dickinson0d4785b2009-02-15 17:27:41 +000051 return get_small_int((sdigit)ival); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000052 } while(0)
53
Facundo Batista6e6f59b2008-07-24 18:57:11 +000054static PyLongObject *
55maybe_small_long(PyLongObject *v)
56{
57 if (v && ABS(Py_SIZE(v)) <= 1) {
Mark Dickinsone4416742009-02-15 15:14:57 +000058 sdigit ival = MEDIUM_VALUE(v);
Facundo Batista6e6f59b2008-07-24 18:57:11 +000059 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
65}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Christian Heimes90aa7642007-12-19 02:45:37 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
Christian Heimes217cfd12007-12-02 14:31:20 +000075 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000076 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000098 if (--_Py_Ticker < 0) { \
99 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000100 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101 }
102
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000103/* Normalize (remove leading zeros from) a long int object.
104 Doesn't attempt to free the storage--in most cases, due to the nature
105 of the algorithms used, this could save at most be one word anyway. */
106
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000107static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000108long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000109{
Christian Heimes90aa7642007-12-19 02:45:37 +0000110 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000111 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000112
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000113 while (i > 0 && v->ob_digit[i-1] == 0)
114 --i;
115 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000116 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117 return v;
118}
119
120/* Allocate a new long int object with size digits.
121 Return NULL and set exception if we run out of memory. */
122
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000123#define MAX_LONG_DIGITS \
124 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
125
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000127_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000129 PyLongObject *result;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000130 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
131 sizeof(digit)*size. Previous incarnations of this code used
132 sizeof(PyVarObject) instead of the offsetof, but this risks being
133 incorrect in the presence of padding between the PyVarObject header
134 and the digits. */
Mark Dickinsone4416742009-02-15 15:14:57 +0000135 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000136 PyErr_SetString(PyExc_OverflowError,
137 "too many digits in integer");
138 return NULL;
139 }
140 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
Guido van Rossumddefaf32007-01-14 03:31:43 +0000141 size*sizeof(digit));
142 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000143 PyErr_NoMemory();
144 return NULL;
145 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000146 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000147}
148
Tim Peters64b5ce32001-09-10 20:52:51 +0000149PyObject *
150_PyLong_Copy(PyLongObject *src)
151{
152 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000153 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000154
155 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000156 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000157 if (i < 0)
158 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000159 if (i < 2) {
Mark Dickinsone4416742009-02-15 15:14:57 +0000160 sdigit ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000161 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000162 ival = -ival;
163 CHECK_SMALL_INT(ival);
164 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000165 result = _PyLong_New(i);
166 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000167 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000168 while (--i >= 0)
169 result->ob_digit[i] = src->ob_digit[i];
170 }
171 return (PyObject *)result;
172}
173
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000174/* Create a new long int object from a C long int */
175
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000176PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000177PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000178{
Tim Petersce9de2f2001-06-14 04:56:19 +0000179 PyLongObject *v;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000180 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000181 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
182 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000183 int sign = 1;
184
185 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000186
187 if (ival < 0) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000188 /* negate: can't write this as abs_ival = -ival since that
189 invokes undefined behaviour when ival is LONG_MIN */
190 abs_ival = 0U-(unsigned long)ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000191 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000192 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000193 else {
194 abs_ival = (unsigned long)ival;
195 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000196
Mark Dickinsond4624c32009-01-24 15:02:35 +0000197 /* Fast path for single-digit ints */
198 if (!(abs_ival >> PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000199 v = _PyLong_New(1);
200 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000201 Py_SIZE(v) = sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000202 v->ob_digit[0] = Py_SAFE_DOWNCAST(
203 abs_ival, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000204 }
205 return (PyObject*)v;
206 }
207
Mark Dickinsonbd792642009-03-18 20:06:12 +0000208#if PyLONG_SHIFT==15
Guido van Rossumddefaf32007-01-14 03:31:43 +0000209 /* 2 digits */
Mark Dickinsond4624c32009-01-24 15:02:35 +0000210 if (!(abs_ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000211 v = _PyLong_New(2);
212 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000213 Py_SIZE(v) = 2*sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000214 v->ob_digit[0] = Py_SAFE_DOWNCAST(
215 abs_ival & PyLong_MASK, unsigned long, digit);
216 v->ob_digit[1] = Py_SAFE_DOWNCAST(
217 abs_ival >> PyLong_SHIFT, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000218 }
219 return (PyObject*)v;
220 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000221#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000222
223 /* Larger numbers: loop to determine number of digits */
Christian Heimesdae2a892008-04-19 00:55:37 +0000224 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000225 while (t) {
226 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000227 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000228 }
229 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000230 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000231 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000232 Py_SIZE(v) = ndigits*sign;
Christian Heimesdae2a892008-04-19 00:55:37 +0000233 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000234 while (t) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000235 *p++ = Py_SAFE_DOWNCAST(
236 t & PyLong_MASK, unsigned long, digit);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000237 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000239 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000241}
242
Guido van Rossum53756b11997-01-03 17:14:46 +0000243/* Create a new long int object from a C unsigned long int */
244
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000246PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000247{
Tim Petersce9de2f2001-06-14 04:56:19 +0000248 PyLongObject *v;
249 unsigned long t;
250 int ndigits = 0;
251
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000252 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000253 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000254 /* Count the number of Python digits. */
255 t = (unsigned long)ival;
256 while (t) {
257 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000258 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000259 }
260 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000261 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000262 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000263 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000264 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000265 *p++ = (digit)(ival & PyLong_MASK);
266 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000267 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000268 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000269 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000270}
271
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000272/* Create a new long int object from a C double */
273
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000275PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000276{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000277 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000278 double frac;
279 int i, ndig, expo, neg;
280 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000281 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000282 PyErr_SetString(PyExc_OverflowError,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000283 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000284 return NULL;
285 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000286 if (Py_IS_NAN(dval)) {
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000287 PyErr_SetString(PyExc_ValueError,
288 "cannot convert float NaN to integer");
Christian Heimes386cd1e2008-01-15 02:01:20 +0000289 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000290 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000291 if (dval < 0.0) {
292 neg = 1;
293 dval = -dval;
294 }
295 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
296 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000297 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000298 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000300 if (v == NULL)
301 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000302 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000303 for (i = ndig; --i >= 0; ) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000304 digit bits = (digit)frac;
305 v->ob_digit[i] = bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000306 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000307 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000308 }
309 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000310 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000312}
313
Thomas Wouters89f507f2006-12-13 04:49:30 +0000314/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
315 * anything about what happens when a signed integer operation overflows,
316 * and some compilers think they're doing you a favor by being "clever"
317 * then. The bit pattern for the largest postive signed long is
318 * (unsigned long)LONG_MAX, and for the smallest negative signed long
319 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
320 * However, some other compilers warn about applying unary minus to an
321 * unsigned operand. Hence the weird "0-".
322 */
323#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
324#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
325
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000326/* Get a C long int from a long int object.
327 Returns -1 and sets an error condition if overflow occurs. */
328
329long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000330PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000331{
Guido van Rossumf7531811998-05-26 14:33:37 +0000332 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000334 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000335 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000336 Py_ssize_t i;
337 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000338 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000339
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000340 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000341 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000342 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000343 return -1;
344 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000345
346 if (!PyLong_Check(vv)) {
347 PyNumberMethods *nb;
348 if ((nb = vv->ob_type->tp_as_number) == NULL ||
349 nb->nb_int == NULL) {
350 PyErr_SetString(PyExc_TypeError, "an integer is required");
351 return -1;
352 }
353 vv = (*nb->nb_int) (vv);
354 if (vv == NULL)
355 return -1;
356 do_decref = 1;
357 if (!PyLong_Check(vv)) {
358 Py_DECREF(vv);
359 PyErr_SetString(PyExc_TypeError,
360 "nb_int should return int object");
361 return -1;
362 }
363 }
364
Georg Brandl61c31b02007-02-26 14:46:30 +0000365 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000366 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000367 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000368
Georg Brandl61c31b02007-02-26 14:46:30 +0000369 switch (i) {
370 case -1:
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000371 res = -(sdigit)v->ob_digit[0];
Georg Brandl61c31b02007-02-26 14:46:30 +0000372 break;
373 case 0:
374 res = 0;
375 break;
376 case 1:
377 res = v->ob_digit[0];
378 break;
379 default:
380 sign = 1;
381 x = 0;
382 if (i < 0) {
383 sign = -1;
384 i = -(i);
385 }
386 while (--i >= 0) {
387 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000388 x = (x << PyLong_SHIFT) + v->ob_digit[i];
389 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000390 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000391 goto exit;
392 }
393 }
394 /* Haven't lost any bits, but casting to long requires extra care
395 * (see comment above).
396 */
397 if (x <= (unsigned long)LONG_MAX) {
398 res = (long)x * sign;
399 }
400 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
401 res = LONG_MIN;
402 }
403 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000404 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000405 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000406 }
407 }
408 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000409 if (do_decref) {
410 Py_DECREF(vv);
411 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000412 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000413}
414
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000415long
416PyLong_AsLong(PyObject *obj)
417{
418 int overflow;
419 long result = PyLong_AsLongAndOverflow(obj, &overflow);
420 if (overflow) {
421 /* XXX: could be cute and give a different
422 message for overflow == -1 */
423 PyErr_SetString(PyExc_OverflowError,
424 "Python int too large to convert to C long");
425 }
426 return result;
427}
428
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000429/* Get a Py_ssize_t from a long int object.
430 Returns -1 and sets an error condition if overflow occurs. */
431
432Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000433PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000434 register PyLongObject *v;
435 size_t x, prev;
436 Py_ssize_t i;
437 int sign;
438
439 if (vv == NULL || !PyLong_Check(vv)) {
440 PyErr_BadInternalCall();
441 return -1;
442 }
443 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000444 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000445 switch (i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000446 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +0000447 case 0: return 0;
448 case 1: return v->ob_digit[0];
449 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000450 sign = 1;
451 x = 0;
452 if (i < 0) {
453 sign = -1;
454 i = -(i);
455 }
456 while (--i >= 0) {
457 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000458 x = (x << PyLong_SHIFT) + v->ob_digit[i];
459 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000460 goto overflow;
461 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000462 /* Haven't lost any bits, but casting to a signed type requires
463 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000464 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000465 if (x <= (size_t)PY_SSIZE_T_MAX) {
466 return (Py_ssize_t)x * sign;
467 }
468 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
469 return PY_SSIZE_T_MIN;
470 }
471 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000472
473 overflow:
474 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000475 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000476 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000477}
478
Guido van Rossumd8c80482002-08-13 00:24:58 +0000479/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000480 Returns -1 and sets an error condition if overflow occurs. */
481
482unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000483PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000484{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000486 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000487 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000488
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489 if (vv == NULL || !PyLong_Check(vv)) {
490 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000491 return (unsigned long) -1;
492 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000494 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000495 x = 0;
496 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000497 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000498 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000499 return (unsigned long) -1;
500 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000501 switch (i) {
502 case 0: return 0;
503 case 1: return v->ob_digit[0];
504 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000505 while (--i >= 0) {
506 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000507 x = (x << PyLong_SHIFT) + v->ob_digit[i];
508 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000510 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000511 return (unsigned long) -1;
512 }
513 }
514 return x;
515}
516
517/* Get a C unsigned long int from a long int object.
518 Returns -1 and sets an error condition if overflow occurs. */
519
520size_t
521PyLong_AsSize_t(PyObject *vv)
522{
523 register PyLongObject *v;
524 size_t x, prev;
525 Py_ssize_t i;
526
527 if (vv == NULL || !PyLong_Check(vv)) {
528 PyErr_BadInternalCall();
529 return (unsigned long) -1;
530 }
531 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000532 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000533 x = 0;
534 if (i < 0) {
535 PyErr_SetString(PyExc_OverflowError,
536 "can't convert negative value to size_t");
537 return (size_t) -1;
538 }
539 switch (i) {
540 case 0: return 0;
541 case 1: return v->ob_digit[0];
542 }
543 while (--i >= 0) {
544 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000545 x = (x << PyLong_SHIFT) + v->ob_digit[i];
546 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000547 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000548 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000549 return (unsigned long) -1;
550 }
551 }
552 return x;
553}
554
Thomas Hellera4ea6032003-04-17 18:55:45 +0000555/* Get a C unsigned long int from a long int object, ignoring the high bits.
556 Returns -1 and sets an error condition if an error occurs. */
557
Guido van Rossumddefaf32007-01-14 03:31:43 +0000558static unsigned long
559_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000560{
561 register PyLongObject *v;
562 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000563 Py_ssize_t i;
564 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000565
566 if (vv == NULL || !PyLong_Check(vv)) {
567 PyErr_BadInternalCall();
568 return (unsigned long) -1;
569 }
570 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000571 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000572 switch (i) {
573 case 0: return 0;
574 case 1: return v->ob_digit[0];
575 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000576 sign = 1;
577 x = 0;
578 if (i < 0) {
579 sign = -1;
580 i = -i;
581 }
582 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000583 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000584 }
585 return x * sign;
586}
587
Guido van Rossumddefaf32007-01-14 03:31:43 +0000588unsigned long
589PyLong_AsUnsignedLongMask(register PyObject *op)
590{
591 PyNumberMethods *nb;
592 PyLongObject *lo;
593 unsigned long val;
594
595 if (op && PyLong_Check(op))
596 return _PyLong_AsUnsignedLongMask(op);
597
598 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
599 nb->nb_int == NULL) {
600 PyErr_SetString(PyExc_TypeError, "an integer is required");
601 return (unsigned long)-1;
602 }
603
604 lo = (PyLongObject*) (*nb->nb_int) (op);
605 if (lo == NULL)
606 return (unsigned long)-1;
607 if (PyLong_Check(lo)) {
608 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
609 Py_DECREF(lo);
610 if (PyErr_Occurred())
611 return (unsigned long)-1;
612 return val;
613 }
614 else
615 {
616 Py_DECREF(lo);
617 PyErr_SetString(PyExc_TypeError,
618 "nb_int should return int object");
619 return (unsigned long)-1;
620 }
621}
622
Tim Peters5b8132f2003-01-31 15:52:05 +0000623int
624_PyLong_Sign(PyObject *vv)
625{
626 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000627
628 assert(v != NULL);
629 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000630
Christian Heimes90aa7642007-12-19 02:45:37 +0000631 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000632}
633
Tim Petersbaefd9e2003-01-28 20:37:45 +0000634size_t
635_PyLong_NumBits(PyObject *vv)
636{
637 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000638 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000639 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000640
641 assert(v != NULL);
642 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000643 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000644 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
645 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000646 digit msd = v->ob_digit[ndigits - 1];
647
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000648 result = (ndigits - 1) * PyLong_SHIFT;
649 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000650 goto Overflow;
651 do {
652 ++result;
653 if (result == 0)
654 goto Overflow;
655 msd >>= 1;
656 } while (msd);
657 }
658 return result;
659
660Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000661 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000662 "to express in a platform size_t");
663 return (size_t)-1;
664}
665
Tim Peters2a9b3672001-06-11 21:23:58 +0000666PyObject *
667_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
668 int little_endian, int is_signed)
669{
670 const unsigned char* pstartbyte;/* LSB of bytes */
671 int incr; /* direction to move pstartbyte */
672 const unsigned char* pendbyte; /* MSB of bytes */
673 size_t numsignificantbytes; /* number of bytes that matter */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000674 Py_ssize_t ndigits; /* number of Python long digits */
Tim Peters2a9b3672001-06-11 21:23:58 +0000675 PyLongObject* v; /* result */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000676 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000677
678 if (n == 0)
679 return PyLong_FromLong(0L);
680
681 if (little_endian) {
682 pstartbyte = bytes;
683 pendbyte = bytes + n - 1;
684 incr = 1;
685 }
686 else {
687 pstartbyte = bytes + n - 1;
688 pendbyte = bytes;
689 incr = -1;
690 }
691
692 if (is_signed)
693 is_signed = *pendbyte >= 0x80;
694
695 /* Compute numsignificantbytes. This consists of finding the most
696 significant byte. Leading 0 bytes are insignficant if the number
697 is positive, and leading 0xff bytes if negative. */
698 {
699 size_t i;
700 const unsigned char* p = pendbyte;
701 const int pincr = -incr; /* search MSB to LSB */
702 const unsigned char insignficant = is_signed ? 0xff : 0x00;
703
704 for (i = 0; i < n; ++i, p += pincr) {
705 if (*p != insignficant)
706 break;
707 }
708 numsignificantbytes = n - i;
709 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
710 actually has 2 significant bytes. OTOH, 0xff0001 ==
711 -0x00ffff, so we wouldn't *need* to bump it there; but we
712 do for 0xffff = -0x0001. To be safe without bothering to
713 check every case, bump it regardless. */
714 if (is_signed && numsignificantbytes < n)
715 ++numsignificantbytes;
716 }
717
718 /* How many Python long digits do we need? We have
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000719 8*numsignificantbytes bits, and each Python long digit has
720 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
721 /* catch overflow before it happens */
722 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
723 PyErr_SetString(PyExc_OverflowError,
724 "byte array too long to convert to int");
725 return NULL;
726 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000727 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000728 v = _PyLong_New(ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000729 if (v == NULL)
730 return NULL;
731
732 /* Copy the bits over. The tricky parts are computing 2's-comp on
733 the fly for signed numbers, and dealing with the mismatch between
734 8-bit bytes and (probably) 15-bit Python digits.*/
735 {
736 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000737 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000738 twodigits accum = 0; /* sliding register */
739 unsigned int accumbits = 0; /* number of bits in accum */
740 const unsigned char* p = pstartbyte;
741
742 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000743 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000744 /* Compute correction for 2's comp, if needed. */
745 if (is_signed) {
746 thisbyte = (0xff ^ thisbyte) + carry;
747 carry = thisbyte >> 8;
748 thisbyte &= 0xff;
749 }
750 /* Because we're going LSB to MSB, thisbyte is
751 more significant than what's already in accum,
752 so needs to be prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000753 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000754 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000755 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000756 /* There's enough to fill a Python digit. */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000757 assert(idigit < ndigits);
758 v->ob_digit[idigit] = (digit)(accum &
759 PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000760 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000761 accum >>= PyLong_SHIFT;
762 accumbits -= PyLong_SHIFT;
763 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000764 }
765 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000766 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000767 if (accumbits) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000768 assert(idigit < ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000769 v->ob_digit[idigit] = (digit)accum;
770 ++idigit;
771 }
772 }
773
Christian Heimes90aa7642007-12-19 02:45:37 +0000774 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000775 return (PyObject *)long_normalize(v);
776}
777
778int
779_PyLong_AsByteArray(PyLongObject* v,
780 unsigned char* bytes, size_t n,
781 int little_endian, int is_signed)
782{
Mark Dickinson17e55872009-01-24 15:56:57 +0000783 Py_ssize_t i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000784 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000785 twodigits accum; /* sliding register */
786 unsigned int accumbits; /* # bits in accum */
787 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
Mark Dickinson1e2d8702009-01-25 22:25:06 +0000788 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000789 size_t j; /* # bytes filled */
790 unsigned char* p; /* pointer to next byte in bytes */
791 int pincr; /* direction to move p */
792
793 assert(v != NULL && PyLong_Check(v));
794
Christian Heimes90aa7642007-12-19 02:45:37 +0000795 if (Py_SIZE(v) < 0) {
796 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000797 if (!is_signed) {
Mark Dickinson21776072009-02-10 16:13:25 +0000798 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000799 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000800 return -1;
801 }
802 do_twos_comp = 1;
803 }
804 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000805 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000806 do_twos_comp = 0;
807 }
808
809 if (little_endian) {
810 p = bytes;
811 pincr = 1;
812 }
813 else {
814 p = bytes + n - 1;
815 pincr = -1;
816 }
817
Tim Peters898cf852001-06-13 20:50:08 +0000818 /* Copy over all the Python digits.
819 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000820 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000821 normalized. */
822 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000823 j = 0;
824 accum = 0;
825 accumbits = 0;
826 carry = do_twos_comp ? 1 : 0;
827 for (i = 0; i < ndigits; ++i) {
Mark Dickinson17e55872009-01-24 15:56:57 +0000828 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000829 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000830 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
831 carry = thisdigit >> PyLong_SHIFT;
832 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000833 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000834 /* Because we're going LSB to MSB, thisdigit is more
835 significant than what's already in accum, so needs to be
836 prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000837 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000838
Tim Petersede05092001-06-14 08:53:38 +0000839 /* The most-significant digit may be (probably is) at least
840 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000841 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000842 /* Count # of sign bits -- they needn't be stored,
843 * although for signed conversion we need later to
Mark Dickinson17e55872009-01-24 15:56:57 +0000844 * make sure at least one sign bit gets stored. */
845 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
846 thisdigit;
847 while (s != 0) {
848 s >>= 1;
849 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000850 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000851 }
Mark Dickinson17e55872009-01-24 15:56:57 +0000852 else
853 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000854
Tim Peters2a9b3672001-06-11 21:23:58 +0000855 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000856 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000857 if (j >= n)
858 goto Overflow;
859 ++j;
860 *p = (unsigned char)(accum & 0xff);
861 p += pincr;
862 accumbits -= 8;
863 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000864 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000865 }
866
867 /* Store the straggler (if any). */
868 assert(accumbits < 8);
869 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000870 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000871 if (j >= n)
872 goto Overflow;
873 ++j;
874 if (do_twos_comp) {
875 /* Fill leading bits of the byte with sign bits
876 (appropriately pretending that the long had an
877 infinite supply of sign bits). */
878 accum |= (~(twodigits)0) << accumbits;
879 }
880 *p = (unsigned char)(accum & 0xff);
881 p += pincr;
882 }
Tim Peters05607ad2001-06-13 21:01:27 +0000883 else if (j == n && n > 0 && is_signed) {
884 /* The main loop filled the byte array exactly, so the code
885 just above didn't get to ensure there's a sign bit, and the
886 loop below wouldn't add one either. Make sure a sign bit
887 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000888 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000889 int sign_bit_set = msb >= 0x80;
890 assert(accumbits == 0);
891 if (sign_bit_set == do_twos_comp)
892 return 0;
893 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000894 goto Overflow;
895 }
Tim Peters05607ad2001-06-13 21:01:27 +0000896
897 /* Fill remaining bytes with copies of the sign bit. */
898 {
899 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
900 for ( ; j < n; ++j, p += pincr)
901 *p = signbyte;
902 }
903
Tim Peters2a9b3672001-06-11 21:23:58 +0000904 return 0;
905
906Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000907 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000908 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000909
Tim Peters2a9b3672001-06-11 21:23:58 +0000910}
911
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000912double
913_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
914{
915/* NBITS_WANTED should be > the number of bits in a double's precision,
916 but small enough so that 2**NBITS_WANTED is within the normal double
917 range. nbitsneeded is set to 1 less than that because the most-significant
918 Python digit contains at least 1 significant bit, but we don't want to
919 bother counting them (catering to the worst case cheaply).
920
921 57 is one more than VAX-D double precision; I (Tim) don't know of a double
922 format with more precision than that; it's 1 larger so that we add in at
923 least one round bit to stand in for the ignored least-significant bits.
924*/
925#define NBITS_WANTED 57
926 PyLongObject *v;
927 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000928 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000929 Py_ssize_t i;
930 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000931 int nbitsneeded;
932
933 if (vv == NULL || !PyLong_Check(vv)) {
934 PyErr_BadInternalCall();
935 return -1;
936 }
937 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000938 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000939 sign = 1;
940 if (i < 0) {
941 sign = -1;
942 i = -(i);
943 }
944 else if (i == 0) {
945 *exponent = 0;
946 return 0.0;
947 }
948 --i;
949 x = (double)v->ob_digit[i];
950 nbitsneeded = NBITS_WANTED - 1;
951 /* Invariant: i Python digits remain unaccounted for. */
952 while (i > 0 && nbitsneeded > 0) {
953 --i;
954 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000955 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000956 }
957 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000958 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000959 *exponent = i;
960 assert(x > 0.0);
961 return x * sign;
962#undef NBITS_WANTED
963}
964
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000965/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000966
967double
Tim Peters9f688bf2000-07-07 15:53:28 +0000968PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000969{
Thomas Wouters553489a2006-02-01 21:32:04 +0000970 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000971 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000972
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000973 if (vv == NULL || !PyLong_Check(vv)) {
974 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000975 return -1;
976 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000977 x = _PyLong_AsScaledDouble(vv, &e);
978 if (x == -1.0 && PyErr_Occurred())
979 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000980 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
981 set correctly after a successful _PyLong_AsScaledDouble() call */
982 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000983 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000984 goto overflow;
985 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000986 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000987 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000988 goto overflow;
989 return x;
990
991overflow:
992 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000993 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000994 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000995}
996
Guido van Rossum78694d91998-09-18 14:14:13 +0000997/* Create a new long (or int) object from a C pointer */
998
999PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001000PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001001{
Tim Peters70128a12001-06-16 08:48:40 +00001002#ifndef HAVE_LONG_LONG
1003# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1004#endif
1005#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001006# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001007#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +00001008 /* special-case null pointer */
1009 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +00001010 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001011 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +00001012
Guido van Rossum78694d91998-09-18 14:14:13 +00001013}
1014
1015/* Get a C pointer from a long object (or an int object in some cases) */
1016
1017void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001018PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001019{
1020 /* This function will allow int or long objects. If vv is neither,
1021 then the PyLong_AsLong*() functions will raise the exception:
1022 PyExc_SystemError, "bad argument to internal function"
1023 */
Tim Peters70128a12001-06-16 08:48:40 +00001024#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001025 long x;
1026
Guido van Rossumddefaf32007-01-14 03:31:43 +00001027 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001028 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001029 else
1030 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001031#else
Tim Peters70128a12001-06-16 08:48:40 +00001032
1033#ifndef HAVE_LONG_LONG
1034# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1035#endif
1036#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001037# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001038#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001039 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001040
Guido van Rossumddefaf32007-01-14 03:31:43 +00001041 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001042 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001043 else
1044 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001045
1046#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001047
1048 if (x == -1 && PyErr_Occurred())
1049 return NULL;
1050 return (void *)x;
1051}
1052
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001053#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001054
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001055/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001056 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001057 */
1058
Tim Peterscf37dfc2001-06-14 18:42:50 +00001059#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001060
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001061/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001062
1063PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001064PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001065{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001066 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +00001067 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001068 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1069 int ndigits = 0;
1070 int negative = 0;
1071
Guido van Rossumddefaf32007-01-14 03:31:43 +00001072 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +00001074 /* avoid signed overflow on negation; see comments
1075 in PyLong_FromLong above. */
1076 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001077 negative = 1;
1078 }
Christian Heimesdae2a892008-04-19 00:55:37 +00001079 else {
1080 abs_ival = (unsigned PY_LONG_LONG)ival;
1081 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001082
1083 /* Count the number of Python digits.
1084 We used to pick 5 ("big enough for anything"), but that's a
1085 waste of time and space given that 5*15 = 75 bits are rarely
1086 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001087 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088 while (t) {
1089 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001090 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091 }
1092 v = _PyLong_New(ndigits);
1093 if (v != NULL) {
1094 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001095 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001096 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001097 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001098 *p++ = (digit)(t & PyLong_MASK);
1099 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100 }
1101 }
1102 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001103}
1104
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001105/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001106
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001107PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001108PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001109{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001110 PyLongObject *v;
1111 unsigned PY_LONG_LONG t;
1112 int ndigits = 0;
1113
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001114 if (ival < PyLong_BASE)
Mark Dickinson50b2b6e2008-12-05 17:14:29 +00001115 return PyLong_FromLong((long)ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001116 /* Count the number of Python digits. */
1117 t = (unsigned PY_LONG_LONG)ival;
1118 while (t) {
1119 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001120 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001121 }
1122 v = _PyLong_New(ndigits);
1123 if (v != NULL) {
1124 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001125 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001126 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001127 *p++ = (digit)(ival & PyLong_MASK);
1128 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001129 }
1130 }
1131 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001132}
1133
Martin v. Löwis18e16552006-02-15 17:27:45 +00001134/* Create a new long int object from a C Py_ssize_t. */
1135
1136PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001137PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001138{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001139 PyLongObject *v;
1140 size_t abs_ival;
1141 size_t t; /* unsigned so >> doesn't propagate sign bit */
1142 int ndigits = 0;
1143 int negative = 0;
1144
1145 CHECK_SMALL_INT(ival);
1146 if (ival < 0) {
1147 /* avoid signed overflow when ival = SIZE_T_MIN */
1148 abs_ival = (size_t)(-1-ival)+1;
1149 negative = 1;
1150 }
1151 else {
1152 abs_ival = (size_t)ival;
1153 }
1154
1155 /* Count the number of Python digits. */
1156 t = abs_ival;
1157 while (t) {
1158 ++ndigits;
1159 t >>= PyLong_SHIFT;
1160 }
1161 v = _PyLong_New(ndigits);
1162 if (v != NULL) {
1163 digit *p = v->ob_digit;
1164 Py_SIZE(v) = negative ? -ndigits : ndigits;
1165 t = abs_ival;
1166 while (t) {
1167 *p++ = (digit)(t & PyLong_MASK);
1168 t >>= PyLong_SHIFT;
1169 }
1170 }
1171 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001172}
1173
1174/* Create a new long int object from a C size_t. */
1175
1176PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001177PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001178{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001179 PyLongObject *v;
1180 size_t t;
1181 int ndigits = 0;
1182
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001183 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001184 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001185 /* Count the number of Python digits. */
1186 t = ival;
1187 while (t) {
1188 ++ndigits;
1189 t >>= PyLong_SHIFT;
1190 }
1191 v = _PyLong_New(ndigits);
1192 if (v != NULL) {
1193 digit *p = v->ob_digit;
1194 Py_SIZE(v) = ndigits;
1195 while (ival) {
1196 *p++ = (digit)(ival & PyLong_MASK);
1197 ival >>= PyLong_SHIFT;
1198 }
1199 }
1200 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001201}
1202
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001203/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001204 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001205
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001206PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001207PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001208{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001209 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001210 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001211 int one = 1;
1212 int res;
1213
Tim Petersd38b1c72001-09-30 05:09:37 +00001214 if (vv == NULL) {
1215 PyErr_BadInternalCall();
1216 return -1;
1217 }
1218 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001219 PyNumberMethods *nb;
1220 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001221 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1222 nb->nb_int == NULL) {
1223 PyErr_SetString(PyExc_TypeError, "an integer is required");
1224 return -1;
1225 }
1226 io = (*nb->nb_int) (vv);
1227 if (io == NULL)
1228 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001229 if (PyLong_Check(io)) {
1230 bytes = PyLong_AsLongLong(io);
1231 Py_DECREF(io);
1232 return bytes;
1233 }
1234 Py_DECREF(io);
1235 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001236 return -1;
1237 }
1238
Guido van Rossumddefaf32007-01-14 03:31:43 +00001239 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001240 switch(Py_SIZE(v)) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00001241 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00001242 case 0: return 0;
1243 case 1: return v->ob_digit[0];
1244 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001245 res = _PyLong_AsByteArray(
1246 (PyLongObject *)vv, (unsigned char *)&bytes,
1247 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001248
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001249 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001250 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001251 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001252 else
1253 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001254}
1255
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001256/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001257 Return -1 and set an error if overflow occurs. */
1258
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001259unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001260PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001261{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001262 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001263 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001264 int one = 1;
1265 int res;
1266
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001267 if (vv == NULL || !PyLong_Check(vv)) {
1268 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001269 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001270 }
1271
Guido van Rossumddefaf32007-01-14 03:31:43 +00001272 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001273 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001274 case 0: return 0;
1275 case 1: return v->ob_digit[0];
1276 }
1277
Tim Petersd1a7da62001-06-13 00:35:57 +00001278 res = _PyLong_AsByteArray(
1279 (PyLongObject *)vv, (unsigned char *)&bytes,
1280 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001281
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001282 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001283 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001284 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001285 else
1286 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001287}
Tim Petersd1a7da62001-06-13 00:35:57 +00001288
Thomas Hellera4ea6032003-04-17 18:55:45 +00001289/* Get a C unsigned long int from a long int object, ignoring the high bits.
1290 Returns -1 and sets an error condition if an error occurs. */
1291
Guido van Rossumddefaf32007-01-14 03:31:43 +00001292static unsigned PY_LONG_LONG
1293_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001294{
1295 register PyLongObject *v;
1296 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001297 Py_ssize_t i;
1298 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001299
1300 if (vv == NULL || !PyLong_Check(vv)) {
1301 PyErr_BadInternalCall();
1302 return (unsigned long) -1;
1303 }
1304 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001305 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001306 case 0: return 0;
1307 case 1: return v->ob_digit[0];
1308 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001309 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001310 sign = 1;
1311 x = 0;
1312 if (i < 0) {
1313 sign = -1;
1314 i = -i;
1315 }
1316 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001317 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001318 }
1319 return x * sign;
1320}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001321
1322unsigned PY_LONG_LONG
1323PyLong_AsUnsignedLongLongMask(register PyObject *op)
1324{
1325 PyNumberMethods *nb;
1326 PyLongObject *lo;
1327 unsigned PY_LONG_LONG val;
1328
1329 if (op && PyLong_Check(op))
1330 return _PyLong_AsUnsignedLongLongMask(op);
1331
1332 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1333 nb->nb_int == NULL) {
1334 PyErr_SetString(PyExc_TypeError, "an integer is required");
1335 return (unsigned PY_LONG_LONG)-1;
1336 }
1337
1338 lo = (PyLongObject*) (*nb->nb_int) (op);
1339 if (lo == NULL)
1340 return (unsigned PY_LONG_LONG)-1;
1341 if (PyLong_Check(lo)) {
1342 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1343 Py_DECREF(lo);
1344 if (PyErr_Occurred())
1345 return (unsigned PY_LONG_LONG)-1;
1346 return val;
1347 }
1348 else
1349 {
1350 Py_DECREF(lo);
1351 PyErr_SetString(PyExc_TypeError,
1352 "nb_int should return int object");
1353 return (unsigned PY_LONG_LONG)-1;
1354 }
1355}
Tim Petersd1a7da62001-06-13 00:35:57 +00001356#undef IS_LITTLE_ENDIAN
1357
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001358#endif /* HAVE_LONG_LONG */
1359
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001360#define CHECK_BINOP(v,w) \
1361 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001362 Py_INCREF(Py_NotImplemented); \
1363 return Py_NotImplemented; \
1364 }
1365
Tim Peters877a2122002-08-12 05:09:36 +00001366/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1367 * is modified in place, by adding y to it. Carries are propagated as far as
1368 * x[m-1], and the remaining carry (0 or 1) is returned.
1369 */
1370static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001371v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001372{
Mark Dickinson17e55872009-01-24 15:56:57 +00001373 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001374 digit carry = 0;
1375
1376 assert(m >= n);
1377 for (i = 0; i < n; ++i) {
1378 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001379 x[i] = carry & PyLong_MASK;
1380 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001381 assert((carry & 1) == carry);
1382 }
1383 for (; carry && i < m; ++i) {
1384 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001385 x[i] = carry & PyLong_MASK;
1386 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001387 assert((carry & 1) == carry);
1388 }
1389 return carry;
1390}
1391
1392/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1393 * is modified in place, by subtracting y from it. Borrows are propagated as
1394 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1395 */
1396static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001397v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001398{
Mark Dickinson17e55872009-01-24 15:56:57 +00001399 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001400 digit borrow = 0;
1401
1402 assert(m >= n);
1403 for (i = 0; i < n; ++i) {
1404 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001405 x[i] = borrow & PyLong_MASK;
1406 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001407 borrow &= 1; /* keep only 1 sign bit */
1408 }
1409 for (; borrow && i < m; ++i) {
1410 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001411 x[i] = borrow & PyLong_MASK;
1412 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001413 borrow &= 1;
1414 }
1415 return borrow;
1416}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001417
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001418/* Multiply by a single digit, ignoring the sign. */
1419
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001420static PyLongObject *
Mark Dickinson5a74bf62009-02-15 11:04:38 +00001421mul1(PyLongObject *a, digit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001422{
Christian Heimes90aa7642007-12-19 02:45:37 +00001423 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001424 PyLongObject *z = _PyLong_New(size_a+1);
Mark Dickinson5a74bf62009-02-15 11:04:38 +00001425 twodigits carry = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001426 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001427
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001428 if (z == NULL)
1429 return NULL;
1430 for (i = 0; i < size_a; ++i) {
1431 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001432 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1433 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001434 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001435 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001436 return long_normalize(z);
1437}
1438
Tim Peters212e6142001-07-14 12:23:19 +00001439/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1440 in pout, and returning the remainder. pin and pout point at the LSD.
1441 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001442 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001443 immutable. */
1444
1445static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001446inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001447{
1448 twodigits rem = 0;
1449
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001450 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001451 pin += size;
1452 pout += size;
1453 while (--size >= 0) {
1454 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001455 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001456 *--pout = hi = (digit)(rem / n);
Mark Dickinson17e55872009-01-24 15:56:57 +00001457 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001458 }
1459 return (digit)rem;
1460}
1461
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001462/* Divide a long integer by a digit, returning both the quotient
1463 (as function result) and the remainder (through *prem).
1464 The sign of a is ignored; n should not be zero. */
1465
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001466static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001467divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001468{
Christian Heimes90aa7642007-12-19 02:45:37 +00001469 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001470 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001471
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001472 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001473 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001474 if (z == NULL)
1475 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001476 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001477 return long_normalize(z);
1478}
1479
1480/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001481 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001482 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001483
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001484PyObject *
1485_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001486{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001487 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001488 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001489 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001490 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001491 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001492 int bits;
1493 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001494
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001495 if (a == NULL || !PyLong_Check(a)) {
1496 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001497 return NULL;
1498 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001499 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001500 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001501
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001502 /* Compute a rough upper bound for the length of the string */
1503 i = base;
1504 bits = 0;
1505 while (i > 1) {
1506 ++bits;
1507 i >>= 1;
1508 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001509 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001510 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001511 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001512 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001513 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001514 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001515 return NULL;
1516 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001517 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001518 if (str == NULL)
1519 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001520 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001521 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001522 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001523 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001524
Christian Heimes90aa7642007-12-19 02:45:37 +00001525 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001526 *--p = '0';
1527 }
1528 else if ((base & (base - 1)) == 0) {
1529 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001530 twodigits accum = 0;
1531 int accumbits = 0; /* # of bits in accum */
1532 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001533 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001534 while ((i >>= 1) > 1)
1535 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001536
1537 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001538 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001539 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001540 assert(accumbits >= basebits);
1541 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001542 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001543 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001544 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001545 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001546 accumbits -= basebits;
1547 accum >>= basebits;
1548 } while (i < size_a-1 ? accumbits >= basebits :
1549 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001550 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001551 }
1552 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001553 /* Not 0, and base not a power of 2. Divide repeatedly by
1554 base, but for speed use the highest power of base that
1555 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001556 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001557 digit *pin = a->ob_digit;
1558 PyLongObject *scratch;
1559 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001560 digit powbase = base; /* powbase == base ** power */
1561 int power = 1;
1562 for (;;) {
Mark Dickinson134708a2009-02-25 20:33:49 +00001563 twodigits newpow = powbase * (twodigits)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001564 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001565 break;
1566 powbase = (digit)newpow;
1567 ++power;
1568 }
Tim Peters212e6142001-07-14 12:23:19 +00001569
1570 /* Get a scratch area for repeated division. */
1571 scratch = _PyLong_New(size);
1572 if (scratch == NULL) {
1573 Py_DECREF(str);
1574 return NULL;
1575 }
1576
1577 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001578 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001579 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001580 digit rem = inplace_divrem1(scratch->ob_digit,
1581 pin, size, powbase);
1582 pin = scratch->ob_digit; /* no need to use a again */
1583 if (pin[size - 1] == 0)
1584 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001585 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001586 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001587 Py_DECREF(str);
1588 return NULL;
1589 })
Tim Peters212e6142001-07-14 12:23:19 +00001590
1591 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001592 assert(ntostore > 0);
1593 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001594 digit nextrem = (digit)(rem / base);
1595 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001596 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001597 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001598 *--p = c;
1599 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001600 --ntostore;
1601 /* Termination is a bit delicate: must not
1602 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001603 remaining quotient and rem are both 0. */
1604 } while (ntostore && (size || rem));
1605 } while (size != 0);
1606 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001607 }
1608
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001609 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001610 *--p = 'x';
1611 *--p = '0';
1612 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001613 else if (base == 8) {
1614 *--p = 'o';
1615 *--p = '0';
1616 }
1617 else if (base == 2) {
1618 *--p = 'b';
1619 *--p = '0';
1620 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001621 else if (base != 10) {
1622 *--p = '#';
1623 *--p = '0' + base%10;
1624 if (base > 10)
1625 *--p = '0' + base/10;
1626 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001627 if (sign)
1628 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001629 if (p != PyUnicode_AS_UNICODE(str)) {
1630 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001631 assert(p > q);
1632 do {
1633 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001634 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001635 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1636 Py_DECREF(str);
1637 return NULL;
1638 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001639 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001640 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001641}
1642
Thomas Wouters477c8d52006-05-27 19:21:47 +00001643/* Table of digit values for 8-bit string -> integer conversion.
1644 * '0' maps to 0, ..., '9' maps to 9.
1645 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1646 * All other indices map to 37.
1647 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001648 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001649 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001650unsigned char _PyLong_DigitValue[256] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001651 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1652 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1653 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1654 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1655 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1656 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1657 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1658 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1659 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1660 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1661 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1662 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1663 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1664 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1665 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1666 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1667};
1668
1669/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001670 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1671 * non-digit (which may be *str!). A normalized long is returned.
1672 * The point to this routine is that it takes time linear in the number of
1673 * string characters.
1674 */
1675static PyLongObject *
1676long_from_binary_base(char **str, int base)
1677{
1678 char *p = *str;
1679 char *start = p;
1680 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001681 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001682 PyLongObject *z;
1683 twodigits accum;
1684 int bits_in_accum;
1685 digit *pdigit;
1686
1687 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1688 n = base;
1689 for (bits_per_char = -1; n; ++bits_per_char)
1690 n >>= 1;
1691 /* n <- total # of bits needed, while setting p to end-of-string */
1692 n = 0;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001693 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001694 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001695 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001696 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1697 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001698 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001699 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001700 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001701 return NULL;
1702 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001703 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001704 z = _PyLong_New(n);
1705 if (z == NULL)
1706 return NULL;
1707 /* Read string from right, and fill in long from left; i.e.,
1708 * from least to most significant in both.
1709 */
1710 accum = 0;
1711 bits_in_accum = 0;
1712 pdigit = z->ob_digit;
1713 while (--p >= start) {
Raymond Hettinger35631532009-01-09 03:58:09 +00001714 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001715 assert(k >= 0 && k < base);
Mark Dickinson17e55872009-01-24 15:56:57 +00001716 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001717 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001718 if (bits_in_accum >= PyLong_SHIFT) {
1719 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinson17e55872009-01-24 15:56:57 +00001720 assert(pdigit - z->ob_digit <= n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001721 accum >>= PyLong_SHIFT;
1722 bits_in_accum -= PyLong_SHIFT;
1723 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001724 }
1725 }
1726 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001727 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001728 *pdigit++ = (digit)accum;
Mark Dickinson17e55872009-01-24 15:56:57 +00001729 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001730 }
1731 while (pdigit - z->ob_digit < n)
1732 *pdigit++ = 0;
1733 return long_normalize(z);
1734}
1735
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001736PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001737PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001738{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001739 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001740 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001741 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001742 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001743 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001744
Guido van Rossum472c04f1996-12-05 21:57:21 +00001745 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001746 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001747 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001748 return NULL;
1749 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001750 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001751 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001752 if (*str == '+')
1753 ++str;
1754 else if (*str == '-') {
1755 ++str;
1756 sign = -1;
1757 }
1758 if (base == 0) {
1759 if (str[0] != '0')
1760 base = 10;
1761 else if (str[1] == 'x' || str[1] == 'X')
1762 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001763 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001764 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001765 else if (str[1] == 'b' || str[1] == 'B')
1766 base = 2;
1767 else {
1768 /* "old" (C-style) octal literal, now invalid.
1769 it might still be zero though */
1770 error_if_nonzero = 1;
1771 base = 10;
1772 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001773 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001774 if (str[0] == '0' &&
1775 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1776 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1777 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001778 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001779
Guido van Rossume6762971998-06-22 03:54:46 +00001780 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001781 if ((base & (base - 1)) == 0)
1782 z = long_from_binary_base(&str, base);
1783 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001784/***
1785Binary bases can be converted in time linear in the number of digits, because
1786Python's representation base is binary. Other bases (including decimal!) use
1787the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001788
Thomas Wouters477c8d52006-05-27 19:21:47 +00001789First some math: the largest integer that can be expressed in N base-B digits
1790is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1791case number of Python digits needed to hold it is the smallest integer n s.t.
1792
1793 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1794 BASE**n >= B**N [taking logs to base BASE]
1795 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1796
1797The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1798this quickly. A Python long with that much space is reserved near the start,
1799and the result is computed into it.
1800
1801The input string is actually treated as being in base base**i (i.e., i digits
1802are processed at a time), where two more static arrays hold:
1803
1804 convwidth_base[base] = the largest integer i such that base**i <= BASE
1805 convmultmax_base[base] = base ** convwidth_base[base]
1806
1807The first of these is the largest i such that i consecutive input digits
1808must fit in a single Python digit. The second is effectively the input
1809base we're really using.
1810
1811Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1812convmultmax_base[base], the result is "simply"
1813
1814 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1815
1816where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001817
1818Error analysis: as above, the number of Python digits `n` needed is worst-
1819case
1820
1821 n >= N * log(B)/log(BASE)
1822
1823where `N` is the number of input digits in base `B`. This is computed via
1824
1825 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1826
1827below. Two numeric concerns are how much space this can waste, and whether
1828the computed result can be too small. To be concrete, assume BASE = 2**15,
1829which is the default (and it's unlikely anyone changes that).
1830
1831Waste isn't a problem: provided the first input digit isn't 0, the difference
1832between the worst-case input with N digits and the smallest input with N
1833digits is about a factor of B, but B is small compared to BASE so at most
1834one allocated Python digit can remain unused on that count. If
1835N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1836and adding 1 returns a result 1 larger than necessary. However, that can't
1837happen: whenever B is a power of 2, long_from_binary_base() is called
1838instead, and it's impossible for B**i to be an integer power of 2**15 when
1839B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1840an exact integer when B is not a power of 2, since B**i has a prime factor
1841other than 2 in that case, but (2**15)**j's only prime factor is 2).
1842
1843The computed result can be too small if the true value of N*log(B)/log(BASE)
1844is a little bit larger than an exact integer, but due to roundoff errors (in
1845computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1846yields a numeric result a little less than that integer. Unfortunately, "how
1847close can a transcendental function get to an integer over some range?"
1848questions are generally theoretically intractable. Computer analysis via
1849continued fractions is practical: expand log(B)/log(BASE) via continued
1850fractions, giving a sequence i/j of "the best" rational approximations. Then
1851j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1852we can get very close to being in trouble, but very rarely. For example,
185376573 is a denominator in one of the continued-fraction approximations to
1854log(10)/log(2**15), and indeed:
1855
1856 >>> log(10)/log(2**15)*76573
1857 16958.000000654003
1858
1859is very close to an integer. If we were working with IEEE single-precision,
1860rounding errors could kill us. Finding worst cases in IEEE double-precision
1861requires better-than-double-precision log() functions, and Tim didn't bother.
1862Instead the code checks to see whether the allocated space is enough as each
1863new Python digit is added, and copies the whole thing to a larger long if not.
1864This should happen extremely rarely, and in fact I don't have a test case
1865that triggers it(!). Instead the code was tested by artificially allocating
1866just 1 digit at the start, so that the copying code was exercised for every
1867digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001868***/
1869 register twodigits c; /* current input character */
1870 Py_ssize_t size_z;
1871 int i;
1872 int convwidth;
1873 twodigits convmultmax, convmult;
1874 digit *pz, *pzstop;
1875 char* scan;
1876
1877 static double log_base_BASE[37] = {0.0e0,};
1878 static int convwidth_base[37] = {0,};
1879 static twodigits convmultmax_base[37] = {0,};
1880
1881 if (log_base_BASE[base] == 0.0) {
1882 twodigits convmax = base;
1883 int i = 1;
1884
1885 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001886 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001887 for (;;) {
1888 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001889 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001890 break;
1891 convmax = next;
1892 ++i;
1893 }
1894 convmultmax_base[base] = convmax;
1895 assert(i > 0);
1896 convwidth_base[base] = i;
1897 }
1898
1899 /* Find length of the string of numeric characters. */
1900 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001901 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001902 ++scan;
1903
1904 /* Create a long object that can contain the largest possible
1905 * integer with this base and length. Note that there's no
1906 * need to initialize z->ob_digit -- no slot is read up before
1907 * being stored into.
1908 */
1909 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001910 /* Uncomment next line to test exceedingly rare copy code */
1911 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001912 assert(size_z > 0);
1913 z = _PyLong_New(size_z);
1914 if (z == NULL)
1915 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001916 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001917
1918 /* `convwidth` consecutive input digits are treated as a single
1919 * digit in base `convmultmax`.
1920 */
1921 convwidth = convwidth_base[base];
1922 convmultmax = convmultmax_base[base];
1923
1924 /* Work ;-) */
1925 while (str < scan) {
1926 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001927 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00001928 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1929 c = (twodigits)(c * base +
Raymond Hettinger35631532009-01-09 03:58:09 +00001930 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001931 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001932 }
1933
1934 convmult = convmultmax;
1935 /* Calculate the shift only if we couldn't get
1936 * convwidth digits.
1937 */
1938 if (i != convwidth) {
1939 convmult = base;
1940 for ( ; i > 1; --i)
1941 convmult *= base;
1942 }
1943
1944 /* Multiply z by convmult, and add c. */
1945 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001946 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001947 for (; pz < pzstop; ++pz) {
1948 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001949 *pz = (digit)(c & PyLong_MASK);
1950 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001951 }
1952 /* carry off the current end? */
1953 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001954 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001955 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001956 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001957 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001958 }
1959 else {
1960 PyLongObject *tmp;
1961 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001962 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001963 tmp = _PyLong_New(size_z + 1);
1964 if (tmp == NULL) {
1965 Py_DECREF(z);
1966 return NULL;
1967 }
1968 memcpy(tmp->ob_digit,
1969 z->ob_digit,
1970 sizeof(digit) * size_z);
1971 Py_DECREF(z);
1972 z = tmp;
1973 z->ob_digit[size_z] = (digit)c;
1974 ++size_z;
1975 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001976 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001977 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001978 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001979 if (z == NULL)
1980 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001981 if (error_if_nonzero) {
1982 /* reset the base to 0, else the exception message
1983 doesn't make too much sense */
1984 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00001985 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001986 goto onError;
1987 /* there might still be other problems, therefore base
1988 remains zero here for the same reason */
1989 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001990 if (str == start)
1991 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001992 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00001993 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001994 while (*str && isspace(Py_CHARMASK(*str)))
1995 str++;
1996 if (*str != '\0')
1997 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001998 if (pend)
1999 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00002000 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002001 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002002
2003 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002004 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002005 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002006 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002007 if (strobj == NULL)
2008 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002009 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002010 "invalid literal for int() with base %d: %R",
2011 base, strobj);
2012 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002013 return NULL;
2014}
2015
2016PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002017PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002018{
Walter Dörwald07e14762002-11-06 16:15:14 +00002019 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002020 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002021
Walter Dörwald07e14762002-11-06 16:15:14 +00002022 if (buffer == NULL)
2023 return NULL;
2024
2025 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2026 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002027 return NULL;
2028 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002029 result = PyLong_FromString(buffer, NULL, base);
2030 PyMem_FREE(buffer);
2031 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002032}
2033
Tim Peters9f688bf2000-07-07 15:53:28 +00002034/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002035static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002036 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002037static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002038
2039/* Long division with remainder, top-level routine */
2040
Guido van Rossume32e0141992-01-19 16:31:05 +00002041static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002042long_divrem(PyLongObject *a, PyLongObject *b,
2043 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002044{
Christian Heimes90aa7642007-12-19 02:45:37 +00002045 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002046 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002047
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002048 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002049 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002050 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002051 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002052 }
2053 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002054 (size_a == size_b &&
2055 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002056 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002057 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002058 if (*pdiv == NULL)
2059 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002060 Py_INCREF(a);
2061 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002062 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002063 }
2064 if (size_b == 1) {
2065 digit rem = 0;
2066 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002067 if (z == NULL)
2068 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002069 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002070 if (*prem == NULL) {
2071 Py_DECREF(z);
2072 return -1;
2073 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002074 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002075 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002076 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002077 if (z == NULL)
2078 return -1;
2079 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002080 /* Set the signs.
2081 The quotient z has the sign of a*b;
2082 the remainder r has the sign of a,
2083 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002084 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002085 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002086 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002087 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002088 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002089 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090}
2091
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002092/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002093
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002094static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002095x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002096{
Christian Heimes90aa7642007-12-19 02:45:37 +00002097 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002098 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002099 PyLongObject *v = mul1(v1, d);
2100 PyLongObject *w = mul1(w1, d);
2101 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002102 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002103
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002104 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002105 Py_XDECREF(v);
2106 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002107 return NULL;
2108 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002109
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002110 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002111 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
2112 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002113
Christian Heimes90aa7642007-12-19 02:45:37 +00002114 size_v = ABS(Py_SIZE(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002115 k = size_v - size_w;
2116 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002117
Thomas Wouters477c8d52006-05-27 19:21:47 +00002118 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002119 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2120 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002121 stwodigits carry = 0;
Mark Dickinson17e55872009-01-24 15:56:57 +00002122 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002123
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002124 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002125 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002126 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002127 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002128 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002129 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002130 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002131 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002132 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002133 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002134
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002135 while (w->ob_digit[size_w-2]*q >
2136 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002137 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002138 + v->ob_digit[j-1]
2139 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002140 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002141 + v->ob_digit[j-2])
2142 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002143
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002144 for (i = 0; i < size_w && i+k < size_v; ++i) {
2145 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002146 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002147 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002148 + ((twodigits)zz << PyLong_SHIFT);
2149 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Mark Dickinsone4416742009-02-15 15:14:57 +00002150 carry = Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002151 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002152 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002153 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002154
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002155 if (i+k < size_v) {
2156 carry += v->ob_digit[i+k];
2157 v->ob_digit[i+k] = 0;
2158 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002159
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002160 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002161 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002162 else {
2163 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002164 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002165 carry = 0;
2166 for (i = 0; i < size_w && i+k < size_v; ++i) {
2167 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002168 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002169 carry = Py_ARITHMETIC_RIGHT_SHIFT(
Mark Dickinsone4416742009-02-15 15:14:57 +00002170 stwodigits,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002171 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002172 }
2173 }
2174 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002175
Guido van Rossumc206c761995-01-10 15:23:19 +00002176 if (a == NULL)
2177 *prem = NULL;
2178 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002179 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002180 *prem = divrem1(v, d, &d);
2181 /* d receives the (unused) remainder */
2182 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002183 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002184 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002185 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002186 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002187 Py_DECREF(v);
2188 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002189 return a;
2190}
2191
2192/* Methods */
2193
2194static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002195long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002196{
Christian Heimes90aa7642007-12-19 02:45:37 +00002197 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002198}
2199
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002200static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002201long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002202{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002203 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002204}
2205
2206static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002207long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002208{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002209 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002210
Christian Heimes90aa7642007-12-19 02:45:37 +00002211 if (Py_SIZE(a) != Py_SIZE(b)) {
2212 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002213 sign = 0;
2214 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002215 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002216 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002217 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002218 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002219 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2220 ;
2221 if (i < 0)
2222 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002223 else {
Mark Dickinsone4416742009-02-15 15:14:57 +00002224 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002225 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002226 sign = -sign;
2227 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002228 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002229 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002230}
2231
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002232#define TEST_COND(cond) \
2233 ((cond) ? Py_True : Py_False)
2234
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002235static PyObject *
2236long_richcompare(PyObject *self, PyObject *other, int op)
2237{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002238 int result;
2239 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002240 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002241 if (self == other)
2242 result = 0;
2243 else
2244 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2245 /* Convert the return value to a Boolean */
2246 switch (op) {
2247 case Py_EQ:
2248 v = TEST_COND(result == 0);
2249 break;
2250 case Py_NE:
2251 v = TEST_COND(result != 0);
2252 break;
2253 case Py_LE:
2254 v = TEST_COND(result <= 0);
2255 break;
2256 case Py_GE:
2257 v = TEST_COND(result >= 0);
2258 break;
2259 case Py_LT:
2260 v = TEST_COND(result == -1);
2261 break;
2262 case Py_GT:
2263 v = TEST_COND(result == 1);
2264 break;
2265 default:
2266 PyErr_BadArgument();
2267 return NULL;
2268 }
2269 Py_INCREF(v);
2270 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002271}
2272
Guido van Rossum9bfef441993-03-29 10:43:31 +00002273static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002274long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002275{
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002276 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002277 Py_ssize_t i;
2278 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002279
2280 /* This is designed so that Python ints and longs with the
2281 same value hash to the same value, otherwise comparisons
2282 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002283 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002284 switch(i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00002285 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00002286 case 0: return 0;
2287 case 1: return v->ob_digit[0];
2288 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002289 sign = 1;
2290 x = 0;
2291 if (i < 0) {
2292 sign = -1;
2293 i = -(i);
2294 }
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002295 /* The following loop produces a C unsigned long x such that x is
2296 congruent to the absolute value of v modulo ULONG_MAX. The
Thomas Woutersce272b62007-09-19 21:19:28 +00002297 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002298 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002299 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002300 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002301 x += v->ob_digit[i];
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002302 /* If the addition above overflowed we compensate by
2303 incrementing. This preserves the value modulo
2304 ULONG_MAX. */
2305 if (x < v->ob_digit[i])
Thomas Woutersce272b62007-09-19 21:19:28 +00002306 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002307 }
2308 x = x * sign;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002309 if (x == (unsigned long)-1)
2310 x = (unsigned long)-2;
2311 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002312}
2313
2314
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002315/* Add the absolute values of two long integers. */
2316
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002317static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002318x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002319{
Christian Heimes90aa7642007-12-19 02:45:37 +00002320 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002321 PyLongObject *z;
Mark Dickinson17e55872009-01-24 15:56:57 +00002322 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002323 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002324
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002325 /* Ensure a is the larger of the two: */
2326 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002327 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002328 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002329 size_a = size_b;
2330 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002331 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002332 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002333 if (z == NULL)
2334 return NULL;
2335 for (i = 0; i < size_b; ++i) {
2336 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002337 z->ob_digit[i] = carry & PyLong_MASK;
2338 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002339 }
2340 for (; i < size_a; ++i) {
2341 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002342 z->ob_digit[i] = carry & PyLong_MASK;
2343 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002344 }
2345 z->ob_digit[i] = carry;
2346 return long_normalize(z);
2347}
2348
2349/* Subtract the absolute values of two integers. */
2350
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002351static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002352x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002353{
Christian Heimes90aa7642007-12-19 02:45:37 +00002354 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002355 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002356 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002357 int sign = 1;
2358 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002359
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002360 /* Ensure a is the larger of the two: */
2361 if (size_a < size_b) {
2362 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002363 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002364 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002365 size_a = size_b;
2366 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002367 }
2368 else if (size_a == size_b) {
2369 /* Find highest digit where a and b differ: */
2370 i = size_a;
2371 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2372 ;
2373 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002374 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002375 if (a->ob_digit[i] < b->ob_digit[i]) {
2376 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002377 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002378 }
2379 size_a = size_b = i+1;
2380 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002381 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002382 if (z == NULL)
2383 return NULL;
2384 for (i = 0; i < size_b; ++i) {
2385 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002386 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002387 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002388 z->ob_digit[i] = borrow & PyLong_MASK;
2389 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002390 borrow &= 1; /* Keep only one sign bit */
2391 }
2392 for (; i < size_a; ++i) {
2393 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002394 z->ob_digit[i] = borrow & PyLong_MASK;
2395 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002396 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002397 }
2398 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002399 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002400 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002401 return long_normalize(z);
2402}
2403
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002404static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002405long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002406{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002407 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002408
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002409 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002410
Christian Heimes90aa7642007-12-19 02:45:37 +00002411 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002412 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002413 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002414 return result;
2415 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002416 if (Py_SIZE(a) < 0) {
2417 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002418 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002419 if (z != NULL && Py_SIZE(z) != 0)
2420 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002421 }
2422 else
2423 z = x_sub(b, a);
2424 }
2425 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002426 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002427 z = x_sub(a, b);
2428 else
2429 z = x_add(a, b);
2430 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002431 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002432}
2433
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002434static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002435long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002436{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002437 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002438
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002439 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002440
Christian Heimes90aa7642007-12-19 02:45:37 +00002441 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002442 PyObject* r;
2443 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002444 return r;
2445 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002446 if (Py_SIZE(a) < 0) {
2447 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002448 z = x_sub(a, b);
2449 else
2450 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002451 if (z != NULL && Py_SIZE(z) != 0)
2452 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002453 }
2454 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002455 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002456 z = x_add(a, b);
2457 else
2458 z = x_sub(a, b);
2459 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002460 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002461}
2462
Tim Peters5af4e6c2002-08-12 02:31:19 +00002463/* Grade school multiplication, ignoring the signs.
2464 * Returns the absolute value of the product, or NULL if error.
2465 */
2466static PyLongObject *
2467x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002468{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002469 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002470 Py_ssize_t size_a = ABS(Py_SIZE(a));
2471 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002472 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002473
Tim Peters5af4e6c2002-08-12 02:31:19 +00002474 z = _PyLong_New(size_a + size_b);
2475 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002476 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002477
Christian Heimes90aa7642007-12-19 02:45:37 +00002478 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002479 if (a == b) {
2480 /* Efficient squaring per HAC, Algorithm 14.16:
2481 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2482 * Gives slightly less than a 2x speedup when a == b,
2483 * via exploiting that each entry in the multiplication
2484 * pyramid appears twice (except for the size_a squares).
2485 */
2486 for (i = 0; i < size_a; ++i) {
2487 twodigits carry;
2488 twodigits f = a->ob_digit[i];
2489 digit *pz = z->ob_digit + (i << 1);
2490 digit *pa = a->ob_digit + i + 1;
2491 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002492
Tim Peters0973b992004-08-29 22:16:50 +00002493 SIGCHECK({
2494 Py_DECREF(z);
2495 return NULL;
2496 })
2497
2498 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002499 *pz++ = (digit)(carry & PyLong_MASK);
2500 carry >>= PyLong_SHIFT;
2501 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002502
2503 /* Now f is added in twice in each column of the
2504 * pyramid it appears. Same as adding f<<1 once.
2505 */
2506 f <<= 1;
2507 while (pa < paend) {
2508 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002509 *pz++ = (digit)(carry & PyLong_MASK);
2510 carry >>= PyLong_SHIFT;
2511 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002512 }
2513 if (carry) {
2514 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002515 *pz++ = (digit)(carry & PyLong_MASK);
2516 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002517 }
2518 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002519 *pz += (digit)(carry & PyLong_MASK);
2520 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002521 }
Tim Peters0973b992004-08-29 22:16:50 +00002522 }
2523 else { /* a is not the same as b -- gradeschool long mult */
2524 for (i = 0; i < size_a; ++i) {
2525 twodigits carry = 0;
2526 twodigits f = a->ob_digit[i];
2527 digit *pz = z->ob_digit + i;
2528 digit *pb = b->ob_digit;
2529 digit *pbend = b->ob_digit + size_b;
2530
2531 SIGCHECK({
2532 Py_DECREF(z);
2533 return NULL;
2534 })
2535
2536 while (pb < pbend) {
2537 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002538 *pz++ = (digit)(carry & PyLong_MASK);
2539 carry >>= PyLong_SHIFT;
2540 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002541 }
2542 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002543 *pz += (digit)(carry & PyLong_MASK);
2544 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002545 }
2546 }
Tim Peters44121a62002-08-12 06:17:58 +00002547 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002548}
2549
2550/* A helper for Karatsuba multiplication (k_mul).
2551 Takes a long "n" and an integer "size" representing the place to
2552 split, and sets low and high such that abs(n) == (high << size) + low,
2553 viewing the shift as being by digits. The sign bit is ignored, and
2554 the return values are >= 0.
2555 Returns 0 on success, -1 on failure.
2556*/
2557static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002558kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002559{
2560 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002561 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002562 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002563
2564 size_lo = MIN(size_n, size);
2565 size_hi = size_n - size_lo;
2566
2567 if ((hi = _PyLong_New(size_hi)) == NULL)
2568 return -1;
2569 if ((lo = _PyLong_New(size_lo)) == NULL) {
2570 Py_DECREF(hi);
2571 return -1;
2572 }
2573
2574 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2575 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2576
2577 *high = long_normalize(hi);
2578 *low = long_normalize(lo);
2579 return 0;
2580}
2581
Tim Peters60004642002-08-12 22:01:34 +00002582static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2583
Tim Peters5af4e6c2002-08-12 02:31:19 +00002584/* Karatsuba multiplication. Ignores the input signs, and returns the
2585 * absolute value of the product (or NULL if error).
2586 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2587 */
2588static PyLongObject *
2589k_mul(PyLongObject *a, PyLongObject *b)
2590{
Christian Heimes90aa7642007-12-19 02:45:37 +00002591 Py_ssize_t asize = ABS(Py_SIZE(a));
2592 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002593 PyLongObject *ah = NULL;
2594 PyLongObject *al = NULL;
2595 PyLongObject *bh = NULL;
2596 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002597 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002598 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002599 Py_ssize_t shift; /* the number of digits we split off */
2600 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002601
Tim Peters5af4e6c2002-08-12 02:31:19 +00002602 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2603 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2604 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002605 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002606 * By picking X to be a power of 2, "*X" is just shifting, and it's
2607 * been reduced to 3 multiplies on numbers half the size.
2608 */
2609
Tim Petersfc07e562002-08-12 02:54:10 +00002610 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002611 * is largest.
2612 */
Tim Peters738eda72002-08-12 15:08:20 +00002613 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002614 t1 = a;
2615 a = b;
2616 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002617
2618 i = asize;
2619 asize = bsize;
2620 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002621 }
2622
2623 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002624 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2625 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002626 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002627 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002628 else
2629 return x_mul(a, b);
2630 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002631
Tim Peters60004642002-08-12 22:01:34 +00002632 /* If a is small compared to b, splitting on b gives a degenerate
2633 * case with ah==0, and Karatsuba may be (even much) less efficient
2634 * than "grade school" then. However, we can still win, by viewing
2635 * b as a string of "big digits", each of width a->ob_size. That
2636 * leads to a sequence of balanced calls to k_mul.
2637 */
2638 if (2 * asize <= bsize)
2639 return k_lopsided_mul(a, b);
2640
Tim Petersd6974a52002-08-13 20:37:51 +00002641 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002642 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002643 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002644 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002645
Tim Peters0973b992004-08-29 22:16:50 +00002646 if (a == b) {
2647 bh = ah;
2648 bl = al;
2649 Py_INCREF(bh);
2650 Py_INCREF(bl);
2651 }
2652 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002653
Tim Petersd64c1de2002-08-12 17:36:03 +00002654 /* The plan:
2655 * 1. Allocate result space (asize + bsize digits: that's always
2656 * enough).
2657 * 2. Compute ah*bh, and copy into result at 2*shift.
2658 * 3. Compute al*bl, and copy into result at 0. Note that this
2659 * can't overlap with #2.
2660 * 4. Subtract al*bl from the result, starting at shift. This may
2661 * underflow (borrow out of the high digit), but we don't care:
2662 * we're effectively doing unsigned arithmetic mod
2663 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2664 * borrows and carries out of the high digit can be ignored.
2665 * 5. Subtract ah*bh from the result, starting at shift.
2666 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2667 * at shift.
2668 */
2669
2670 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002671 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002672 if (ret == NULL) goto fail;
2673#ifdef Py_DEBUG
2674 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002675 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002676#endif
Tim Peters44121a62002-08-12 06:17:58 +00002677
Tim Petersd64c1de2002-08-12 17:36:03 +00002678 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002679 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002680 assert(Py_SIZE(t1) >= 0);
2681 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002682 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002683 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002684
2685 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002686 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002687 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002688 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002689 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002690
Tim Petersd64c1de2002-08-12 17:36:03 +00002691 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002692 if ((t2 = k_mul(al, bl)) == NULL) {
2693 Py_DECREF(t1);
2694 goto fail;
2695 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002696 assert(Py_SIZE(t2) >= 0);
2697 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2698 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002699
2700 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002701 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002702 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002703 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002704
Tim Petersd64c1de2002-08-12 17:36:03 +00002705 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2706 * because it's fresher in cache.
2707 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002708 i = Py_SIZE(ret) - shift; /* # digits after shift */
2709 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002710 Py_DECREF(t2);
2711
Christian Heimes90aa7642007-12-19 02:45:37 +00002712 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002713 Py_DECREF(t1);
2714
Tim Petersd64c1de2002-08-12 17:36:03 +00002715 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002716 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2717 Py_DECREF(ah);
2718 Py_DECREF(al);
2719 ah = al = NULL;
2720
Tim Peters0973b992004-08-29 22:16:50 +00002721 if (a == b) {
2722 t2 = t1;
2723 Py_INCREF(t2);
2724 }
2725 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002726 Py_DECREF(t1);
2727 goto fail;
2728 }
2729 Py_DECREF(bh);
2730 Py_DECREF(bl);
2731 bh = bl = NULL;
2732
Tim Peters738eda72002-08-12 15:08:20 +00002733 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002734 Py_DECREF(t1);
2735 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002736 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002737 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002738
Tim Petersd6974a52002-08-13 20:37:51 +00002739 /* Add t3. It's not obvious why we can't run out of room here.
2740 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002741 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002742 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002743 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002744
Tim Peters5af4e6c2002-08-12 02:31:19 +00002745 return long_normalize(ret);
2746
2747 fail:
2748 Py_XDECREF(ret);
2749 Py_XDECREF(ah);
2750 Py_XDECREF(al);
2751 Py_XDECREF(bh);
2752 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002753 return NULL;
2754}
2755
Tim Petersd6974a52002-08-13 20:37:51 +00002756/* (*) Why adding t3 can't "run out of room" above.
2757
Tim Petersab86c2b2002-08-15 20:06:00 +00002758Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2759to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002760
Tim Petersab86c2b2002-08-15 20:06:00 +000027611. For any integer i, i = c(i/2) + f(i/2). In particular,
2762 bsize = c(bsize/2) + f(bsize/2).
27632. shift = f(bsize/2)
27643. asize <= bsize
27654. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2766 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002767
Tim Petersab86c2b2002-08-15 20:06:00 +00002768We allocated asize + bsize result digits, and add t3 into them at an offset
2769of shift. This leaves asize+bsize-shift allocated digit positions for t3
2770to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2771asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002772
Tim Petersab86c2b2002-08-15 20:06:00 +00002773bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2774at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002775
Tim Petersab86c2b2002-08-15 20:06:00 +00002776If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2777digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2778most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002779
Tim Petersab86c2b2002-08-15 20:06:00 +00002780The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002781
Tim Petersab86c2b2002-08-15 20:06:00 +00002782 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002783
Tim Petersab86c2b2002-08-15 20:06:00 +00002784and we have asize + c(bsize/2) available digit positions. We need to show
2785this is always enough. An instance of c(bsize/2) cancels out in both, so
2786the question reduces to whether asize digits is enough to hold
2787(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2788then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2789asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002790digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002791asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002792c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2793is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2794bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002795
Tim Peters48d52c02002-08-14 17:07:32 +00002796Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2797clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2798ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002799*/
2800
Tim Peters60004642002-08-12 22:01:34 +00002801/* b has at least twice the digits of a, and a is big enough that Karatsuba
2802 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2803 * of slices, each with a->ob_size digits, and multiply the slices by a,
2804 * one at a time. This gives k_mul balanced inputs to work with, and is
2805 * also cache-friendly (we compute one double-width slice of the result
2806 * at a time, then move on, never bactracking except for the helpful
2807 * single-width slice overlap between successive partial sums).
2808 */
2809static PyLongObject *
2810k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2811{
Christian Heimes90aa7642007-12-19 02:45:37 +00002812 const Py_ssize_t asize = ABS(Py_SIZE(a));
2813 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002814 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002815 PyLongObject *ret;
2816 PyLongObject *bslice = NULL;
2817
2818 assert(asize > KARATSUBA_CUTOFF);
2819 assert(2 * asize <= bsize);
2820
2821 /* Allocate result space, and zero it out. */
2822 ret = _PyLong_New(asize + bsize);
2823 if (ret == NULL)
2824 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002825 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002826
2827 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002828 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002829 if (bslice == NULL)
2830 goto fail;
2831
2832 nbdone = 0;
2833 while (bsize > 0) {
2834 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002835 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002836
2837 /* Multiply the next slice of b by a. */
2838 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2839 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002840 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002841 product = k_mul(a, bslice);
2842 if (product == NULL)
2843 goto fail;
2844
2845 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002846 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2847 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002848 Py_DECREF(product);
2849
2850 bsize -= nbtouse;
2851 nbdone += nbtouse;
2852 }
2853
2854 Py_DECREF(bslice);
2855 return long_normalize(ret);
2856
2857 fail:
2858 Py_DECREF(ret);
2859 Py_XDECREF(bslice);
2860 return NULL;
2861}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002862
2863static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002864long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002865{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002866 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002867
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002868 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002869
Mark Dickinsonbd792642009-03-18 20:06:12 +00002870 /* fast path for single-digit multiplication */
Christian Heimes90aa7642007-12-19 02:45:37 +00002871 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonbd792642009-03-18 20:06:12 +00002872 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
2873#ifdef HAVE_LONG_LONG
2874 return PyLong_FromLongLong((PY_LONG_LONG)v);
2875#else
2876 /* if we don't have long long then we're almost certainly
2877 using 15-bit digits, so v will fit in a long. In the
2878 unlikely event that we're using 30-bit digits on a platform
2879 without long long, a large v will just cause us to fall
2880 through to the general multiplication code below. */
2881 if (v >= LONG_MIN && v <= LONG_MAX)
2882 return PyLong_FromLong((long)v);
2883#endif
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002884 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002885
Tim Petersd64c1de2002-08-12 17:36:03 +00002886 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002887 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002888 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002889 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002890 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002891}
2892
Guido van Rossume32e0141992-01-19 16:31:05 +00002893/* The / and % operators are now defined in terms of divmod().
2894 The expression a mod b has the value a - b*floor(a/b).
2895 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002896 |a| by |b|, with the sign of a. This is also expressed
2897 as a - b*trunc(a/b), if trunc truncates towards zero.
2898 Some examples:
2899 a b a rem b a mod b
2900 13 10 3 3
2901 -13 10 -3 7
2902 13 -10 3 -7
2903 -13 -10 -3 -3
2904 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002905 have different signs. We then subtract one from the 'div'
2906 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002907
Tim Peters47e52ee2004-08-30 02:44:38 +00002908/* Compute
2909 * *pdiv, *pmod = divmod(v, w)
2910 * NULL can be passed for pdiv or pmod, in which case that part of
2911 * the result is simply thrown away. The caller owns a reference to
2912 * each of these it requests (does not pass NULL for).
2913 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002914static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002915l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002916 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002917{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002918 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002919
Guido van Rossume32e0141992-01-19 16:31:05 +00002920 if (long_divrem(v, w, &div, &mod) < 0)
2921 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002922 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2923 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002924 PyLongObject *temp;
2925 PyLongObject *one;
2926 temp = (PyLongObject *) long_add(mod, w);
2927 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002928 mod = temp;
2929 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002930 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002931 return -1;
2932 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002933 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002934 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002935 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2936 Py_DECREF(mod);
2937 Py_DECREF(div);
2938 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002939 return -1;
2940 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002941 Py_DECREF(one);
2942 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002943 div = temp;
2944 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002945 if (pdiv != NULL)
2946 *pdiv = div;
2947 else
2948 Py_DECREF(div);
2949
2950 if (pmod != NULL)
2951 *pmod = mod;
2952 else
2953 Py_DECREF(mod);
2954
Guido van Rossume32e0141992-01-19 16:31:05 +00002955 return 0;
2956}
2957
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002958static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002959long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002960{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002961 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002962
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002963 CHECK_BINOP(a, b);
2964 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002965 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002966 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002967}
2968
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002969static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002970long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002971{
Tim Peterse2a60002001-09-04 06:17:36 +00002972 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002973 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002974
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002975 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002976 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2977 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002978 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002979 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002980 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002981 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2982 but should really be set correctly after sucessful calls to
2983 _PyLong_AsScaledDouble() */
2984 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002985
2986 if (bd == 0.0) {
2987 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002988 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002989 return NULL;
2990 }
2991
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002992 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002993 ad /= bd; /* overflow/underflow impossible here */
2994 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002995 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002996 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002997 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002998 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002999 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003000 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00003001 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003002 goto overflow;
3003 return PyFloat_FromDouble(ad);
3004
3005overflow:
3006 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003007 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00003008 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003009
Tim Peters20dab9f2001-09-04 05:31:47 +00003010}
3011
3012static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003013long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003014{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003015 PyLongObject *mod;
3016
3017 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003018
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003019 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003020 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003021 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003022}
3023
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003024static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003025long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003026{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003027 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003028 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003029
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003030 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003031
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003032 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003033 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003034 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003035 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003036 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003037 PyTuple_SetItem(z, 0, (PyObject *) div);
3038 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003039 }
3040 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003041 Py_DECREF(div);
3042 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003043 }
3044 return z;
3045}
3046
Tim Peters47e52ee2004-08-30 02:44:38 +00003047/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003048static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003049long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003050{
Tim Peters47e52ee2004-08-30 02:44:38 +00003051 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3052 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003053
Tim Peters47e52ee2004-08-30 02:44:38 +00003054 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003055 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003056 PyLongObject *temp = NULL;
3057
3058 /* 5-ary values. If the exponent is large enough, table is
3059 * precomputed so that table[i] == a**i % c for i in range(32).
3060 */
3061 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3062 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3063
3064 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003065 CHECK_BINOP(v, w);
3066 a = (PyLongObject*)v; Py_INCREF(a);
3067 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003068 if (PyLong_Check(x)) {
3069 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003070 Py_INCREF(x);
3071 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003072 else if (x == Py_None)
3073 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003074 else {
3075 Py_DECREF(a);
3076 Py_DECREF(b);
3077 Py_INCREF(Py_NotImplemented);
3078 return Py_NotImplemented;
3079 }
Tim Peters4c483c42001-09-05 06:24:58 +00003080
Christian Heimes90aa7642007-12-19 02:45:37 +00003081 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003082 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003083 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003084 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003085 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003086 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003087 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003088 /* else return a float. This works because we know
3089 that this calls float_pow() which converts its
3090 arguments to double. */
3091 Py_DECREF(a);
3092 Py_DECREF(b);
3093 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003094 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003095 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003096
3097 if (c) {
3098 /* if modulus == 0:
3099 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003100 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003101 PyErr_SetString(PyExc_ValueError,
3102 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003103 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003104 }
3105
3106 /* if modulus < 0:
3107 negativeOutput = True
3108 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003109 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003110 negativeOutput = 1;
3111 temp = (PyLongObject *)_PyLong_Copy(c);
3112 if (temp == NULL)
3113 goto Error;
3114 Py_DECREF(c);
3115 c = temp;
3116 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003117 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003118 }
3119
3120 /* if modulus == 1:
3121 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003122 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003123 z = (PyLongObject *)PyLong_FromLong(0L);
3124 goto Done;
3125 }
3126
3127 /* if base < 0:
3128 base = base % modulus
3129 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003130 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003131 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003132 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003133 Py_DECREF(a);
3134 a = temp;
3135 temp = NULL;
3136 }
3137 }
3138
3139 /* At this point a, b, and c are guaranteed non-negative UNLESS
3140 c is NULL, in which case a may be negative. */
3141
3142 z = (PyLongObject *)PyLong_FromLong(1L);
3143 if (z == NULL)
3144 goto Error;
3145
3146 /* Perform a modular reduction, X = X % c, but leave X alone if c
3147 * is NULL.
3148 */
3149#define REDUCE(X) \
3150 if (c != NULL) { \
3151 if (l_divmod(X, c, NULL, &temp) < 0) \
3152 goto Error; \
3153 Py_XDECREF(X); \
3154 X = temp; \
3155 temp = NULL; \
3156 }
3157
3158 /* Multiply two values, then reduce the result:
3159 result = X*Y % c. If c is NULL, skip the mod. */
3160#define MULT(X, Y, result) \
3161{ \
3162 temp = (PyLongObject *)long_mul(X, Y); \
3163 if (temp == NULL) \
3164 goto Error; \
3165 Py_XDECREF(result); \
3166 result = temp; \
3167 temp = NULL; \
3168 REDUCE(result) \
3169}
3170
Christian Heimes90aa7642007-12-19 02:45:37 +00003171 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003172 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3173 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003174 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003175 digit bi = b->ob_digit[i];
3176
Mark Dickinsone4416742009-02-15 15:14:57 +00003177 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003178 MULT(z, z, z)
3179 if (bi & j)
3180 MULT(z, a, z)
3181 }
3182 }
3183 }
3184 else {
3185 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3186 Py_INCREF(z); /* still holds 1L */
3187 table[0] = z;
3188 for (i = 1; i < 32; ++i)
3189 MULT(table[i-1], a, table[i])
3190
Christian Heimes90aa7642007-12-19 02:45:37 +00003191 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003192 const digit bi = b->ob_digit[i];
3193
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003194 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003195 const int index = (bi >> j) & 0x1f;
3196 for (k = 0; k < 5; ++k)
3197 MULT(z, z, z)
3198 if (index)
3199 MULT(z, table[index], z)
3200 }
3201 }
3202 }
3203
Christian Heimes90aa7642007-12-19 02:45:37 +00003204 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003205 temp = (PyLongObject *)long_sub(z, c);
3206 if (temp == NULL)
3207 goto Error;
3208 Py_DECREF(z);
3209 z = temp;
3210 temp = NULL;
3211 }
3212 goto Done;
3213
3214 Error:
3215 if (z != NULL) {
3216 Py_DECREF(z);
3217 z = NULL;
3218 }
3219 /* fall through */
3220 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003221 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003222 for (i = 0; i < 32; ++i)
3223 Py_XDECREF(table[i]);
3224 }
Tim Petersde7990b2005-07-17 23:45:23 +00003225 Py_DECREF(a);
3226 Py_DECREF(b);
3227 Py_XDECREF(c);
3228 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003229 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003230}
3231
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003232static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003233long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003234{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003235 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003236 PyLongObject *x;
3237 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003238 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003239 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003240 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003241 if (w == NULL)
3242 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003243 x = (PyLongObject *) long_add(v, w);
3244 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003245 if (x == NULL)
3246 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003247 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003248 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003249}
3250
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003251static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003252long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003253{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003254 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003255 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003256 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003257 z = (PyLongObject *)_PyLong_Copy(v);
3258 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003259 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003260 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003261}
3262
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003263static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003264long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003265{
Christian Heimes90aa7642007-12-19 02:45:37 +00003266 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003267 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003268 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003269 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003270}
3271
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003272static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003273long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003274{
Christian Heimes90aa7642007-12-19 02:45:37 +00003275 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003276}
3277
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003278static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003279long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003280{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003281 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003282 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003283 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003284 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003285
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003286 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003287
Christian Heimes90aa7642007-12-19 02:45:37 +00003288 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003289 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003290 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003291 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003292 if (a1 == NULL)
3293 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003294 a2 = (PyLongObject *) long_rshift(a1, b);
3295 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003296 if (a2 == NULL)
3297 goto rshift_error;
3298 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003299 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003300 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003301 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003302
Neil Schemenauerba872e22001-01-04 01:46:03 +00003303 shiftby = PyLong_AsLong((PyObject *)b);
3304 if (shiftby == -1L && PyErr_Occurred())
3305 goto rshift_error;
3306 if (shiftby < 0) {
3307 PyErr_SetString(PyExc_ValueError,
3308 "negative shift count");
3309 goto rshift_error;
3310 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003311 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003312 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003313 if (newsize <= 0)
3314 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003315 loshift = shiftby % PyLong_SHIFT;
3316 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003317 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003318 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003319 z = _PyLong_New(newsize);
3320 if (z == NULL)
3321 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003322 if (Py_SIZE(a) < 0)
3323 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003324 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3325 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3326 if (i+1 < newsize)
3327 z->ob_digit[i] |=
3328 (a->ob_digit[j+1] << hishift) & himask;
3329 }
3330 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003331 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003332rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003333 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003334
Guido van Rossumc6913e71991-11-19 20:26:46 +00003335}
3336
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003337static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003338long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003339{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003340 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003341 PyLongObject *a = (PyLongObject*)v;
3342 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003343 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003344 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003345 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003346 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003347
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003348 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003349
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003350 shiftby = PyLong_AsLong((PyObject *)b);
3351 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003352 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003353 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003354 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003355 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003356 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003357 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003358 PyErr_SetString(PyExc_ValueError,
3359 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003360 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003361 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003362 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3363 wordshift = (int)shiftby / PyLong_SHIFT;
3364 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003365
Christian Heimes90aa7642007-12-19 02:45:37 +00003366 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003367 newsize = oldsize + wordshift;
3368 if (remshift)
3369 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003370 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003371 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003372 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003373 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003374 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003375 for (i = 0; i < wordshift; i++)
3376 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003377 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003378 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003379 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003380 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3381 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003382 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003383 if (remshift)
3384 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003385 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003386 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003387 z = long_normalize(z);
3388lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003389 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003390}
3391
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003392
3393/* Bitwise and/xor/or operations */
3394
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003395static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003396long_bitwise(PyLongObject *a,
3397 int op, /* '&', '|', '^' */
3398 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003399{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003400 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003401 int negz;
Mark Dickinsone4416742009-02-15 15:14:57 +00003402 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003403 PyLongObject *z;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003404 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003405 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003406
Christian Heimes90aa7642007-12-19 02:45:37 +00003407 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003408 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003409 if (a == NULL)
3410 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003411 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003412 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003413 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003414 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003415 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003416 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003417 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003418 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003419 if (b == NULL) {
3420 Py_DECREF(a);
3421 return NULL;
3422 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003423 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003424 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003425 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003426 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003427 maskb = 0;
3428 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003429
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003430 negz = 0;
3431 switch (op) {
3432 case '^':
3433 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003434 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003435 negz = -1;
3436 }
3437 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003438 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003439 if (maska && maskb) {
3440 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003441 maska ^= PyLong_MASK;
3442 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003443 negz = -1;
3444 }
3445 break;
3446 case '|':
3447 if (maska || maskb) {
3448 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003449 maska ^= PyLong_MASK;
3450 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003451 negz = -1;
3452 }
3453 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003454 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003455
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003456 /* JRH: The original logic here was to allocate the result value (z)
3457 as the longer of the two operands. However, there are some cases
3458 where the result is guaranteed to be shorter than that: AND of two
3459 positives, OR of two negatives: use the shorter number. AND with
3460 mixed signs: use the positive number. OR with mixed signs: use the
3461 negative number. After the transformations above, op will be '&'
3462 iff one of these cases applies, and mask will be non-0 for operands
3463 whose length should be ignored.
3464 */
3465
Christian Heimes90aa7642007-12-19 02:45:37 +00003466 size_a = Py_SIZE(a);
3467 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003468 size_z = op == '&'
3469 ? (maska
3470 ? size_b
3471 : (maskb ? size_a : MIN(size_a, size_b)))
3472 : MAX(size_a, size_b);
3473 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003474 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003475 Py_DECREF(a);
3476 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003477 return NULL;
3478 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003479
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003480 for (i = 0; i < size_z; ++i) {
3481 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3482 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3483 switch (op) {
3484 case '&': z->ob_digit[i] = diga & digb; break;
3485 case '|': z->ob_digit[i] = diga | digb; break;
3486 case '^': z->ob_digit[i] = diga ^ digb; break;
3487 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003488 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003489
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003490 Py_DECREF(a);
3491 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003492 z = long_normalize(z);
3493 if (negz == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003494 return (PyObject *) maybe_small_long(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003495 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003496 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003497 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003498}
3499
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003500static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003501long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003502{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003503 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003504 CHECK_BINOP(a, b);
3505 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003506 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003507}
3508
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003509static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003510long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003511{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003512 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003513 CHECK_BINOP(a, b);
3514 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003515 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003516}
3517
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003518static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003519long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003520{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003521 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003522 CHECK_BINOP(a, b);
3523 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003524 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003525}
3526
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003527static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003528long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003529{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003530 if (PyLong_CheckExact(v))
3531 Py_INCREF(v);
3532 else
3533 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003534 return v;
3535}
3536
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003537static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003538long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003539{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003540 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003541 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003542 if (result == -1.0 && PyErr_Occurred())
3543 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003544 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003545}
3546
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003547static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003548long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003549
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550static PyObject *
3551long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3552{
3553 PyObject *x = NULL;
3554 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003555 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003556
Guido van Rossumbef14172001-08-29 15:47:46 +00003557 if (type != &PyLong_Type)
3558 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003559 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003560 &x, &base))
3561 return NULL;
3562 if (x == NULL)
3563 return PyLong_FromLong(0L);
3564 if (base == -909)
3565 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003566 else if (PyUnicode_Check(x))
3567 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3568 PyUnicode_GET_SIZE(x),
3569 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003570 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003571 /* Since PyLong_FromString doesn't have a length parameter,
3572 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003573 char *string;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003574 Py_ssize_t size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003575 if (PyByteArray_Check(x))
3576 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003577 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003578 string = PyBytes_AS_STRING(x);
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003579 if (strlen(string) != (size_t)size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003580 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003581 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003582 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003583 "invalid literal for int() with base %d: %R",
3584 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003585 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003586 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003587 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003588 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003589 else {
3590 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003591 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003592 return NULL;
3593 }
3594}
3595
Guido van Rossumbef14172001-08-29 15:47:46 +00003596/* Wimpy, slow approach to tp_new calls for subtypes of long:
3597 first create a regular long from whatever arguments we got,
3598 then allocate a subtype instance and initialize it from
3599 the regular long. The regular long is then thrown away.
3600*/
3601static PyObject *
3602long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3603{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003604 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003605 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003606
3607 assert(PyType_IsSubtype(type, &PyLong_Type));
3608 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3609 if (tmp == NULL)
3610 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003611 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003612 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003613 if (n < 0)
3614 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003615 newobj = (PyLongObject *)type->tp_alloc(type, n);
3616 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003617 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003618 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003619 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003620 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003621 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003622 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003623 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003624 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003625 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003626}
3627
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003628static PyObject *
3629long_getnewargs(PyLongObject *v)
3630{
3631 return Py_BuildValue("(N)", _PyLong_Copy(v));
3632}
3633
Guido van Rossumb43daf72007-08-01 18:08:08 +00003634static PyObject *
3635long_getN(PyLongObject *v, void *context) {
Christian Heimesc36625b2008-01-04 13:33:00 +00003636 return PyLong_FromLong((Py_intptr_t)context);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003637}
3638
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003639static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003640long__format__(PyObject *self, PyObject *args)
3641{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003642 PyObject *format_spec;
3643
3644 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3645 return NULL;
3646 return _PyLong_FormatAdvanced(self,
3647 PyUnicode_AS_UNICODE(format_spec),
3648 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003649}
3650
Eric Smith8c663262007-08-25 02:26:07 +00003651static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003652long_round(PyObject *self, PyObject *args)
3653{
Mark Dickinson1124e712009-01-28 21:25:58 +00003654 PyObject *o_ndigits=NULL, *temp;
3655 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
3656 int errcode;
3657 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003658
Mark Dickinson1124e712009-01-28 21:25:58 +00003659 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
3660 the straightforward method is:
3661
3662 (1) divide by 10**n
3663 (2) round to nearest integer (round to even in case of tie)
3664 (3) multiply result by 10**n.
3665
3666 But the rounding step involves examining the fractional part of the
3667 quotient to see whether it's greater than 0.5 or not. Since we
3668 want to do the whole calculation in integer arithmetic, it's
3669 simpler to do:
3670
3671 (1) divide by (10**n)/2
3672 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
3673 (3) multiply result by (10**n)/2.
3674
3675 Then all we need to know about the fractional part of the quotient
3676 arising in step (2) is whether it's zero or not.
3677
3678 Doing both a multiplication and division is wasteful, and is easily
3679 avoided if we just figure out how much to adjust the original input
3680 by to do the rounding.
3681
3682 Here's the whole algorithm expressed in Python.
3683
3684 def round(self, ndigits = None):
3685 """round(int, int) -> int"""
3686 if ndigits is None or ndigits >= 0:
3687 return self
3688 pow = 10**-ndigits >> 1
3689 q, r = divmod(self, pow)
3690 self -= r
3691 if (q & 1 != 0):
3692 if (q & 2 == r == 0):
3693 self -= pow
3694 else:
3695 self += pow
3696 return self
3697
3698 */
3699 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
3700 return NULL;
3701 if (o_ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003702 return long_long(self);
3703
Mark Dickinson1124e712009-01-28 21:25:58 +00003704 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
3705 if (ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003706 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00003707
3708 if (Py_SIZE(ndigits) >= 0) {
3709 Py_DECREF(ndigits);
3710 return long_long(self);
3711 }
3712
3713 Py_INCREF(self); /* to keep refcounting simple */
3714 /* we now own references to self, ndigits */
3715
3716 /* pow = 10 ** -ndigits >> 1 */
3717 pow = (PyLongObject *)PyLong_FromLong(10L);
3718 if (pow == NULL)
3719 goto error;
3720 temp = long_neg(ndigits);
3721 Py_DECREF(ndigits);
3722 ndigits = (PyLongObject *)temp;
3723 if (ndigits == NULL)
3724 goto error;
3725 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
3726 Py_DECREF(pow);
3727 pow = (PyLongObject *)temp;
3728 if (pow == NULL)
3729 goto error;
3730 assert(PyLong_Check(pow)); /* check long_pow returned a long */
3731 one = (PyLongObject *)PyLong_FromLong(1L);
3732 if (one == NULL)
3733 goto error;
3734 temp = long_rshift(pow, one);
3735 Py_DECREF(one);
3736 Py_DECREF(pow);
3737 pow = (PyLongObject *)temp;
3738 if (pow == NULL)
3739 goto error;
3740
3741 /* q, r = divmod(self, pow) */
3742 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
3743 if (errcode == -1)
3744 goto error;
3745
3746 /* self -= r */
3747 temp = long_sub((PyLongObject *)self, r);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003748 Py_DECREF(self);
Mark Dickinson1124e712009-01-28 21:25:58 +00003749 self = temp;
3750 if (self == NULL)
3751 goto error;
3752
3753 /* get value of quotient modulo 4 */
3754 if (Py_SIZE(q) == 0)
3755 q_mod_4 = 0;
3756 else if (Py_SIZE(q) > 0)
3757 q_mod_4 = q->ob_digit[0] & 3;
3758 else
3759 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
3760
3761 if ((q_mod_4 & 1) == 1) {
3762 /* q is odd; round self up or down by adding or subtracting pow */
3763 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
3764 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
3765 else
3766 temp = (PyObject *)long_add((PyLongObject *)self, pow);
3767 Py_DECREF(self);
3768 self = temp;
3769 if (self == NULL)
3770 goto error;
3771 }
3772 Py_DECREF(q);
3773 Py_DECREF(r);
3774 Py_DECREF(pow);
3775 Py_DECREF(ndigits);
3776 return self;
3777
3778 error:
3779 Py_XDECREF(q);
3780 Py_XDECREF(r);
3781 Py_XDECREF(pow);
3782 Py_XDECREF(self);
3783 Py_XDECREF(ndigits);
3784 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003785}
3786
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003787static PyObject *
3788long_sizeof(PyLongObject *v)
3789{
3790 Py_ssize_t res;
3791
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003792 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003793 return PyLong_FromSsize_t(res);
3794}
3795
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003796static const unsigned char BitLengthTable[32] = {
3797 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
3798 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
3799};
3800
3801static PyObject *
3802long_bit_length(PyLongObject *v)
3803{
3804 PyLongObject *result, *x, *y;
3805 Py_ssize_t ndigits, msd_bits = 0;
3806 digit msd;
3807
3808 assert(v != NULL);
3809 assert(PyLong_Check(v));
3810
3811 ndigits = ABS(Py_SIZE(v));
3812 if (ndigits == 0)
3813 return PyLong_FromLong(0);
3814
3815 msd = v->ob_digit[ndigits-1];
3816 while (msd >= 32) {
3817 msd_bits += 6;
3818 msd >>= 6;
3819 }
3820 msd_bits += (long)(BitLengthTable[msd]);
3821
3822 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3823 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3824
3825 /* expression above may overflow; use Python integers instead */
3826 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3827 if (result == NULL)
3828 return NULL;
3829 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3830 if (x == NULL)
3831 goto error;
3832 y = (PyLongObject *)long_mul(result, x);
3833 Py_DECREF(x);
3834 if (y == NULL)
3835 goto error;
3836 Py_DECREF(result);
3837 result = y;
3838
3839 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3840 if (x == NULL)
3841 goto error;
3842 y = (PyLongObject *)long_add(result, x);
3843 Py_DECREF(x);
3844 if (y == NULL)
3845 goto error;
3846 Py_DECREF(result);
3847 result = y;
3848
3849 return (PyObject *)result;
3850
3851error:
3852 Py_DECREF(result);
3853 return NULL;
3854}
3855
3856PyDoc_STRVAR(long_bit_length_doc,
3857"int.bit_length() -> int\n\
3858\n\
3859Number of bits necessary to represent self in binary.\n\
3860>>> bin(37)\n\
3861'0b100101'\n\
3862>>> (37).bit_length()\n\
38636");
3864
Christian Heimes53876d92008-04-19 00:31:39 +00003865#if 0
3866static PyObject *
3867long_is_finite(PyObject *v)
3868{
3869 Py_RETURN_TRUE;
3870}
3871#endif
3872
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003873static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003874 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3875 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003876 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3877 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00003878#if 0
3879 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3880 "Returns always True."},
3881#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003882 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3883 "Truncating an Integral returns itself."},
3884 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3885 "Flooring an Integral returns itself."},
3886 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3887 "Ceiling of an Integral returns itself."},
3888 {"__round__", (PyCFunction)long_round, METH_VARARGS,
Mark Dickinson1124e712009-01-28 21:25:58 +00003889 "Rounding an Integral returns itself.\n"
3890 "Rounding with an ndigits argument also returns an integer."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003891 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003892 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003893 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
3894 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003895 {NULL, NULL} /* sentinel */
3896};
3897
Guido van Rossumb43daf72007-08-01 18:08:08 +00003898static PyGetSetDef long_getset[] = {
3899 {"real",
3900 (getter)long_long, (setter)NULL,
3901 "the real part of a complex number",
3902 NULL},
3903 {"imag",
3904 (getter)long_getN, (setter)NULL,
3905 "the imaginary part of a complex number",
3906 (void*)0},
3907 {"numerator",
3908 (getter)long_long, (setter)NULL,
3909 "the numerator of a rational number in lowest terms",
3910 NULL},
3911 {"denominator",
3912 (getter)long_getN, (setter)NULL,
3913 "the denominator of a rational number in lowest terms",
3914 (void*)1},
3915 {NULL} /* Sentinel */
3916};
3917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003918PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003919"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003920\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003921Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003922point argument will be truncated towards zero (this does not include a\n\
3923string representation of a floating point number!) When converting a\n\
3924string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003925converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003926
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003927static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003928 (binaryfunc) long_add, /*nb_add*/
3929 (binaryfunc) long_sub, /*nb_subtract*/
3930 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003931 long_mod, /*nb_remainder*/
3932 long_divmod, /*nb_divmod*/
3933 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003934 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003935 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003936 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003937 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003938 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003939 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003940 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003941 long_and, /*nb_and*/
3942 long_xor, /*nb_xor*/
3943 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003944 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00003945 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003946 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003947 0, /* nb_inplace_add */
3948 0, /* nb_inplace_subtract */
3949 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003950 0, /* nb_inplace_remainder */
3951 0, /* nb_inplace_power */
3952 0, /* nb_inplace_lshift */
3953 0, /* nb_inplace_rshift */
3954 0, /* nb_inplace_and */
3955 0, /* nb_inplace_xor */
3956 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003957 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003958 long_true_divide, /* nb_true_divide */
3959 0, /* nb_inplace_floor_divide */
3960 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003961 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003962};
3963
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003964PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003965 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003966 "int", /* tp_name */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003967 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003968 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003969 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003970 0, /* tp_print */
3971 0, /* tp_getattr */
3972 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003973 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003974 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003975 &long_as_number, /* tp_as_number */
3976 0, /* tp_as_sequence */
3977 0, /* tp_as_mapping */
3978 (hashfunc)long_hash, /* tp_hash */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003979 0, /* tp_call */
3980 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981 PyObject_GenericGetAttr, /* tp_getattro */
3982 0, /* tp_setattro */
3983 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003984 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3985 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003986 long_doc, /* tp_doc */
3987 0, /* tp_traverse */
3988 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003989 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003990 0, /* tp_weaklistoffset */
3991 0, /* tp_iter */
3992 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003993 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003994 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003995 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003996 0, /* tp_base */
3997 0, /* tp_dict */
3998 0, /* tp_descr_get */
3999 0, /* tp_descr_set */
4000 0, /* tp_dictoffset */
4001 0, /* tp_init */
4002 0, /* tp_alloc */
4003 long_new, /* tp_new */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004004 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004005};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004006
Mark Dickinsonbd792642009-03-18 20:06:12 +00004007static PyTypeObject Int_InfoType;
4008
4009PyDoc_STRVAR(int_info__doc__,
4010"sys.int_info\n\
4011\n\
4012A struct sequence that holds information about Python's\n\
4013internal representation of integers. The attributes are read only.");
4014
4015static PyStructSequence_Field int_info_fields[] = {
4016 {"bits_per_digit", "size of a digit in bits"},
4017 {"sizeof_digit", "size in bytes of the C type used to "
4018 "represent a digit"},
4019 {NULL, NULL}
4020};
4021
4022static PyStructSequence_Desc int_info_desc = {
4023 "sys.int_info", /* name */
4024 int_info__doc__, /* doc */
4025 int_info_fields, /* fields */
4026 2 /* number of fields */
4027};
4028
4029PyObject *
4030PyLong_GetInfo(void)
4031{
4032 PyObject* int_info;
4033 int field = 0;
4034 int_info = PyStructSequence_New(&Int_InfoType);
4035 if (int_info == NULL)
4036 return NULL;
4037 PyStructSequence_SET_ITEM(int_info, field++, PyLong_FromLong(PyLong_SHIFT));
4038 PyStructSequence_SET_ITEM(int_info, field++, PyLong_FromLong(sizeof(digit)));
4039 if (PyErr_Occurred()) {
4040 Py_CLEAR(int_info);
4041 return NULL;
4042 }
4043 return int_info;
4044}
4045
Guido van Rossumddefaf32007-01-14 03:31:43 +00004046int
4047_PyLong_Init(void)
4048{
4049#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004050 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004051 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004052
4053 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4054 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4055 if (Py_TYPE(v) == &PyLong_Type) {
4056 /* The element is already initialized, most likely
4057 * the Python interpreter was initialized before.
4058 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00004059 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004060 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004061
Christian Heimes48aa4b12008-02-01 16:56:30 +00004062 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4063 _Py_NewReference(op);
4064 /* _Py_NewReference sets the ref count to 1 but
4065 * the ref count might be larger. Set the refcnt
4066 * to the original refcnt + 1 */
4067 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004068 assert(Py_SIZE(op) == size);
4069 assert(v->ob_digit[0] == abs(ival));
4070 }
4071 else {
4072 PyObject_INIT(v, &PyLong_Type);
4073 }
4074 Py_SIZE(v) = size;
4075 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004076 }
4077#endif
Mark Dickinsonbd792642009-03-18 20:06:12 +00004078 /* initialize int_info */
4079 if (Int_InfoType.tp_name == 0)
4080 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
4081
Guido van Rossumddefaf32007-01-14 03:31:43 +00004082 return 1;
4083}
4084
4085void
4086PyLong_Fini(void)
4087{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004088 /* Integers are currently statically allocated. Py_DECREF is not
4089 needed, but Python must forget about the reference or multiple
4090 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004091#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004092 int i;
4093 PyLongObject *v = small_ints;
4094 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4095 _Py_DEC_REFTOTAL;
4096 _Py_ForgetReference((PyObject*)v);
4097 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004098#endif
4099}