blob: 598c873f5954248aadbb285999e1472ee0dc2e6f [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
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001366/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1367 2**k if d is nonzero, else 0. */
1368
1369static const unsigned char BitLengthTable[32] = {
1370 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1371 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1372};
1373
1374static int
1375bits_in_digit(digit d)
1376{
1377 int d_bits = 0;
1378 while (d >= 32) {
1379 d_bits += 6;
1380 d >>= 6;
1381 }
1382 d_bits += (int)BitLengthTable[d];
1383 return d_bits;
1384}
1385
Tim Peters877a2122002-08-12 05:09:36 +00001386/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1387 * is modified in place, by adding y to it. Carries are propagated as far as
1388 * x[m-1], and the remaining carry (0 or 1) is returned.
1389 */
1390static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001391v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001392{
Mark Dickinson17e55872009-01-24 15:56:57 +00001393 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001394 digit carry = 0;
1395
1396 assert(m >= n);
1397 for (i = 0; i < n; ++i) {
1398 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001399 x[i] = carry & PyLong_MASK;
1400 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001401 assert((carry & 1) == carry);
1402 }
1403 for (; carry && i < m; ++i) {
1404 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001405 x[i] = carry & PyLong_MASK;
1406 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001407 assert((carry & 1) == carry);
1408 }
1409 return carry;
1410}
1411
1412/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1413 * is modified in place, by subtracting y from it. Borrows are propagated as
1414 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1415 */
1416static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001417v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001418{
Mark Dickinson17e55872009-01-24 15:56:57 +00001419 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001420 digit borrow = 0;
1421
1422 assert(m >= n);
1423 for (i = 0; i < n; ++i) {
1424 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001425 x[i] = borrow & PyLong_MASK;
1426 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001427 borrow &= 1; /* keep only 1 sign bit */
1428 }
1429 for (; borrow && i < m; ++i) {
1430 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001431 x[i] = borrow & PyLong_MASK;
1432 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001433 borrow &= 1;
1434 }
1435 return borrow;
1436}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001437
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001438/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1439 * result in z[0:m], and return the d bits shifted out of the top.
1440 */
1441static digit
1442v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001443{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001444 Py_ssize_t i;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001445 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001446
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001447 assert(0 <= d && d < PyLong_SHIFT);
1448 for (i=0; i < m; i++) {
1449 twodigits acc = (twodigits)a[i] << d | carry;
1450 z[i] = (digit)acc & PyLong_MASK;
1451 carry = (digit)(acc >> PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001452 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001453 return carry;
1454}
1455
1456/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1457 * result in z[0:m], and return the d bits shifted out of the bottom.
1458 */
1459static digit
1460v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1461{
1462 Py_ssize_t i;
1463 digit carry = 0;
1464 digit mask = ((digit)1 << d) - 1U;
1465
1466 assert(0 <= d && d < PyLong_SHIFT);
1467 for (i=m; i-- > 0;) {
1468 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1469 carry = (digit)acc & mask;
1470 z[i] = (digit)(acc >> d);
1471 }
1472 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001473}
1474
Tim Peters212e6142001-07-14 12:23:19 +00001475/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1476 in pout, and returning the remainder. pin and pout point at the LSD.
1477 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001478 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001479 immutable. */
1480
1481static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001482inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001483{
1484 twodigits rem = 0;
1485
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001486 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001487 pin += size;
1488 pout += size;
1489 while (--size >= 0) {
1490 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001491 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001492 *--pout = hi = (digit)(rem / n);
Mark Dickinson17e55872009-01-24 15:56:57 +00001493 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001494 }
1495 return (digit)rem;
1496}
1497
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001498/* Divide a long integer by a digit, returning both the quotient
1499 (as function result) and the remainder (through *prem).
1500 The sign of a is ignored; n should not be zero. */
1501
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001502static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001503divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001504{
Christian Heimes90aa7642007-12-19 02:45:37 +00001505 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001506 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001507
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001508 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001509 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001510 if (z == NULL)
1511 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001512 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001513 return long_normalize(z);
1514}
1515
1516/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001517 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001518 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001519
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001520PyObject *
1521_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001522{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001523 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001524 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001525 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001526 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001527 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001528 int bits;
1529 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001530
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001531 if (a == NULL || !PyLong_Check(a)) {
1532 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001533 return NULL;
1534 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001535 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001536 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001537
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001538 /* Compute a rough upper bound for the length of the string */
1539 i = base;
1540 bits = 0;
1541 while (i > 1) {
1542 ++bits;
1543 i >>= 1;
1544 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001545 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001546 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001547 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001548 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001549 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001550 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001551 return NULL;
1552 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001553 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001554 if (str == NULL)
1555 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001556 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001557 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001558 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001559 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001560
Christian Heimes90aa7642007-12-19 02:45:37 +00001561 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001562 *--p = '0';
1563 }
1564 else if ((base & (base - 1)) == 0) {
1565 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001566 twodigits accum = 0;
1567 int accumbits = 0; /* # of bits in accum */
1568 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001569 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001570 while ((i >>= 1) > 1)
1571 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001572
1573 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001574 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001575 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001576 assert(accumbits >= basebits);
1577 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001578 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001579 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001580 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001581 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001582 accumbits -= basebits;
1583 accum >>= basebits;
1584 } while (i < size_a-1 ? accumbits >= basebits :
1585 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001586 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001587 }
1588 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001589 /* Not 0, and base not a power of 2. Divide repeatedly by
1590 base, but for speed use the highest power of base that
1591 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001592 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001593 digit *pin = a->ob_digit;
1594 PyLongObject *scratch;
1595 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001596 digit powbase = base; /* powbase == base ** power */
1597 int power = 1;
1598 for (;;) {
Mark Dickinson134708a2009-02-25 20:33:49 +00001599 twodigits newpow = powbase * (twodigits)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001600 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001601 break;
1602 powbase = (digit)newpow;
1603 ++power;
1604 }
Tim Peters212e6142001-07-14 12:23:19 +00001605
1606 /* Get a scratch area for repeated division. */
1607 scratch = _PyLong_New(size);
1608 if (scratch == NULL) {
1609 Py_DECREF(str);
1610 return NULL;
1611 }
1612
1613 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001614 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001615 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001616 digit rem = inplace_divrem1(scratch->ob_digit,
1617 pin, size, powbase);
1618 pin = scratch->ob_digit; /* no need to use a again */
1619 if (pin[size - 1] == 0)
1620 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001621 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001622 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001623 Py_DECREF(str);
1624 return NULL;
1625 })
Tim Peters212e6142001-07-14 12:23:19 +00001626
1627 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001628 assert(ntostore > 0);
1629 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001630 digit nextrem = (digit)(rem / base);
1631 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001632 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001633 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001634 *--p = c;
1635 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001636 --ntostore;
1637 /* Termination is a bit delicate: must not
1638 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001639 remaining quotient and rem are both 0. */
1640 } while (ntostore && (size || rem));
1641 } while (size != 0);
1642 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001643 }
1644
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001645 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001646 *--p = 'x';
1647 *--p = '0';
1648 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001649 else if (base == 8) {
1650 *--p = 'o';
1651 *--p = '0';
1652 }
1653 else if (base == 2) {
1654 *--p = 'b';
1655 *--p = '0';
1656 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001657 else if (base != 10) {
1658 *--p = '#';
1659 *--p = '0' + base%10;
1660 if (base > 10)
1661 *--p = '0' + base/10;
1662 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001663 if (sign)
1664 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001665 if (p != PyUnicode_AS_UNICODE(str)) {
1666 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001667 assert(p > q);
1668 do {
1669 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001670 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001671 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1672 Py_DECREF(str);
1673 return NULL;
1674 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001675 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001676 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001677}
1678
Thomas Wouters477c8d52006-05-27 19:21:47 +00001679/* Table of digit values for 8-bit string -> integer conversion.
1680 * '0' maps to 0, ..., '9' maps to 9.
1681 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1682 * All other indices map to 37.
1683 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001684 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001685 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001686unsigned char _PyLong_DigitValue[256] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001687 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1688 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1689 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1690 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1691 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1692 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1693 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1694 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1695 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1696 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1697 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1698 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1699 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1700 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1701 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1702 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1703};
1704
1705/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001706 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1707 * non-digit (which may be *str!). A normalized long is returned.
1708 * The point to this routine is that it takes time linear in the number of
1709 * string characters.
1710 */
1711static PyLongObject *
1712long_from_binary_base(char **str, int base)
1713{
1714 char *p = *str;
1715 char *start = p;
1716 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001717 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001718 PyLongObject *z;
1719 twodigits accum;
1720 int bits_in_accum;
1721 digit *pdigit;
1722
1723 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1724 n = base;
1725 for (bits_per_char = -1; n; ++bits_per_char)
1726 n >>= 1;
1727 /* n <- total # of bits needed, while setting p to end-of-string */
1728 n = 0;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001729 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001730 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001731 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001732 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1733 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001734 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001735 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001736 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001737 return NULL;
1738 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001739 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001740 z = _PyLong_New(n);
1741 if (z == NULL)
1742 return NULL;
1743 /* Read string from right, and fill in long from left; i.e.,
1744 * from least to most significant in both.
1745 */
1746 accum = 0;
1747 bits_in_accum = 0;
1748 pdigit = z->ob_digit;
1749 while (--p >= start) {
Raymond Hettinger35631532009-01-09 03:58:09 +00001750 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001751 assert(k >= 0 && k < base);
Mark Dickinson17e55872009-01-24 15:56:57 +00001752 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001753 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001754 if (bits_in_accum >= PyLong_SHIFT) {
1755 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinson17e55872009-01-24 15:56:57 +00001756 assert(pdigit - z->ob_digit <= n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001757 accum >>= PyLong_SHIFT;
1758 bits_in_accum -= PyLong_SHIFT;
1759 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001760 }
1761 }
1762 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001763 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001764 *pdigit++ = (digit)accum;
Mark Dickinson17e55872009-01-24 15:56:57 +00001765 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001766 }
1767 while (pdigit - z->ob_digit < n)
1768 *pdigit++ = 0;
1769 return long_normalize(z);
1770}
1771
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001772PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001773PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001774{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001775 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001776 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001777 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001778 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001779 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001780
Guido van Rossum472c04f1996-12-05 21:57:21 +00001781 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001782 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001783 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001784 return NULL;
1785 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001786 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001787 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001788 if (*str == '+')
1789 ++str;
1790 else if (*str == '-') {
1791 ++str;
1792 sign = -1;
1793 }
1794 if (base == 0) {
1795 if (str[0] != '0')
1796 base = 10;
1797 else if (str[1] == 'x' || str[1] == 'X')
1798 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001799 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001800 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001801 else if (str[1] == 'b' || str[1] == 'B')
1802 base = 2;
1803 else {
1804 /* "old" (C-style) octal literal, now invalid.
1805 it might still be zero though */
1806 error_if_nonzero = 1;
1807 base = 10;
1808 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001809 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001810 if (str[0] == '0' &&
1811 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1812 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1813 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001814 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001815
Guido van Rossume6762971998-06-22 03:54:46 +00001816 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001817 if ((base & (base - 1)) == 0)
1818 z = long_from_binary_base(&str, base);
1819 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001820/***
1821Binary bases can be converted in time linear in the number of digits, because
1822Python's representation base is binary. Other bases (including decimal!) use
1823the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001824
Thomas Wouters477c8d52006-05-27 19:21:47 +00001825First some math: the largest integer that can be expressed in N base-B digits
1826is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1827case number of Python digits needed to hold it is the smallest integer n s.t.
1828
1829 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1830 BASE**n >= B**N [taking logs to base BASE]
1831 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1832
1833The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1834this quickly. A Python long with that much space is reserved near the start,
1835and the result is computed into it.
1836
1837The input string is actually treated as being in base base**i (i.e., i digits
1838are processed at a time), where two more static arrays hold:
1839
1840 convwidth_base[base] = the largest integer i such that base**i <= BASE
1841 convmultmax_base[base] = base ** convwidth_base[base]
1842
1843The first of these is the largest i such that i consecutive input digits
1844must fit in a single Python digit. The second is effectively the input
1845base we're really using.
1846
1847Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1848convmultmax_base[base], the result is "simply"
1849
1850 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1851
1852where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001853
1854Error analysis: as above, the number of Python digits `n` needed is worst-
1855case
1856
1857 n >= N * log(B)/log(BASE)
1858
1859where `N` is the number of input digits in base `B`. This is computed via
1860
1861 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1862
1863below. Two numeric concerns are how much space this can waste, and whether
1864the computed result can be too small. To be concrete, assume BASE = 2**15,
1865which is the default (and it's unlikely anyone changes that).
1866
1867Waste isn't a problem: provided the first input digit isn't 0, the difference
1868between the worst-case input with N digits and the smallest input with N
1869digits is about a factor of B, but B is small compared to BASE so at most
1870one allocated Python digit can remain unused on that count. If
1871N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1872and adding 1 returns a result 1 larger than necessary. However, that can't
1873happen: whenever B is a power of 2, long_from_binary_base() is called
1874instead, and it's impossible for B**i to be an integer power of 2**15 when
1875B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1876an exact integer when B is not a power of 2, since B**i has a prime factor
1877other than 2 in that case, but (2**15)**j's only prime factor is 2).
1878
1879The computed result can be too small if the true value of N*log(B)/log(BASE)
1880is a little bit larger than an exact integer, but due to roundoff errors (in
1881computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1882yields a numeric result a little less than that integer. Unfortunately, "how
1883close can a transcendental function get to an integer over some range?"
1884questions are generally theoretically intractable. Computer analysis via
1885continued fractions is practical: expand log(B)/log(BASE) via continued
1886fractions, giving a sequence i/j of "the best" rational approximations. Then
1887j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1888we can get very close to being in trouble, but very rarely. For example,
188976573 is a denominator in one of the continued-fraction approximations to
1890log(10)/log(2**15), and indeed:
1891
1892 >>> log(10)/log(2**15)*76573
1893 16958.000000654003
1894
1895is very close to an integer. If we were working with IEEE single-precision,
1896rounding errors could kill us. Finding worst cases in IEEE double-precision
1897requires better-than-double-precision log() functions, and Tim didn't bother.
1898Instead the code checks to see whether the allocated space is enough as each
1899new Python digit is added, and copies the whole thing to a larger long if not.
1900This should happen extremely rarely, and in fact I don't have a test case
1901that triggers it(!). Instead the code was tested by artificially allocating
1902just 1 digit at the start, so that the copying code was exercised for every
1903digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904***/
1905 register twodigits c; /* current input character */
1906 Py_ssize_t size_z;
1907 int i;
1908 int convwidth;
1909 twodigits convmultmax, convmult;
1910 digit *pz, *pzstop;
1911 char* scan;
1912
1913 static double log_base_BASE[37] = {0.0e0,};
1914 static int convwidth_base[37] = {0,};
1915 static twodigits convmultmax_base[37] = {0,};
1916
1917 if (log_base_BASE[base] == 0.0) {
1918 twodigits convmax = base;
1919 int i = 1;
1920
1921 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001922 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001923 for (;;) {
1924 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001925 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001926 break;
1927 convmax = next;
1928 ++i;
1929 }
1930 convmultmax_base[base] = convmax;
1931 assert(i > 0);
1932 convwidth_base[base] = i;
1933 }
1934
1935 /* Find length of the string of numeric characters. */
1936 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001937 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001938 ++scan;
1939
1940 /* Create a long object that can contain the largest possible
1941 * integer with this base and length. Note that there's no
1942 * need to initialize z->ob_digit -- no slot is read up before
1943 * being stored into.
1944 */
1945 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001946 /* Uncomment next line to test exceedingly rare copy code */
1947 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001948 assert(size_z > 0);
1949 z = _PyLong_New(size_z);
1950 if (z == NULL)
1951 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001952 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001953
1954 /* `convwidth` consecutive input digits are treated as a single
1955 * digit in base `convmultmax`.
1956 */
1957 convwidth = convwidth_base[base];
1958 convmultmax = convmultmax_base[base];
1959
1960 /* Work ;-) */
1961 while (str < scan) {
1962 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001963 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00001964 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1965 c = (twodigits)(c * base +
Raymond Hettinger35631532009-01-09 03:58:09 +00001966 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001967 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001968 }
1969
1970 convmult = convmultmax;
1971 /* Calculate the shift only if we couldn't get
1972 * convwidth digits.
1973 */
1974 if (i != convwidth) {
1975 convmult = base;
1976 for ( ; i > 1; --i)
1977 convmult *= base;
1978 }
1979
1980 /* Multiply z by convmult, and add c. */
1981 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001982 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001983 for (; pz < pzstop; ++pz) {
1984 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001985 *pz = (digit)(c & PyLong_MASK);
1986 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001987 }
1988 /* carry off the current end? */
1989 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001990 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001991 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001992 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001993 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001994 }
1995 else {
1996 PyLongObject *tmp;
1997 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001998 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001999 tmp = _PyLong_New(size_z + 1);
2000 if (tmp == NULL) {
2001 Py_DECREF(z);
2002 return NULL;
2003 }
2004 memcpy(tmp->ob_digit,
2005 z->ob_digit,
2006 sizeof(digit) * size_z);
2007 Py_DECREF(z);
2008 z = tmp;
2009 z->ob_digit[size_z] = (digit)c;
2010 ++size_z;
2011 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002012 }
Tim Petersbf2674b2003-02-02 07:51:32 +00002013 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002014 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00002015 if (z == NULL)
2016 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002017 if (error_if_nonzero) {
2018 /* reset the base to 0, else the exception message
2019 doesn't make too much sense */
2020 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00002021 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002022 goto onError;
2023 /* there might still be other problems, therefore base
2024 remains zero here for the same reason */
2025 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00002026 if (str == start)
2027 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002028 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00002029 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00002030 while (*str && isspace(Py_CHARMASK(*str)))
2031 str++;
2032 if (*str != '\0')
2033 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002034 if (pend)
2035 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00002036 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002037 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002038
2039 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002040 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002041 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002042 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002043 if (strobj == NULL)
2044 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002045 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002046 "invalid literal for int() with base %d: %R",
2047 base, strobj);
2048 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002049 return NULL;
2050}
2051
2052PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002053PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002054{
Walter Dörwald07e14762002-11-06 16:15:14 +00002055 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002056 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002057
Walter Dörwald07e14762002-11-06 16:15:14 +00002058 if (buffer == NULL)
2059 return NULL;
2060
2061 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2062 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002063 return NULL;
2064 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002065 result = PyLong_FromString(buffer, NULL, base);
2066 PyMem_FREE(buffer);
2067 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002068}
2069
Tim Peters9f688bf2000-07-07 15:53:28 +00002070/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002071static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002072 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002073static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002074
2075/* Long division with remainder, top-level routine */
2076
Guido van Rossume32e0141992-01-19 16:31:05 +00002077static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002078long_divrem(PyLongObject *a, PyLongObject *b,
2079 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002080{
Christian Heimes90aa7642007-12-19 02:45:37 +00002081 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002082 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002083
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002085 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002086 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002087 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002088 }
2089 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002090 (size_a == size_b &&
2091 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002092 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002093 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002094 if (*pdiv == NULL)
2095 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002096 Py_INCREF(a);
2097 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002098 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002099 }
2100 if (size_b == 1) {
2101 digit rem = 0;
2102 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002103 if (z == NULL)
2104 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002105 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002106 if (*prem == NULL) {
2107 Py_DECREF(z);
2108 return -1;
2109 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002110 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002111 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002112 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002113 if (z == NULL)
2114 return -1;
2115 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002116 /* Set the signs.
2117 The quotient z has the sign of a*b;
2118 the remainder r has the sign of a,
2119 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002120 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002121 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002122 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002123 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002124 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002125 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002126}
2127
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002128/* Unsigned long division with remainder -- the algorithm. The arguments v1
2129 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002130
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002131static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002132x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002133{
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002134 PyLongObject *v, *w, *a;
2135 Py_ssize_t i, k, size_v, size_w;
2136 int d;
2137 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2138 twodigits vv;
2139 sdigit zhi;
2140 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002141
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002142 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2143 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2144 handle the special case when the initial estimate q for a quotient
2145 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2146 that won't overflow a digit. */
2147
2148 /* allocate space; w will also be used to hold the final remainder */
2149 size_v = ABS(Py_SIZE(v1));
2150 size_w = ABS(Py_SIZE(w1));
2151 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2152 v = _PyLong_New(size_v+1);
2153 if (v == NULL) {
2154 *prem = NULL;
2155 return NULL;
2156 }
2157 w = _PyLong_New(size_w);
2158 if (w == NULL) {
2159 Py_DECREF(v);
2160 *prem = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002161 return NULL;
2162 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002163
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002164 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2165 shift v1 left by the same amount. Results go into w and v. */
2166 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2167 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2168 assert(carry == 0);
2169 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2170 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2171 v->ob_digit[size_v] = carry;
2172 size_v++;
2173 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002174
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002175 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2176 at most (and usually exactly) k = size_v - size_w digits. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002177 k = size_v - size_w;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002178 assert(k >= 0);
2179 a = _PyLong_New(k);
2180 if (a == NULL) {
2181 Py_DECREF(w);
2182 Py_DECREF(v);
2183 *prem = NULL;
2184 return NULL;
2185 }
2186 v0 = v->ob_digit;
2187 w0 = w->ob_digit;
2188 wm1 = w0[size_w-1];
2189 wm2 = w0[size_w-2];
2190 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2191 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2192 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002193
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002194 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195 Py_DECREF(a);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002196 Py_DECREF(w);
2197 Py_DECREF(v);
2198 *prem = NULL;
2199 return NULL;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002200 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002201
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002202 /* estimate quotient digit q; may overestimate by 1 (rare) */
2203 vtop = vk[size_w];
2204 assert(vtop <= wm1);
2205 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2206 q = (digit)(vv / wm1);
2207 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2208 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2209 | vk[size_w-2])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002210 --q;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002211 r += wm1;
2212 if (r >= PyLong_BASE)
2213 break;
2214 }
2215 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002216
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002217 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2218 zhi = 0;
2219 for (i = 0; i < size_w; ++i) {
2220 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2221 -PyLong_BASE * q <= z < PyLong_BASE */
2222 z = (sdigit)vk[i] + zhi -
2223 (stwodigits)q * (stwodigits)w0[i];
2224 vk[i] = (digit)z & PyLong_MASK;
2225 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2226 z, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002227 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002228
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002229 /* add w back if q was too large (this branch taken rarely) */
2230 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2231 if ((sdigit)vtop + zhi < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002232 carry = 0;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002233 for (i = 0; i < size_w; ++i) {
2234 carry += vk[i] + w0[i];
2235 vk[i] = carry & PyLong_MASK;
2236 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002237 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002238 --q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002239 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002240
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002241 /* store quotient digit */
2242 assert(q < PyLong_BASE);
2243 *--ak = q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002244 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002245
2246 /* unshift remainder; we reuse w to store the result */
2247 carry = v_rshift(w0, v0, size_w, d);
2248 assert(carry==0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002249 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002250
2251 *prem = long_normalize(w);
2252 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002253}
2254
2255/* Methods */
2256
2257static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002258long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002259{
Christian Heimes90aa7642007-12-19 02:45:37 +00002260 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002261}
2262
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002263static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002264long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002265{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002266 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002267}
2268
2269static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002270long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002271{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002272 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002273
Christian Heimes90aa7642007-12-19 02:45:37 +00002274 if (Py_SIZE(a) != Py_SIZE(b)) {
2275 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002276 sign = 0;
2277 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002278 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002279 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002280 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002281 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002282 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2283 ;
2284 if (i < 0)
2285 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002286 else {
Mark Dickinsone4416742009-02-15 15:14:57 +00002287 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002288 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002289 sign = -sign;
2290 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002291 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002292 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002293}
2294
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002295#define TEST_COND(cond) \
2296 ((cond) ? Py_True : Py_False)
2297
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002298static PyObject *
2299long_richcompare(PyObject *self, PyObject *other, int op)
2300{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002301 int result;
2302 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002303 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002304 if (self == other)
2305 result = 0;
2306 else
2307 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2308 /* Convert the return value to a Boolean */
2309 switch (op) {
2310 case Py_EQ:
2311 v = TEST_COND(result == 0);
2312 break;
2313 case Py_NE:
2314 v = TEST_COND(result != 0);
2315 break;
2316 case Py_LE:
2317 v = TEST_COND(result <= 0);
2318 break;
2319 case Py_GE:
2320 v = TEST_COND(result >= 0);
2321 break;
2322 case Py_LT:
2323 v = TEST_COND(result == -1);
2324 break;
2325 case Py_GT:
2326 v = TEST_COND(result == 1);
2327 break;
2328 default:
2329 PyErr_BadArgument();
2330 return NULL;
2331 }
2332 Py_INCREF(v);
2333 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002334}
2335
Guido van Rossum9bfef441993-03-29 10:43:31 +00002336static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002337long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002338{
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002339 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002340 Py_ssize_t i;
2341 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002342
2343 /* This is designed so that Python ints and longs with the
2344 same value hash to the same value, otherwise comparisons
2345 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002346 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002347 switch(i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00002348 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00002349 case 0: return 0;
2350 case 1: return v->ob_digit[0];
2351 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002352 sign = 1;
2353 x = 0;
2354 if (i < 0) {
2355 sign = -1;
2356 i = -(i);
2357 }
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002358 /* The following loop produces a C unsigned long x such that x is
2359 congruent to the absolute value of v modulo ULONG_MAX. The
Thomas Woutersce272b62007-09-19 21:19:28 +00002360 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002361 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002362 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002363 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002364 x += v->ob_digit[i];
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002365 /* If the addition above overflowed we compensate by
2366 incrementing. This preserves the value modulo
2367 ULONG_MAX. */
2368 if (x < v->ob_digit[i])
Thomas Woutersce272b62007-09-19 21:19:28 +00002369 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002370 }
2371 x = x * sign;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002372 if (x == (unsigned long)-1)
2373 x = (unsigned long)-2;
2374 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002375}
2376
2377
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002378/* Add the absolute values of two long integers. */
2379
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002380static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002381x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002382{
Christian Heimes90aa7642007-12-19 02:45:37 +00002383 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002384 PyLongObject *z;
Mark Dickinson17e55872009-01-24 15:56:57 +00002385 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002386 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002387
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002388 /* Ensure a is the larger of the two: */
2389 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002390 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002391 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002392 size_a = size_b;
2393 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002394 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002395 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002396 if (z == NULL)
2397 return NULL;
2398 for (i = 0; i < size_b; ++i) {
2399 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002400 z->ob_digit[i] = carry & PyLong_MASK;
2401 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002402 }
2403 for (; i < size_a; ++i) {
2404 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002405 z->ob_digit[i] = carry & PyLong_MASK;
2406 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002407 }
2408 z->ob_digit[i] = carry;
2409 return long_normalize(z);
2410}
2411
2412/* Subtract the absolute values of two integers. */
2413
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002414static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002415x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002416{
Christian Heimes90aa7642007-12-19 02:45:37 +00002417 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002418 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002419 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002420 int sign = 1;
2421 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002422
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002423 /* Ensure a is the larger of the two: */
2424 if (size_a < size_b) {
2425 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002426 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002427 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002428 size_a = size_b;
2429 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002430 }
2431 else if (size_a == size_b) {
2432 /* Find highest digit where a and b differ: */
2433 i = size_a;
2434 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2435 ;
2436 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002437 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002438 if (a->ob_digit[i] < b->ob_digit[i]) {
2439 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002440 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002441 }
2442 size_a = size_b = i+1;
2443 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002444 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002445 if (z == NULL)
2446 return NULL;
2447 for (i = 0; i < size_b; ++i) {
2448 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002449 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002450 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002451 z->ob_digit[i] = borrow & PyLong_MASK;
2452 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002453 borrow &= 1; /* Keep only one sign bit */
2454 }
2455 for (; i < size_a; ++i) {
2456 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002457 z->ob_digit[i] = borrow & PyLong_MASK;
2458 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002459 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002460 }
2461 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002462 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002463 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002464 return long_normalize(z);
2465}
2466
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002467static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002468long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002469{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002470 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002471
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002472 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002473
Christian Heimes90aa7642007-12-19 02:45:37 +00002474 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002475 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002476 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002477 return result;
2478 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002479 if (Py_SIZE(a) < 0) {
2480 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002481 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002482 if (z != NULL && Py_SIZE(z) != 0)
2483 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002484 }
2485 else
2486 z = x_sub(b, a);
2487 }
2488 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002489 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002490 z = x_sub(a, b);
2491 else
2492 z = x_add(a, b);
2493 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002494 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002495}
2496
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002497static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002498long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002499{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002500 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002501
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002502 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002503
Christian Heimes90aa7642007-12-19 02:45:37 +00002504 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002505 PyObject* r;
2506 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002507 return r;
2508 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002509 if (Py_SIZE(a) < 0) {
2510 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002511 z = x_sub(a, b);
2512 else
2513 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002514 if (z != NULL && Py_SIZE(z) != 0)
2515 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002516 }
2517 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002518 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002519 z = x_add(a, b);
2520 else
2521 z = x_sub(a, b);
2522 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002523 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002524}
2525
Tim Peters5af4e6c2002-08-12 02:31:19 +00002526/* Grade school multiplication, ignoring the signs.
2527 * Returns the absolute value of the product, or NULL if error.
2528 */
2529static PyLongObject *
2530x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002531{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002532 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002533 Py_ssize_t size_a = ABS(Py_SIZE(a));
2534 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002535 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002536
Tim Peters5af4e6c2002-08-12 02:31:19 +00002537 z = _PyLong_New(size_a + size_b);
2538 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002539 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002540
Christian Heimes90aa7642007-12-19 02:45:37 +00002541 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002542 if (a == b) {
2543 /* Efficient squaring per HAC, Algorithm 14.16:
2544 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2545 * Gives slightly less than a 2x speedup when a == b,
2546 * via exploiting that each entry in the multiplication
2547 * pyramid appears twice (except for the size_a squares).
2548 */
2549 for (i = 0; i < size_a; ++i) {
2550 twodigits carry;
2551 twodigits f = a->ob_digit[i];
2552 digit *pz = z->ob_digit + (i << 1);
2553 digit *pa = a->ob_digit + i + 1;
2554 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002555
Tim Peters0973b992004-08-29 22:16:50 +00002556 SIGCHECK({
2557 Py_DECREF(z);
2558 return NULL;
2559 })
2560
2561 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002562 *pz++ = (digit)(carry & PyLong_MASK);
2563 carry >>= PyLong_SHIFT;
2564 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002565
2566 /* Now f is added in twice in each column of the
2567 * pyramid it appears. Same as adding f<<1 once.
2568 */
2569 f <<= 1;
2570 while (pa < paend) {
2571 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002572 *pz++ = (digit)(carry & PyLong_MASK);
2573 carry >>= PyLong_SHIFT;
2574 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002575 }
2576 if (carry) {
2577 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002578 *pz++ = (digit)(carry & PyLong_MASK);
2579 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002580 }
2581 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002582 *pz += (digit)(carry & PyLong_MASK);
2583 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002584 }
Tim Peters0973b992004-08-29 22:16:50 +00002585 }
2586 else { /* a is not the same as b -- gradeschool long mult */
2587 for (i = 0; i < size_a; ++i) {
2588 twodigits carry = 0;
2589 twodigits f = a->ob_digit[i];
2590 digit *pz = z->ob_digit + i;
2591 digit *pb = b->ob_digit;
2592 digit *pbend = b->ob_digit + size_b;
2593
2594 SIGCHECK({
2595 Py_DECREF(z);
2596 return NULL;
2597 })
2598
2599 while (pb < pbend) {
2600 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002601 *pz++ = (digit)(carry & PyLong_MASK);
2602 carry >>= PyLong_SHIFT;
2603 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002604 }
2605 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002606 *pz += (digit)(carry & PyLong_MASK);
2607 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002608 }
2609 }
Tim Peters44121a62002-08-12 06:17:58 +00002610 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002611}
2612
2613/* A helper for Karatsuba multiplication (k_mul).
2614 Takes a long "n" and an integer "size" representing the place to
2615 split, and sets low and high such that abs(n) == (high << size) + low,
2616 viewing the shift as being by digits. The sign bit is ignored, and
2617 the return values are >= 0.
2618 Returns 0 on success, -1 on failure.
2619*/
2620static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002621kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002622{
2623 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002624 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002625 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002626
2627 size_lo = MIN(size_n, size);
2628 size_hi = size_n - size_lo;
2629
2630 if ((hi = _PyLong_New(size_hi)) == NULL)
2631 return -1;
2632 if ((lo = _PyLong_New(size_lo)) == NULL) {
2633 Py_DECREF(hi);
2634 return -1;
2635 }
2636
2637 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2638 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2639
2640 *high = long_normalize(hi);
2641 *low = long_normalize(lo);
2642 return 0;
2643}
2644
Tim Peters60004642002-08-12 22:01:34 +00002645static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2646
Tim Peters5af4e6c2002-08-12 02:31:19 +00002647/* Karatsuba multiplication. Ignores the input signs, and returns the
2648 * absolute value of the product (or NULL if error).
2649 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2650 */
2651static PyLongObject *
2652k_mul(PyLongObject *a, PyLongObject *b)
2653{
Christian Heimes90aa7642007-12-19 02:45:37 +00002654 Py_ssize_t asize = ABS(Py_SIZE(a));
2655 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002656 PyLongObject *ah = NULL;
2657 PyLongObject *al = NULL;
2658 PyLongObject *bh = NULL;
2659 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002660 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002661 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002662 Py_ssize_t shift; /* the number of digits we split off */
2663 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002664
Tim Peters5af4e6c2002-08-12 02:31:19 +00002665 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2666 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2667 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002668 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002669 * By picking X to be a power of 2, "*X" is just shifting, and it's
2670 * been reduced to 3 multiplies on numbers half the size.
2671 */
2672
Tim Petersfc07e562002-08-12 02:54:10 +00002673 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002674 * is largest.
2675 */
Tim Peters738eda72002-08-12 15:08:20 +00002676 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002677 t1 = a;
2678 a = b;
2679 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002680
2681 i = asize;
2682 asize = bsize;
2683 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002684 }
2685
2686 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002687 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2688 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002689 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002690 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002691 else
2692 return x_mul(a, b);
2693 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002694
Tim Peters60004642002-08-12 22:01:34 +00002695 /* If a is small compared to b, splitting on b gives a degenerate
2696 * case with ah==0, and Karatsuba may be (even much) less efficient
2697 * than "grade school" then. However, we can still win, by viewing
2698 * b as a string of "big digits", each of width a->ob_size. That
2699 * leads to a sequence of balanced calls to k_mul.
2700 */
2701 if (2 * asize <= bsize)
2702 return k_lopsided_mul(a, b);
2703
Tim Petersd6974a52002-08-13 20:37:51 +00002704 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002705 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002706 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002707 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002708
Tim Peters0973b992004-08-29 22:16:50 +00002709 if (a == b) {
2710 bh = ah;
2711 bl = al;
2712 Py_INCREF(bh);
2713 Py_INCREF(bl);
2714 }
2715 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002716
Tim Petersd64c1de2002-08-12 17:36:03 +00002717 /* The plan:
2718 * 1. Allocate result space (asize + bsize digits: that's always
2719 * enough).
2720 * 2. Compute ah*bh, and copy into result at 2*shift.
2721 * 3. Compute al*bl, and copy into result at 0. Note that this
2722 * can't overlap with #2.
2723 * 4. Subtract al*bl from the result, starting at shift. This may
2724 * underflow (borrow out of the high digit), but we don't care:
2725 * we're effectively doing unsigned arithmetic mod
2726 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2727 * borrows and carries out of the high digit can be ignored.
2728 * 5. Subtract ah*bh from the result, starting at shift.
2729 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2730 * at shift.
2731 */
2732
2733 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002734 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002735 if (ret == NULL) goto fail;
2736#ifdef Py_DEBUG
2737 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002738 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002739#endif
Tim Peters44121a62002-08-12 06:17:58 +00002740
Tim Petersd64c1de2002-08-12 17:36:03 +00002741 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002742 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002743 assert(Py_SIZE(t1) >= 0);
2744 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002745 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002746 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002747
2748 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002749 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002750 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002751 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002752 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002753
Tim Petersd64c1de2002-08-12 17:36:03 +00002754 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002755 if ((t2 = k_mul(al, bl)) == NULL) {
2756 Py_DECREF(t1);
2757 goto fail;
2758 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002759 assert(Py_SIZE(t2) >= 0);
2760 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2761 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002762
2763 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002764 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002765 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002766 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002767
Tim Petersd64c1de2002-08-12 17:36:03 +00002768 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2769 * because it's fresher in cache.
2770 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002771 i = Py_SIZE(ret) - shift; /* # digits after shift */
2772 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002773 Py_DECREF(t2);
2774
Christian Heimes90aa7642007-12-19 02:45:37 +00002775 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002776 Py_DECREF(t1);
2777
Tim Petersd64c1de2002-08-12 17:36:03 +00002778 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002779 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2780 Py_DECREF(ah);
2781 Py_DECREF(al);
2782 ah = al = NULL;
2783
Tim Peters0973b992004-08-29 22:16:50 +00002784 if (a == b) {
2785 t2 = t1;
2786 Py_INCREF(t2);
2787 }
2788 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002789 Py_DECREF(t1);
2790 goto fail;
2791 }
2792 Py_DECREF(bh);
2793 Py_DECREF(bl);
2794 bh = bl = NULL;
2795
Tim Peters738eda72002-08-12 15:08:20 +00002796 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002797 Py_DECREF(t1);
2798 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002799 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002800 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002801
Tim Petersd6974a52002-08-13 20:37:51 +00002802 /* Add t3. It's not obvious why we can't run out of room here.
2803 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002804 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002805 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002806 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002807
Tim Peters5af4e6c2002-08-12 02:31:19 +00002808 return long_normalize(ret);
2809
2810 fail:
2811 Py_XDECREF(ret);
2812 Py_XDECREF(ah);
2813 Py_XDECREF(al);
2814 Py_XDECREF(bh);
2815 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002816 return NULL;
2817}
2818
Tim Petersd6974a52002-08-13 20:37:51 +00002819/* (*) Why adding t3 can't "run out of room" above.
2820
Tim Petersab86c2b2002-08-15 20:06:00 +00002821Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2822to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002823
Tim Petersab86c2b2002-08-15 20:06:00 +000028241. For any integer i, i = c(i/2) + f(i/2). In particular,
2825 bsize = c(bsize/2) + f(bsize/2).
28262. shift = f(bsize/2)
28273. asize <= bsize
28284. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2829 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002830
Tim Petersab86c2b2002-08-15 20:06:00 +00002831We allocated asize + bsize result digits, and add t3 into them at an offset
2832of shift. This leaves asize+bsize-shift allocated digit positions for t3
2833to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2834asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002835
Tim Petersab86c2b2002-08-15 20:06:00 +00002836bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2837at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002838
Tim Petersab86c2b2002-08-15 20:06:00 +00002839If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2840digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2841most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002842
Tim Petersab86c2b2002-08-15 20:06:00 +00002843The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002844
Tim Petersab86c2b2002-08-15 20:06:00 +00002845 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002846
Tim Petersab86c2b2002-08-15 20:06:00 +00002847and we have asize + c(bsize/2) available digit positions. We need to show
2848this is always enough. An instance of c(bsize/2) cancels out in both, so
2849the question reduces to whether asize digits is enough to hold
2850(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2851then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2852asize 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 +00002853digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002854asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002855c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2856is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2857bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002858
Tim Peters48d52c02002-08-14 17:07:32 +00002859Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2860clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2861ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002862*/
2863
Tim Peters60004642002-08-12 22:01:34 +00002864/* b has at least twice the digits of a, and a is big enough that Karatsuba
2865 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2866 * of slices, each with a->ob_size digits, and multiply the slices by a,
2867 * one at a time. This gives k_mul balanced inputs to work with, and is
2868 * also cache-friendly (we compute one double-width slice of the result
2869 * at a time, then move on, never bactracking except for the helpful
2870 * single-width slice overlap between successive partial sums).
2871 */
2872static PyLongObject *
2873k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2874{
Christian Heimes90aa7642007-12-19 02:45:37 +00002875 const Py_ssize_t asize = ABS(Py_SIZE(a));
2876 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002877 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002878 PyLongObject *ret;
2879 PyLongObject *bslice = NULL;
2880
2881 assert(asize > KARATSUBA_CUTOFF);
2882 assert(2 * asize <= bsize);
2883
2884 /* Allocate result space, and zero it out. */
2885 ret = _PyLong_New(asize + bsize);
2886 if (ret == NULL)
2887 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002888 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002889
2890 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002891 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002892 if (bslice == NULL)
2893 goto fail;
2894
2895 nbdone = 0;
2896 while (bsize > 0) {
2897 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002898 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002899
2900 /* Multiply the next slice of b by a. */
2901 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2902 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002903 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002904 product = k_mul(a, bslice);
2905 if (product == NULL)
2906 goto fail;
2907
2908 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002909 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2910 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002911 Py_DECREF(product);
2912
2913 bsize -= nbtouse;
2914 nbdone += nbtouse;
2915 }
2916
2917 Py_DECREF(bslice);
2918 return long_normalize(ret);
2919
2920 fail:
2921 Py_DECREF(ret);
2922 Py_XDECREF(bslice);
2923 return NULL;
2924}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002925
2926static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002927long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002928{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002929 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002930
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002931 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002932
Mark Dickinsonbd792642009-03-18 20:06:12 +00002933 /* fast path for single-digit multiplication */
Christian Heimes90aa7642007-12-19 02:45:37 +00002934 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonbd792642009-03-18 20:06:12 +00002935 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
2936#ifdef HAVE_LONG_LONG
2937 return PyLong_FromLongLong((PY_LONG_LONG)v);
2938#else
2939 /* if we don't have long long then we're almost certainly
2940 using 15-bit digits, so v will fit in a long. In the
2941 unlikely event that we're using 30-bit digits on a platform
2942 without long long, a large v will just cause us to fall
2943 through to the general multiplication code below. */
2944 if (v >= LONG_MIN && v <= LONG_MAX)
2945 return PyLong_FromLong((long)v);
2946#endif
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002947 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002948
Tim Petersd64c1de2002-08-12 17:36:03 +00002949 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002950 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002951 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002952 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002953 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002954}
2955
Guido van Rossume32e0141992-01-19 16:31:05 +00002956/* The / and % operators are now defined in terms of divmod().
2957 The expression a mod b has the value a - b*floor(a/b).
2958 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002959 |a| by |b|, with the sign of a. This is also expressed
2960 as a - b*trunc(a/b), if trunc truncates towards zero.
2961 Some examples:
2962 a b a rem b a mod b
2963 13 10 3 3
2964 -13 10 -3 7
2965 13 -10 3 -7
2966 -13 -10 -3 -3
2967 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002968 have different signs. We then subtract one from the 'div'
2969 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002970
Tim Peters47e52ee2004-08-30 02:44:38 +00002971/* Compute
2972 * *pdiv, *pmod = divmod(v, w)
2973 * NULL can be passed for pdiv or pmod, in which case that part of
2974 * the result is simply thrown away. The caller owns a reference to
2975 * each of these it requests (does not pass NULL for).
2976 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002977static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002978l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002979 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002980{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002981 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002982
Guido van Rossume32e0141992-01-19 16:31:05 +00002983 if (long_divrem(v, w, &div, &mod) < 0)
2984 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002985 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2986 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002987 PyLongObject *temp;
2988 PyLongObject *one;
2989 temp = (PyLongObject *) long_add(mod, w);
2990 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002991 mod = temp;
2992 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002993 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002994 return -1;
2995 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002996 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002997 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002998 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2999 Py_DECREF(mod);
3000 Py_DECREF(div);
3001 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00003002 return -1;
3003 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003004 Py_DECREF(one);
3005 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003006 div = temp;
3007 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003008 if (pdiv != NULL)
3009 *pdiv = div;
3010 else
3011 Py_DECREF(div);
3012
3013 if (pmod != NULL)
3014 *pmod = mod;
3015 else
3016 Py_DECREF(mod);
3017
Guido van Rossume32e0141992-01-19 16:31:05 +00003018 return 0;
3019}
3020
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003021static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003022long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003023{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003024 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003025
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003026 CHECK_BINOP(a, b);
3027 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003028 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003029 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003030}
3031
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003032static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003033long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00003034{
Tim Peterse2a60002001-09-04 06:17:36 +00003035 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00003036 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00003037
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003038 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00003039 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
3040 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00003041 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00003042 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00003043 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00003044 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
3045 but should really be set correctly after sucessful calls to
3046 _PyLong_AsScaledDouble() */
3047 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00003048
3049 if (bd == 0.0) {
3050 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003051 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00003052 return NULL;
3053 }
3054
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003055 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00003056 ad /= bd; /* overflow/underflow impossible here */
3057 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003058 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00003059 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003060 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00003061 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003062 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003063 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00003064 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003065 goto overflow;
3066 return PyFloat_FromDouble(ad);
3067
3068overflow:
3069 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003070 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00003071 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003072
Tim Peters20dab9f2001-09-04 05:31:47 +00003073}
3074
3075static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003076long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003077{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003078 PyLongObject *mod;
3079
3080 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003081
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003082 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003083 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003084 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003085}
3086
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003087static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003088long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003089{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003090 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003091 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003092
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003093 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003094
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003095 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003096 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003097 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003098 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003099 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003100 PyTuple_SetItem(z, 0, (PyObject *) div);
3101 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003102 }
3103 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003104 Py_DECREF(div);
3105 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003106 }
3107 return z;
3108}
3109
Tim Peters47e52ee2004-08-30 02:44:38 +00003110/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003111static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003112long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003113{
Tim Peters47e52ee2004-08-30 02:44:38 +00003114 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3115 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003116
Tim Peters47e52ee2004-08-30 02:44:38 +00003117 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003118 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003119 PyLongObject *temp = NULL;
3120
3121 /* 5-ary values. If the exponent is large enough, table is
3122 * precomputed so that table[i] == a**i % c for i in range(32).
3123 */
3124 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3125 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3126
3127 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003128 CHECK_BINOP(v, w);
3129 a = (PyLongObject*)v; Py_INCREF(a);
3130 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003131 if (PyLong_Check(x)) {
3132 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003133 Py_INCREF(x);
3134 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003135 else if (x == Py_None)
3136 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003137 else {
3138 Py_DECREF(a);
3139 Py_DECREF(b);
3140 Py_INCREF(Py_NotImplemented);
3141 return Py_NotImplemented;
3142 }
Tim Peters4c483c42001-09-05 06:24:58 +00003143
Christian Heimes90aa7642007-12-19 02:45:37 +00003144 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003145 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003146 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003147 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003148 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003149 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003150 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003151 /* else return a float. This works because we know
3152 that this calls float_pow() which converts its
3153 arguments to double. */
3154 Py_DECREF(a);
3155 Py_DECREF(b);
3156 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003157 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003158 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003159
3160 if (c) {
3161 /* if modulus == 0:
3162 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003163 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003164 PyErr_SetString(PyExc_ValueError,
3165 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003166 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003167 }
3168
3169 /* if modulus < 0:
3170 negativeOutput = True
3171 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003172 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003173 negativeOutput = 1;
3174 temp = (PyLongObject *)_PyLong_Copy(c);
3175 if (temp == NULL)
3176 goto Error;
3177 Py_DECREF(c);
3178 c = temp;
3179 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003180 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003181 }
3182
3183 /* if modulus == 1:
3184 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003185 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003186 z = (PyLongObject *)PyLong_FromLong(0L);
3187 goto Done;
3188 }
3189
3190 /* if base < 0:
3191 base = base % modulus
3192 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003193 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003194 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003195 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003196 Py_DECREF(a);
3197 a = temp;
3198 temp = NULL;
3199 }
3200 }
3201
3202 /* At this point a, b, and c are guaranteed non-negative UNLESS
3203 c is NULL, in which case a may be negative. */
3204
3205 z = (PyLongObject *)PyLong_FromLong(1L);
3206 if (z == NULL)
3207 goto Error;
3208
3209 /* Perform a modular reduction, X = X % c, but leave X alone if c
3210 * is NULL.
3211 */
3212#define REDUCE(X) \
3213 if (c != NULL) { \
3214 if (l_divmod(X, c, NULL, &temp) < 0) \
3215 goto Error; \
3216 Py_XDECREF(X); \
3217 X = temp; \
3218 temp = NULL; \
3219 }
3220
3221 /* Multiply two values, then reduce the result:
3222 result = X*Y % c. If c is NULL, skip the mod. */
3223#define MULT(X, Y, result) \
3224{ \
3225 temp = (PyLongObject *)long_mul(X, Y); \
3226 if (temp == NULL) \
3227 goto Error; \
3228 Py_XDECREF(result); \
3229 result = temp; \
3230 temp = NULL; \
3231 REDUCE(result) \
3232}
3233
Christian Heimes90aa7642007-12-19 02:45:37 +00003234 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003235 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3236 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003237 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003238 digit bi = b->ob_digit[i];
3239
Mark Dickinsone4416742009-02-15 15:14:57 +00003240 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003241 MULT(z, z, z)
3242 if (bi & j)
3243 MULT(z, a, z)
3244 }
3245 }
3246 }
3247 else {
3248 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3249 Py_INCREF(z); /* still holds 1L */
3250 table[0] = z;
3251 for (i = 1; i < 32; ++i)
3252 MULT(table[i-1], a, table[i])
3253
Christian Heimes90aa7642007-12-19 02:45:37 +00003254 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003255 const digit bi = b->ob_digit[i];
3256
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003257 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003258 const int index = (bi >> j) & 0x1f;
3259 for (k = 0; k < 5; ++k)
3260 MULT(z, z, z)
3261 if (index)
3262 MULT(z, table[index], z)
3263 }
3264 }
3265 }
3266
Christian Heimes90aa7642007-12-19 02:45:37 +00003267 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003268 temp = (PyLongObject *)long_sub(z, c);
3269 if (temp == NULL)
3270 goto Error;
3271 Py_DECREF(z);
3272 z = temp;
3273 temp = NULL;
3274 }
3275 goto Done;
3276
3277 Error:
3278 if (z != NULL) {
3279 Py_DECREF(z);
3280 z = NULL;
3281 }
3282 /* fall through */
3283 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003284 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003285 for (i = 0; i < 32; ++i)
3286 Py_XDECREF(table[i]);
3287 }
Tim Petersde7990b2005-07-17 23:45:23 +00003288 Py_DECREF(a);
3289 Py_DECREF(b);
3290 Py_XDECREF(c);
3291 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003292 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003293}
3294
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003295static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003296long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003297{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003298 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003299 PyLongObject *x;
3300 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003301 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003302 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003303 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003304 if (w == NULL)
3305 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003306 x = (PyLongObject *) long_add(v, w);
3307 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003308 if (x == NULL)
3309 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003310 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003311 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003312}
3313
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003314static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003315long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003316{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003317 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003318 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003319 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003320 z = (PyLongObject *)_PyLong_Copy(v);
3321 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003322 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003323 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003324}
3325
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003326static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003327long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003328{
Christian Heimes90aa7642007-12-19 02:45:37 +00003329 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003330 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003331 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003332 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003333}
3334
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003335static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003336long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003337{
Christian Heimes90aa7642007-12-19 02:45:37 +00003338 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003339}
3340
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003341static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003342long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003343{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003344 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003345 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003346 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003347 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003348
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003349 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003350
Christian Heimes90aa7642007-12-19 02:45:37 +00003351 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003352 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003353 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003354 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003355 if (a1 == NULL)
3356 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003357 a2 = (PyLongObject *) long_rshift(a1, b);
3358 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003359 if (a2 == NULL)
3360 goto rshift_error;
3361 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003362 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003363 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003364 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003365
Neil Schemenauerba872e22001-01-04 01:46:03 +00003366 shiftby = PyLong_AsLong((PyObject *)b);
3367 if (shiftby == -1L && PyErr_Occurred())
3368 goto rshift_error;
3369 if (shiftby < 0) {
3370 PyErr_SetString(PyExc_ValueError,
3371 "negative shift count");
3372 goto rshift_error;
3373 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003374 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003375 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003376 if (newsize <= 0)
3377 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003378 loshift = shiftby % PyLong_SHIFT;
3379 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003380 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003381 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003382 z = _PyLong_New(newsize);
3383 if (z == NULL)
3384 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003385 if (Py_SIZE(a) < 0)
3386 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003387 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3388 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3389 if (i+1 < newsize)
3390 z->ob_digit[i] |=
3391 (a->ob_digit[j+1] << hishift) & himask;
3392 }
3393 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003394 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003395rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003396 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003397
Guido van Rossumc6913e71991-11-19 20:26:46 +00003398}
3399
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003400static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003401long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003402{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003403 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003404 PyLongObject *a = (PyLongObject*)v;
3405 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003406 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003407 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003408 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003409 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003410
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003411 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003412
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003413 shiftby = PyLong_AsLong((PyObject *)b);
3414 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003415 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003416 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003417 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003418 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003419 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003420 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003421 PyErr_SetString(PyExc_ValueError,
3422 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003423 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003424 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003425 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3426 wordshift = (int)shiftby / PyLong_SHIFT;
3427 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003428
Christian Heimes90aa7642007-12-19 02:45:37 +00003429 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003430 newsize = oldsize + wordshift;
3431 if (remshift)
3432 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003433 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003434 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003435 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003436 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003437 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003438 for (i = 0; i < wordshift; i++)
3439 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003440 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003441 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003442 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003443 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3444 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003445 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003446 if (remshift)
3447 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003448 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003449 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003450 z = long_normalize(z);
3451lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003452 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003453}
3454
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003455
3456/* Bitwise and/xor/or operations */
3457
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003458static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003459long_bitwise(PyLongObject *a,
3460 int op, /* '&', '|', '^' */
3461 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003462{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003463 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003464 int negz;
Mark Dickinsone4416742009-02-15 15:14:57 +00003465 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003466 PyLongObject *z;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003467 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003468 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003469
Christian Heimes90aa7642007-12-19 02:45:37 +00003470 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003471 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003472 if (a == NULL)
3473 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003474 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003475 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003476 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003477 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003478 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003479 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003480 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003481 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003482 if (b == NULL) {
3483 Py_DECREF(a);
3484 return NULL;
3485 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003486 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003487 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003488 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003489 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003490 maskb = 0;
3491 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003492
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003493 negz = 0;
3494 switch (op) {
3495 case '^':
3496 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003497 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003498 negz = -1;
3499 }
3500 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003501 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003502 if (maska && maskb) {
3503 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003504 maska ^= PyLong_MASK;
3505 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003506 negz = -1;
3507 }
3508 break;
3509 case '|':
3510 if (maska || maskb) {
3511 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003512 maska ^= PyLong_MASK;
3513 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003514 negz = -1;
3515 }
3516 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003517 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003518
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003519 /* JRH: The original logic here was to allocate the result value (z)
3520 as the longer of the two operands. However, there are some cases
3521 where the result is guaranteed to be shorter than that: AND of two
3522 positives, OR of two negatives: use the shorter number. AND with
3523 mixed signs: use the positive number. OR with mixed signs: use the
3524 negative number. After the transformations above, op will be '&'
3525 iff one of these cases applies, and mask will be non-0 for operands
3526 whose length should be ignored.
3527 */
3528
Christian Heimes90aa7642007-12-19 02:45:37 +00003529 size_a = Py_SIZE(a);
3530 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003531 size_z = op == '&'
3532 ? (maska
3533 ? size_b
3534 : (maskb ? size_a : MIN(size_a, size_b)))
3535 : MAX(size_a, size_b);
3536 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003537 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003538 Py_DECREF(a);
3539 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003540 return NULL;
3541 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003542
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003543 for (i = 0; i < size_z; ++i) {
3544 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3545 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3546 switch (op) {
3547 case '&': z->ob_digit[i] = diga & digb; break;
3548 case '|': z->ob_digit[i] = diga | digb; break;
3549 case '^': z->ob_digit[i] = diga ^ digb; break;
3550 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003551 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003552
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003553 Py_DECREF(a);
3554 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003555 z = long_normalize(z);
3556 if (negz == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003557 return (PyObject *) maybe_small_long(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003558 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003559 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003560 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003561}
3562
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003563static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003564long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003565{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003566 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003567 CHECK_BINOP(a, b);
3568 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003569 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003570}
3571
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003572static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003573long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003574{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003575 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003576 CHECK_BINOP(a, b);
3577 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003578 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003579}
3580
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003581static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003582long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003583{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003584 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003585 CHECK_BINOP(a, b);
3586 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003587 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003588}
3589
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003590static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003591long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003592{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003593 if (PyLong_CheckExact(v))
3594 Py_INCREF(v);
3595 else
3596 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003597 return v;
3598}
3599
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003600static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003601long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003602{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003603 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003604 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003605 if (result == -1.0 && PyErr_Occurred())
3606 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003607 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003608}
3609
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003610static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003611long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003612
Tim Peters6d6c1a32001-08-02 04:15:00 +00003613static PyObject *
3614long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3615{
3616 PyObject *x = NULL;
3617 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003618 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619
Guido van Rossumbef14172001-08-29 15:47:46 +00003620 if (type != &PyLong_Type)
3621 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003622 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623 &x, &base))
3624 return NULL;
3625 if (x == NULL)
3626 return PyLong_FromLong(0L);
3627 if (base == -909)
3628 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003629 else if (PyUnicode_Check(x))
3630 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3631 PyUnicode_GET_SIZE(x),
3632 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003633 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003634 /* Since PyLong_FromString doesn't have a length parameter,
3635 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003636 char *string;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003637 Py_ssize_t size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003638 if (PyByteArray_Check(x))
3639 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003640 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003641 string = PyBytes_AS_STRING(x);
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003642 if (strlen(string) != (size_t)size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003643 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003644 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003645 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003646 "invalid literal for int() with base %d: %R",
3647 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003648 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003649 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003650 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003651 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003652 else {
3653 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003654 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655 return NULL;
3656 }
3657}
3658
Guido van Rossumbef14172001-08-29 15:47:46 +00003659/* Wimpy, slow approach to tp_new calls for subtypes of long:
3660 first create a regular long from whatever arguments we got,
3661 then allocate a subtype instance and initialize it from
3662 the regular long. The regular long is then thrown away.
3663*/
3664static PyObject *
3665long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3666{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003667 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003668 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003669
3670 assert(PyType_IsSubtype(type, &PyLong_Type));
3671 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3672 if (tmp == NULL)
3673 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003674 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003675 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003676 if (n < 0)
3677 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003678 newobj = (PyLongObject *)type->tp_alloc(type, n);
3679 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003680 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003681 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003682 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003683 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003684 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003685 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003686 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003687 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003688 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003689}
3690
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003691static PyObject *
3692long_getnewargs(PyLongObject *v)
3693{
3694 return Py_BuildValue("(N)", _PyLong_Copy(v));
3695}
3696
Guido van Rossumb43daf72007-08-01 18:08:08 +00003697static PyObject *
3698long_getN(PyLongObject *v, void *context) {
Christian Heimesc36625b2008-01-04 13:33:00 +00003699 return PyLong_FromLong((Py_intptr_t)context);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003700}
3701
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003702static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003703long__format__(PyObject *self, PyObject *args)
3704{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003705 PyObject *format_spec;
3706
3707 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3708 return NULL;
3709 return _PyLong_FormatAdvanced(self,
3710 PyUnicode_AS_UNICODE(format_spec),
3711 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003712}
3713
Eric Smith8c663262007-08-25 02:26:07 +00003714static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003715long_round(PyObject *self, PyObject *args)
3716{
Mark Dickinson1124e712009-01-28 21:25:58 +00003717 PyObject *o_ndigits=NULL, *temp;
3718 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
3719 int errcode;
3720 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003721
Mark Dickinson1124e712009-01-28 21:25:58 +00003722 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
3723 the straightforward method is:
3724
3725 (1) divide by 10**n
3726 (2) round to nearest integer (round to even in case of tie)
3727 (3) multiply result by 10**n.
3728
3729 But the rounding step involves examining the fractional part of the
3730 quotient to see whether it's greater than 0.5 or not. Since we
3731 want to do the whole calculation in integer arithmetic, it's
3732 simpler to do:
3733
3734 (1) divide by (10**n)/2
3735 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
3736 (3) multiply result by (10**n)/2.
3737
3738 Then all we need to know about the fractional part of the quotient
3739 arising in step (2) is whether it's zero or not.
3740
3741 Doing both a multiplication and division is wasteful, and is easily
3742 avoided if we just figure out how much to adjust the original input
3743 by to do the rounding.
3744
3745 Here's the whole algorithm expressed in Python.
3746
3747 def round(self, ndigits = None):
3748 """round(int, int) -> int"""
3749 if ndigits is None or ndigits >= 0:
3750 return self
3751 pow = 10**-ndigits >> 1
3752 q, r = divmod(self, pow)
3753 self -= r
3754 if (q & 1 != 0):
3755 if (q & 2 == r == 0):
3756 self -= pow
3757 else:
3758 self += pow
3759 return self
3760
3761 */
3762 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
3763 return NULL;
3764 if (o_ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003765 return long_long(self);
3766
Mark Dickinson1124e712009-01-28 21:25:58 +00003767 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
3768 if (ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003769 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00003770
3771 if (Py_SIZE(ndigits) >= 0) {
3772 Py_DECREF(ndigits);
3773 return long_long(self);
3774 }
3775
3776 Py_INCREF(self); /* to keep refcounting simple */
3777 /* we now own references to self, ndigits */
3778
3779 /* pow = 10 ** -ndigits >> 1 */
3780 pow = (PyLongObject *)PyLong_FromLong(10L);
3781 if (pow == NULL)
3782 goto error;
3783 temp = long_neg(ndigits);
3784 Py_DECREF(ndigits);
3785 ndigits = (PyLongObject *)temp;
3786 if (ndigits == NULL)
3787 goto error;
3788 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
3789 Py_DECREF(pow);
3790 pow = (PyLongObject *)temp;
3791 if (pow == NULL)
3792 goto error;
3793 assert(PyLong_Check(pow)); /* check long_pow returned a long */
3794 one = (PyLongObject *)PyLong_FromLong(1L);
3795 if (one == NULL)
3796 goto error;
3797 temp = long_rshift(pow, one);
3798 Py_DECREF(one);
3799 Py_DECREF(pow);
3800 pow = (PyLongObject *)temp;
3801 if (pow == NULL)
3802 goto error;
3803
3804 /* q, r = divmod(self, pow) */
3805 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
3806 if (errcode == -1)
3807 goto error;
3808
3809 /* self -= r */
3810 temp = long_sub((PyLongObject *)self, r);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003811 Py_DECREF(self);
Mark Dickinson1124e712009-01-28 21:25:58 +00003812 self = temp;
3813 if (self == NULL)
3814 goto error;
3815
3816 /* get value of quotient modulo 4 */
3817 if (Py_SIZE(q) == 0)
3818 q_mod_4 = 0;
3819 else if (Py_SIZE(q) > 0)
3820 q_mod_4 = q->ob_digit[0] & 3;
3821 else
3822 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
3823
3824 if ((q_mod_4 & 1) == 1) {
3825 /* q is odd; round self up or down by adding or subtracting pow */
3826 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
3827 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
3828 else
3829 temp = (PyObject *)long_add((PyLongObject *)self, pow);
3830 Py_DECREF(self);
3831 self = temp;
3832 if (self == NULL)
3833 goto error;
3834 }
3835 Py_DECREF(q);
3836 Py_DECREF(r);
3837 Py_DECREF(pow);
3838 Py_DECREF(ndigits);
3839 return self;
3840
3841 error:
3842 Py_XDECREF(q);
3843 Py_XDECREF(r);
3844 Py_XDECREF(pow);
3845 Py_XDECREF(self);
3846 Py_XDECREF(ndigits);
3847 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003848}
3849
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003850static PyObject *
3851long_sizeof(PyLongObject *v)
3852{
3853 Py_ssize_t res;
3854
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003855 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003856 return PyLong_FromSsize_t(res);
3857}
3858
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003859static PyObject *
3860long_bit_length(PyLongObject *v)
3861{
3862 PyLongObject *result, *x, *y;
3863 Py_ssize_t ndigits, msd_bits = 0;
3864 digit msd;
3865
3866 assert(v != NULL);
3867 assert(PyLong_Check(v));
3868
3869 ndigits = ABS(Py_SIZE(v));
3870 if (ndigits == 0)
3871 return PyLong_FromLong(0);
3872
3873 msd = v->ob_digit[ndigits-1];
3874 while (msd >= 32) {
3875 msd_bits += 6;
3876 msd >>= 6;
3877 }
3878 msd_bits += (long)(BitLengthTable[msd]);
3879
3880 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3881 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3882
3883 /* expression above may overflow; use Python integers instead */
3884 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3885 if (result == NULL)
3886 return NULL;
3887 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3888 if (x == NULL)
3889 goto error;
3890 y = (PyLongObject *)long_mul(result, x);
3891 Py_DECREF(x);
3892 if (y == NULL)
3893 goto error;
3894 Py_DECREF(result);
3895 result = y;
3896
3897 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3898 if (x == NULL)
3899 goto error;
3900 y = (PyLongObject *)long_add(result, x);
3901 Py_DECREF(x);
3902 if (y == NULL)
3903 goto error;
3904 Py_DECREF(result);
3905 result = y;
3906
3907 return (PyObject *)result;
3908
3909error:
3910 Py_DECREF(result);
3911 return NULL;
3912}
3913
3914PyDoc_STRVAR(long_bit_length_doc,
3915"int.bit_length() -> int\n\
3916\n\
3917Number of bits necessary to represent self in binary.\n\
3918>>> bin(37)\n\
3919'0b100101'\n\
3920>>> (37).bit_length()\n\
39216");
3922
Christian Heimes53876d92008-04-19 00:31:39 +00003923#if 0
3924static PyObject *
3925long_is_finite(PyObject *v)
3926{
3927 Py_RETURN_TRUE;
3928}
3929#endif
3930
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003931static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003932 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3933 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003934 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3935 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00003936#if 0
3937 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3938 "Returns always True."},
3939#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003940 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3941 "Truncating an Integral returns itself."},
3942 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3943 "Flooring an Integral returns itself."},
3944 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3945 "Ceiling of an Integral returns itself."},
3946 {"__round__", (PyCFunction)long_round, METH_VARARGS,
Mark Dickinson1124e712009-01-28 21:25:58 +00003947 "Rounding an Integral returns itself.\n"
3948 "Rounding with an ndigits argument also returns an integer."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003949 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003950 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003951 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
3952 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003953 {NULL, NULL} /* sentinel */
3954};
3955
Guido van Rossumb43daf72007-08-01 18:08:08 +00003956static PyGetSetDef long_getset[] = {
3957 {"real",
3958 (getter)long_long, (setter)NULL,
3959 "the real part of a complex number",
3960 NULL},
3961 {"imag",
3962 (getter)long_getN, (setter)NULL,
3963 "the imaginary part of a complex number",
3964 (void*)0},
3965 {"numerator",
3966 (getter)long_long, (setter)NULL,
3967 "the numerator of a rational number in lowest terms",
3968 NULL},
3969 {"denominator",
3970 (getter)long_getN, (setter)NULL,
3971 "the denominator of a rational number in lowest terms",
3972 (void*)1},
3973 {NULL} /* Sentinel */
3974};
3975
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003976PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003977"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003979Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003980point argument will be truncated towards zero (this does not include a\n\
3981string representation of a floating point number!) When converting a\n\
3982string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003983converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003984
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003985static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003986 (binaryfunc) long_add, /*nb_add*/
3987 (binaryfunc) long_sub, /*nb_subtract*/
3988 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003989 long_mod, /*nb_remainder*/
3990 long_divmod, /*nb_divmod*/
3991 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003992 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003993 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003994 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003995 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003996 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003997 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003998 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003999 long_and, /*nb_and*/
4000 long_xor, /*nb_xor*/
4001 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004002 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00004003 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004004 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00004005 0, /* nb_inplace_add */
4006 0, /* nb_inplace_subtract */
4007 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00004008 0, /* nb_inplace_remainder */
4009 0, /* nb_inplace_power */
4010 0, /* nb_inplace_lshift */
4011 0, /* nb_inplace_rshift */
4012 0, /* nb_inplace_and */
4013 0, /* nb_inplace_xor */
4014 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004015 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00004016 long_true_divide, /* nb_true_divide */
4017 0, /* nb_inplace_floor_divide */
4018 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004019 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004020};
4021
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004022PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004023 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00004024 "int", /* tp_name */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004025 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004026 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004027 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004028 0, /* tp_print */
4029 0, /* tp_getattr */
4030 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00004031 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004032 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004033 &long_as_number, /* tp_as_number */
4034 0, /* tp_as_sequence */
4035 0, /* tp_as_mapping */
4036 (hashfunc)long_hash, /* tp_hash */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004037 0, /* tp_call */
4038 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004039 PyObject_GenericGetAttr, /* tp_getattro */
4040 0, /* tp_setattro */
4041 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00004042 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4043 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044 long_doc, /* tp_doc */
4045 0, /* tp_traverse */
4046 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00004047 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004048 0, /* tp_weaklistoffset */
4049 0, /* tp_iter */
4050 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004051 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004052 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00004053 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004054 0, /* tp_base */
4055 0, /* tp_dict */
4056 0, /* tp_descr_get */
4057 0, /* tp_descr_set */
4058 0, /* tp_dictoffset */
4059 0, /* tp_init */
4060 0, /* tp_alloc */
4061 long_new, /* tp_new */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004062 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004063};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004064
Mark Dickinsonbd792642009-03-18 20:06:12 +00004065static PyTypeObject Int_InfoType;
4066
4067PyDoc_STRVAR(int_info__doc__,
4068"sys.int_info\n\
4069\n\
4070A struct sequence that holds information about Python's\n\
4071internal representation of integers. The attributes are read only.");
4072
4073static PyStructSequence_Field int_info_fields[] = {
4074 {"bits_per_digit", "size of a digit in bits"},
4075 {"sizeof_digit", "size in bytes of the C type used to "
4076 "represent a digit"},
4077 {NULL, NULL}
4078};
4079
4080static PyStructSequence_Desc int_info_desc = {
4081 "sys.int_info", /* name */
4082 int_info__doc__, /* doc */
4083 int_info_fields, /* fields */
4084 2 /* number of fields */
4085};
4086
4087PyObject *
4088PyLong_GetInfo(void)
4089{
4090 PyObject* int_info;
4091 int field = 0;
4092 int_info = PyStructSequence_New(&Int_InfoType);
4093 if (int_info == NULL)
4094 return NULL;
Mark Dickinson0bdab682009-04-02 18:41:40 +00004095 PyStructSequence_SET_ITEM(int_info, field++,
4096 PyLong_FromLong(PyLong_SHIFT));
4097 PyStructSequence_SET_ITEM(int_info, field++,
4098 PyLong_FromLong(sizeof(digit)));
Mark Dickinsonbd792642009-03-18 20:06:12 +00004099 if (PyErr_Occurred()) {
4100 Py_CLEAR(int_info);
4101 return NULL;
4102 }
4103 return int_info;
4104}
4105
Guido van Rossumddefaf32007-01-14 03:31:43 +00004106int
4107_PyLong_Init(void)
4108{
4109#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004110 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004111 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004112
4113 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4114 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4115 if (Py_TYPE(v) == &PyLong_Type) {
4116 /* The element is already initialized, most likely
4117 * the Python interpreter was initialized before.
4118 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00004119 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004120 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004121
Christian Heimes48aa4b12008-02-01 16:56:30 +00004122 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4123 _Py_NewReference(op);
4124 /* _Py_NewReference sets the ref count to 1 but
4125 * the ref count might be larger. Set the refcnt
4126 * to the original refcnt + 1 */
4127 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004128 assert(Py_SIZE(op) == size);
4129 assert(v->ob_digit[0] == abs(ival));
4130 }
4131 else {
4132 PyObject_INIT(v, &PyLong_Type);
4133 }
4134 Py_SIZE(v) = size;
4135 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004136 }
4137#endif
Mark Dickinsonbd792642009-03-18 20:06:12 +00004138 /* initialize int_info */
4139 if (Int_InfoType.tp_name == 0)
4140 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
4141
Guido van Rossumddefaf32007-01-14 03:31:43 +00004142 return 1;
4143}
4144
4145void
4146PyLong_Fini(void)
4147{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004148 /* Integers are currently statically allocated. Py_DECREF is not
4149 needed, but Python must forget about the reference or multiple
4150 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004151#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004152 int i;
4153 PyLongObject *v = small_ints;
4154 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4155 _Py_DEC_REFTOTAL;
4156 _Py_ForgetReference((PyObject*)v);
4157 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004158#endif
4159}