blob: 8f7ad4c93a16ab8c3ba595ef28187503a7581683 [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"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00008#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +00009
Guido van Rossumddefaf32007-01-14 03:31:43 +000010#ifndef NSMALLPOSINTS
11#define NSMALLPOSINTS 257
12#endif
13#ifndef NSMALLNEGINTS
14#define NSMALLNEGINTS 5
15#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000016
17#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(x)->ob_digit[0] : \
18 (Py_SIZE(x) == 0 ? 0 : (x)->ob_digit[0]))
19#define ABS(x) ((x) < 0 ? -(x) : (x))
20
Guido van Rossumddefaf32007-01-14 03:31:43 +000021#if NSMALLNEGINTS + NSMALLPOSINTS > 0
22/* Small integers are preallocated in this array so that they
23 can be shared.
24 The integers that are preallocated are those in the range
25 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
26*/
27static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
28#ifdef COUNT_ALLOCS
29int quick_int_allocs, quick_neg_int_allocs;
30#endif
31
Guido van Rossum7eaf8222007-06-18 17:58:50 +000032static PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +000033get_small_int(int ival)
34{
35 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
36 Py_INCREF(v);
37#ifdef COUNT_ALLOCS
38 if (ival >= 0)
39 quick_int_allocs++;
40 else
41 quick_neg_int_allocs++;
42#endif
43 return v;
44}
45#define CHECK_SMALL_INT(ival) \
46 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
47 return get_small_int(ival); \
48 } while(0)
49
Facundo Batista6e6f59b2008-07-24 18:57:11 +000050static PyLongObject *
51maybe_small_long(PyLongObject *v)
52{
53 if (v && ABS(Py_SIZE(v)) <= 1) {
54 int ival = MEDIUM_VALUE(v);
55 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
56 Py_DECREF(v);
57 return (PyLongObject *)get_small_int(ival);
58 }
59 }
60 return v;
61}
Guido van Rossumddefaf32007-01-14 03:31:43 +000062#else
63#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000064#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000065#endif
66
Guido van Rossumddefaf32007-01-14 03:31:43 +000067/* If a freshly-allocated long is already shared, it must
68 be a small integer, so negating it must go to PyLong_FromLong */
69#define NEGATE(x) \
Christian Heimes90aa7642007-12-19 02:45:37 +000070 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
Christian Heimes217cfd12007-12-02 14:31:20 +000071 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000072 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
73 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000074/* For long multiplication, use the O(N**2) school algorithm unless
75 * both operands contain more than KARATSUBA_CUTOFF digits (this
76 * being an internal Python long digit, in base BASE).
77 */
Tim Peters0973b992004-08-29 22:16:50 +000078#define KARATSUBA_CUTOFF 70
79#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000080
Tim Peters47e52ee2004-08-30 02:44:38 +000081/* For exponentiation, use the binary left-to-right algorithm
82 * unless the exponent contains more than FIVEARY_CUTOFF digits.
83 * In that case, do 5 bits at a time. The potential drawback is that
84 * a table of 2**5 intermediate results is computed.
85 */
86#define FIVEARY_CUTOFF 8
87
Tim Peters5af4e6c2002-08-12 02:31:19 +000088#undef MIN
89#undef MAX
90#define MAX(x, y) ((x) < (y) ? (y) : (x))
91#define MIN(x, y) ((x) > (y) ? (y) : (x))
92
Guido van Rossume32e0141992-01-19 16:31:05 +000093/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000094static PyLongObject *long_normalize(PyLongObject *);
95static PyLongObject *mul1(PyLongObject *, wdigit);
96static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000097static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000098
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +0000100 if (--_Py_Ticker < 0) { \
101 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000102 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000103 }
104
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000105/* Normalize (remove leading zeros from) a long int object.
106 Doesn't attempt to free the storage--in most cases, due to the nature
107 of the algorithms used, this could save at most be one word anyway. */
108
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000110long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000111{
Christian Heimes90aa7642007-12-19 02:45:37 +0000112 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000114
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000115 while (i > 0 && v->ob_digit[i-1] == 0)
116 --i;
117 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000118 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000119 return v;
120}
121
122/* Allocate a new long int object with size digits.
123 Return NULL and set exception if we run out of memory. */
124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000128 PyLongObject *result;
129 /* Can't use sizeof(PyLongObject) here, since the
130 compiler takes padding at the end into account.
131 As the consequence, this would waste 2 bytes on
132 a 32-bit system, and 6 bytes on a 64-bit system.
133 This computation would be incorrect on systems
134 which have padding before the digits; with 16-bit
135 digits this should not happen. */
136 result = PyObject_MALLOC(sizeof(PyVarObject) +
137 size*sizeof(digit));
138 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000139 PyErr_NoMemory();
140 return NULL;
141 }
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000142 /* XXX(nnorwitz): This can overflow --
143 PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect overflow */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000144 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000145}
146
Tim Peters64b5ce32001-09-10 20:52:51 +0000147PyObject *
148_PyLong_Copy(PyLongObject *src)
149{
150 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000151 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000152
153 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000154 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000155 if (i < 0)
156 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000157 if (i < 2) {
158 int ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000159 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000160 ival = -ival;
161 CHECK_SMALL_INT(ival);
162 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000163 result = _PyLong_New(i);
164 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000165 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000166 while (--i >= 0)
167 result->ob_digit[i] = src->ob_digit[i];
168 }
169 return (PyObject *)result;
170}
171
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000172/* Create a new long int object from a C long int */
173
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000174PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000175PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000176{
Tim Petersce9de2f2001-06-14 04:56:19 +0000177 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +0000178 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000179 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
180 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000181 int sign = 1;
182
183 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000184
185 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +0000186 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
187 ANSI C says that the result of -ival is undefined when ival
188 == LONG_MIN. Hence the following workaround. */
189 abs_ival = (unsigned long)(-1-ival) + 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000190 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000191 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000192 else {
193 abs_ival = (unsigned long)ival;
194 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000195
Guido van Rossumddefaf32007-01-14 03:31:43 +0000196 /* Fast path for single-digits ints */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000197 if (!(ival>>PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000198 v = _PyLong_New(1);
199 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000200 Py_SIZE(v) = sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000201 v->ob_digit[0] = ival;
202 }
203 return (PyObject*)v;
204 }
205
206 /* 2 digits */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000207 if (!(ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000208 v = _PyLong_New(2);
209 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000210 Py_SIZE(v) = 2*sign;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000211 v->ob_digit[0] = (digit)ival & PyLong_MASK;
212 v->ob_digit[1] = ival >> PyLong_SHIFT;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000213 }
214 return (PyObject*)v;
215 }
216
217 /* Larger numbers: loop to determine number of digits */
Christian Heimesdae2a892008-04-19 00:55:37 +0000218 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000219 while (t) {
220 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000221 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000222 }
223 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000224 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000225 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000226 Py_SIZE(v) = ndigits*sign;
Christian Heimesdae2a892008-04-19 00:55:37 +0000227 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000228 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000229 *p++ = (digit)(t & PyLong_MASK);
230 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000231 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000232 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000233 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000234}
235
Guido van Rossum53756b11997-01-03 17:14:46 +0000236/* Create a new long int object from a C unsigned long int */
237
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000239PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000240{
Tim Petersce9de2f2001-06-14 04:56:19 +0000241 PyLongObject *v;
242 unsigned long t;
243 int ndigits = 0;
244
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000245 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000246 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000247 /* Count the number of Python digits. */
248 t = (unsigned long)ival;
249 while (t) {
250 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000251 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000252 }
253 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000254 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000255 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000256 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000257 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000258 *p++ = (digit)(ival & PyLong_MASK);
259 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000260 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000261 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000262 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000263}
264
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000265/* Create a new long int object from a C double */
266
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000267PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000268PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000270 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000271 double frac;
272 int i, ndig, expo, neg;
273 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000274 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000275 PyErr_SetString(PyExc_OverflowError,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000276 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000277 return NULL;
278 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000279 if (Py_IS_NAN(dval)) {
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000280 PyErr_SetString(PyExc_ValueError,
281 "cannot convert float NaN to integer");
Christian Heimes386cd1e2008-01-15 02:01:20 +0000282 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000283 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000284 if (dval < 0.0) {
285 neg = 1;
286 dval = -dval;
287 }
288 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
289 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000291 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000292 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000293 if (v == NULL)
294 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000295 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000296 for (i = ndig; --i >= 0; ) {
297 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000298 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000299 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000300 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000301 }
302 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000303 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000304 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000305}
306
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
308 * anything about what happens when a signed integer operation overflows,
309 * and some compilers think they're doing you a favor by being "clever"
310 * then. The bit pattern for the largest postive signed long is
311 * (unsigned long)LONG_MAX, and for the smallest negative signed long
312 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
313 * However, some other compilers warn about applying unary minus to an
314 * unsigned operand. Hence the weird "0-".
315 */
316#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
317#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
318
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000319/* Get a C long int from a long int object.
320 Returns -1 and sets an error condition if overflow occurs. */
321
322long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000323PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000324{
Guido van Rossumf7531811998-05-26 14:33:37 +0000325 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000327 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000328 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000329 Py_ssize_t i;
330 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000331 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000332
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000333 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000334 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000336 return -1;
337 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000338
339 if (!PyLong_Check(vv)) {
340 PyNumberMethods *nb;
341 if ((nb = vv->ob_type->tp_as_number) == NULL ||
342 nb->nb_int == NULL) {
343 PyErr_SetString(PyExc_TypeError, "an integer is required");
344 return -1;
345 }
346 vv = (*nb->nb_int) (vv);
347 if (vv == NULL)
348 return -1;
349 do_decref = 1;
350 if (!PyLong_Check(vv)) {
351 Py_DECREF(vv);
352 PyErr_SetString(PyExc_TypeError,
353 "nb_int should return int object");
354 return -1;
355 }
356 }
357
Georg Brandl61c31b02007-02-26 14:46:30 +0000358 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000359 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000360 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000361
Georg Brandl61c31b02007-02-26 14:46:30 +0000362 switch (i) {
363 case -1:
364 res = -v->ob_digit[0];
365 break;
366 case 0:
367 res = 0;
368 break;
369 case 1:
370 res = v->ob_digit[0];
371 break;
372 default:
373 sign = 1;
374 x = 0;
375 if (i < 0) {
376 sign = -1;
377 i = -(i);
378 }
379 while (--i >= 0) {
380 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000381 x = (x << PyLong_SHIFT) + v->ob_digit[i];
382 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000383 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000384 goto exit;
385 }
386 }
387 /* Haven't lost any bits, but casting to long requires extra care
388 * (see comment above).
389 */
390 if (x <= (unsigned long)LONG_MAX) {
391 res = (long)x * sign;
392 }
393 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
394 res = LONG_MIN;
395 }
396 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000397 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000398 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000399 }
400 }
401 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000402 if (do_decref) {
403 Py_DECREF(vv);
404 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000405 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000406}
407
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000408long
409PyLong_AsLong(PyObject *obj)
410{
411 int overflow;
412 long result = PyLong_AsLongAndOverflow(obj, &overflow);
413 if (overflow) {
414 /* XXX: could be cute and give a different
415 message for overflow == -1 */
416 PyErr_SetString(PyExc_OverflowError,
417 "Python int too large to convert to C long");
418 }
419 return result;
420}
421
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000422/* Get a Py_ssize_t from a long int object.
423 Returns -1 and sets an error condition if overflow occurs. */
424
425Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000426PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000427 register PyLongObject *v;
428 size_t x, prev;
429 Py_ssize_t i;
430 int sign;
431
432 if (vv == NULL || !PyLong_Check(vv)) {
433 PyErr_BadInternalCall();
434 return -1;
435 }
436 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000437 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000438 switch (i) {
439 case -1: return -v->ob_digit[0];
440 case 0: return 0;
441 case 1: return v->ob_digit[0];
442 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000443 sign = 1;
444 x = 0;
445 if (i < 0) {
446 sign = -1;
447 i = -(i);
448 }
449 while (--i >= 0) {
450 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000451 x = (x << PyLong_SHIFT) + v->ob_digit[i];
452 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000453 goto overflow;
454 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000455 /* Haven't lost any bits, but casting to a signed type requires
456 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000457 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000458 if (x <= (size_t)PY_SSIZE_T_MAX) {
459 return (Py_ssize_t)x * sign;
460 }
461 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
462 return PY_SSIZE_T_MIN;
463 }
464 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000465
466 overflow:
467 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000468 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000469 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000470}
471
Guido van Rossumd8c80482002-08-13 00:24:58 +0000472/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000473 Returns -1 and sets an error condition if overflow occurs. */
474
475unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000476PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000477{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000478 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000479 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000480 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000481
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000482 if (vv == NULL || !PyLong_Check(vv)) {
483 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000484 return (unsigned long) -1;
485 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000487 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000488 x = 0;
489 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000491 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000492 return (unsigned long) -1;
493 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000494 switch (i) {
495 case 0: return 0;
496 case 1: return v->ob_digit[0];
497 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000498 while (--i >= 0) {
499 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000500 x = (x << PyLong_SHIFT) + v->ob_digit[i];
501 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000502 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000503 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000504 return (unsigned long) -1;
505 }
506 }
507 return x;
508}
509
510/* Get a C unsigned long int from a long int object.
511 Returns -1 and sets an error condition if overflow occurs. */
512
513size_t
514PyLong_AsSize_t(PyObject *vv)
515{
516 register PyLongObject *v;
517 size_t x, prev;
518 Py_ssize_t i;
519
520 if (vv == NULL || !PyLong_Check(vv)) {
521 PyErr_BadInternalCall();
522 return (unsigned long) -1;
523 }
524 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000525 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000526 x = 0;
527 if (i < 0) {
528 PyErr_SetString(PyExc_OverflowError,
529 "can't convert negative value to size_t");
530 return (size_t) -1;
531 }
532 switch (i) {
533 case 0: return 0;
534 case 1: return v->ob_digit[0];
535 }
536 while (--i >= 0) {
537 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000538 x = (x << PyLong_SHIFT) + v->ob_digit[i];
539 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000540 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000541 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000542 return (unsigned long) -1;
543 }
544 }
545 return x;
546}
547
Thomas Hellera4ea6032003-04-17 18:55:45 +0000548/* Get a C unsigned long int from a long int object, ignoring the high bits.
549 Returns -1 and sets an error condition if an error occurs. */
550
Guido van Rossumddefaf32007-01-14 03:31:43 +0000551static unsigned long
552_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000553{
554 register PyLongObject *v;
555 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000556 Py_ssize_t i;
557 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000558
559 if (vv == NULL || !PyLong_Check(vv)) {
560 PyErr_BadInternalCall();
561 return (unsigned long) -1;
562 }
563 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000564 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000565 switch (i) {
566 case 0: return 0;
567 case 1: return v->ob_digit[0];
568 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000569 sign = 1;
570 x = 0;
571 if (i < 0) {
572 sign = -1;
573 i = -i;
574 }
575 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000576 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000577 }
578 return x * sign;
579}
580
Guido van Rossumddefaf32007-01-14 03:31:43 +0000581unsigned long
582PyLong_AsUnsignedLongMask(register PyObject *op)
583{
584 PyNumberMethods *nb;
585 PyLongObject *lo;
586 unsigned long val;
587
588 if (op && PyLong_Check(op))
589 return _PyLong_AsUnsignedLongMask(op);
590
591 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
592 nb->nb_int == NULL) {
593 PyErr_SetString(PyExc_TypeError, "an integer is required");
594 return (unsigned long)-1;
595 }
596
597 lo = (PyLongObject*) (*nb->nb_int) (op);
598 if (lo == NULL)
599 return (unsigned long)-1;
600 if (PyLong_Check(lo)) {
601 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
602 Py_DECREF(lo);
603 if (PyErr_Occurred())
604 return (unsigned long)-1;
605 return val;
606 }
607 else
608 {
609 Py_DECREF(lo);
610 PyErr_SetString(PyExc_TypeError,
611 "nb_int should return int object");
612 return (unsigned long)-1;
613 }
614}
615
Tim Peters5b8132f2003-01-31 15:52:05 +0000616int
617_PyLong_Sign(PyObject *vv)
618{
619 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000620
621 assert(v != NULL);
622 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000623
Christian Heimes90aa7642007-12-19 02:45:37 +0000624 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000625}
626
Tim Petersbaefd9e2003-01-28 20:37:45 +0000627size_t
628_PyLong_NumBits(PyObject *vv)
629{
630 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000631 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000632 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000633
634 assert(v != NULL);
635 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000636 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000637 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
638 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000639 digit msd = v->ob_digit[ndigits - 1];
640
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000641 result = (ndigits - 1) * PyLong_SHIFT;
642 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000643 goto Overflow;
644 do {
645 ++result;
646 if (result == 0)
647 goto Overflow;
648 msd >>= 1;
649 } while (msd);
650 }
651 return result;
652
653Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000654 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000655 "to express in a platform size_t");
656 return (size_t)-1;
657}
658
Tim Peters2a9b3672001-06-11 21:23:58 +0000659PyObject *
660_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
661 int little_endian, int is_signed)
662{
663 const unsigned char* pstartbyte;/* LSB of bytes */
664 int incr; /* direction to move pstartbyte */
665 const unsigned char* pendbyte; /* MSB of bytes */
666 size_t numsignificantbytes; /* number of bytes that matter */
667 size_t ndigits; /* number of Python long digits */
668 PyLongObject* v; /* result */
669 int idigit = 0; /* next free index in v->ob_digit */
670
671 if (n == 0)
672 return PyLong_FromLong(0L);
673
674 if (little_endian) {
675 pstartbyte = bytes;
676 pendbyte = bytes + n - 1;
677 incr = 1;
678 }
679 else {
680 pstartbyte = bytes + n - 1;
681 pendbyte = bytes;
682 incr = -1;
683 }
684
685 if (is_signed)
686 is_signed = *pendbyte >= 0x80;
687
688 /* Compute numsignificantbytes. This consists of finding the most
689 significant byte. Leading 0 bytes are insignficant if the number
690 is positive, and leading 0xff bytes if negative. */
691 {
692 size_t i;
693 const unsigned char* p = pendbyte;
694 const int pincr = -incr; /* search MSB to LSB */
695 const unsigned char insignficant = is_signed ? 0xff : 0x00;
696
697 for (i = 0; i < n; ++i, p += pincr) {
698 if (*p != insignficant)
699 break;
700 }
701 numsignificantbytes = n - i;
702 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
703 actually has 2 significant bytes. OTOH, 0xff0001 ==
704 -0x00ffff, so we wouldn't *need* to bump it there; but we
705 do for 0xffff = -0x0001. To be safe without bothering to
706 check every case, bump it regardless. */
707 if (is_signed && numsignificantbytes < n)
708 ++numsignificantbytes;
709 }
710
711 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000712 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000713 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000714 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000715 if (ndigits > (size_t)INT_MAX)
716 return PyErr_NoMemory();
717 v = _PyLong_New((int)ndigits);
718 if (v == NULL)
719 return NULL;
720
721 /* Copy the bits over. The tricky parts are computing 2's-comp on
722 the fly for signed numbers, and dealing with the mismatch between
723 8-bit bytes and (probably) 15-bit Python digits.*/
724 {
725 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000726 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000727 twodigits accum = 0; /* sliding register */
728 unsigned int accumbits = 0; /* number of bits in accum */
729 const unsigned char* p = pstartbyte;
730
731 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000732 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000733 /* Compute correction for 2's comp, if needed. */
734 if (is_signed) {
735 thisbyte = (0xff ^ thisbyte) + carry;
736 carry = thisbyte >> 8;
737 thisbyte &= 0xff;
738 }
739 /* Because we're going LSB to MSB, thisbyte is
740 more significant than what's already in accum,
741 so needs to be prepended to accum. */
742 accum |= thisbyte << accumbits;
743 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000744 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000745 /* There's enough to fill a Python digit. */
746 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000747 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000748 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000749 accum >>= PyLong_SHIFT;
750 accumbits -= PyLong_SHIFT;
751 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000752 }
753 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000754 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000755 if (accumbits) {
756 assert(idigit < (int)ndigits);
757 v->ob_digit[idigit] = (digit)accum;
758 ++idigit;
759 }
760 }
761
Christian Heimes90aa7642007-12-19 02:45:37 +0000762 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000763 return (PyObject *)long_normalize(v);
764}
765
766int
767_PyLong_AsByteArray(PyLongObject* v,
768 unsigned char* bytes, size_t n,
769 int little_endian, int is_signed)
770{
771 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000772 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000773 twodigits accum; /* sliding register */
774 unsigned int accumbits; /* # bits in accum */
775 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
776 twodigits carry; /* for computing 2's-comp */
777 size_t j; /* # bytes filled */
778 unsigned char* p; /* pointer to next byte in bytes */
779 int pincr; /* direction to move p */
780
781 assert(v != NULL && PyLong_Check(v));
782
Christian Heimes90aa7642007-12-19 02:45:37 +0000783 if (Py_SIZE(v) < 0) {
784 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000785 if (!is_signed) {
786 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000787 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000788 return -1;
789 }
790 do_twos_comp = 1;
791 }
792 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000793 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000794 do_twos_comp = 0;
795 }
796
797 if (little_endian) {
798 p = bytes;
799 pincr = 1;
800 }
801 else {
802 p = bytes + n - 1;
803 pincr = -1;
804 }
805
Tim Peters898cf852001-06-13 20:50:08 +0000806 /* Copy over all the Python digits.
807 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000808 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000809 normalized. */
810 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000811 j = 0;
812 accum = 0;
813 accumbits = 0;
814 carry = do_twos_comp ? 1 : 0;
815 for (i = 0; i < ndigits; ++i) {
816 twodigits thisdigit = v->ob_digit[i];
817 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000818 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
819 carry = thisdigit >> PyLong_SHIFT;
820 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000821 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000822 /* Because we're going LSB to MSB, thisdigit is more
823 significant than what's already in accum, so needs to be
824 prepended to accum. */
825 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000826 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000827
Tim Petersede05092001-06-14 08:53:38 +0000828 /* The most-significant digit may be (probably is) at least
829 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000830 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000831 /* Count # of sign bits -- they needn't be stored,
832 * although for signed conversion we need later to
833 * make sure at least one sign bit gets stored.
834 * First shift conceptual sign bit to real sign bit.
835 */
836 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000837 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000838 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000839 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000840 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000841 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000842 }
Tim Petersede05092001-06-14 08:53:38 +0000843 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000844 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000845
Tim Peters2a9b3672001-06-11 21:23:58 +0000846 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000847 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000848 if (j >= n)
849 goto Overflow;
850 ++j;
851 *p = (unsigned char)(accum & 0xff);
852 p += pincr;
853 accumbits -= 8;
854 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000855 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000856 }
857
858 /* Store the straggler (if any). */
859 assert(accumbits < 8);
860 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000861 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000862 if (j >= n)
863 goto Overflow;
864 ++j;
865 if (do_twos_comp) {
866 /* Fill leading bits of the byte with sign bits
867 (appropriately pretending that the long had an
868 infinite supply of sign bits). */
869 accum |= (~(twodigits)0) << accumbits;
870 }
871 *p = (unsigned char)(accum & 0xff);
872 p += pincr;
873 }
Tim Peters05607ad2001-06-13 21:01:27 +0000874 else if (j == n && n > 0 && is_signed) {
875 /* The main loop filled the byte array exactly, so the code
876 just above didn't get to ensure there's a sign bit, and the
877 loop below wouldn't add one either. Make sure a sign bit
878 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000879 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000880 int sign_bit_set = msb >= 0x80;
881 assert(accumbits == 0);
882 if (sign_bit_set == do_twos_comp)
883 return 0;
884 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000885 goto Overflow;
886 }
Tim Peters05607ad2001-06-13 21:01:27 +0000887
888 /* Fill remaining bytes with copies of the sign bit. */
889 {
890 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
891 for ( ; j < n; ++j, p += pincr)
892 *p = signbyte;
893 }
894
Tim Peters2a9b3672001-06-11 21:23:58 +0000895 return 0;
896
897Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000898 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000899 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000900
Tim Peters2a9b3672001-06-11 21:23:58 +0000901}
902
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000903double
904_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
905{
906/* NBITS_WANTED should be > the number of bits in a double's precision,
907 but small enough so that 2**NBITS_WANTED is within the normal double
908 range. nbitsneeded is set to 1 less than that because the most-significant
909 Python digit contains at least 1 significant bit, but we don't want to
910 bother counting them (catering to the worst case cheaply).
911
912 57 is one more than VAX-D double precision; I (Tim) don't know of a double
913 format with more precision than that; it's 1 larger so that we add in at
914 least one round bit to stand in for the ignored least-significant bits.
915*/
916#define NBITS_WANTED 57
917 PyLongObject *v;
918 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000919 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000920 Py_ssize_t i;
921 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000922 int nbitsneeded;
923
924 if (vv == NULL || !PyLong_Check(vv)) {
925 PyErr_BadInternalCall();
926 return -1;
927 }
928 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000929 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000930 sign = 1;
931 if (i < 0) {
932 sign = -1;
933 i = -(i);
934 }
935 else if (i == 0) {
936 *exponent = 0;
937 return 0.0;
938 }
939 --i;
940 x = (double)v->ob_digit[i];
941 nbitsneeded = NBITS_WANTED - 1;
942 /* Invariant: i Python digits remain unaccounted for. */
943 while (i > 0 && nbitsneeded > 0) {
944 --i;
945 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000946 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000947 }
948 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000949 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000950 *exponent = i;
951 assert(x > 0.0);
952 return x * sign;
953#undef NBITS_WANTED
954}
955
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000956/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000957
958double
Tim Peters9f688bf2000-07-07 15:53:28 +0000959PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000960{
Thomas Wouters553489a2006-02-01 21:32:04 +0000961 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000962 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000963
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000964 if (vv == NULL || !PyLong_Check(vv)) {
965 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000966 return -1;
967 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000968 x = _PyLong_AsScaledDouble(vv, &e);
969 if (x == -1.0 && PyErr_Occurred())
970 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000971 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
972 set correctly after a successful _PyLong_AsScaledDouble() call */
973 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000974 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000975 goto overflow;
976 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000977 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000978 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000979 goto overflow;
980 return x;
981
982overflow:
983 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000984 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000985 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000986}
987
Guido van Rossum78694d91998-09-18 14:14:13 +0000988/* Create a new long (or int) object from a C pointer */
989
990PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000991PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000992{
Tim Peters70128a12001-06-16 08:48:40 +0000993#ifndef HAVE_LONG_LONG
994# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
995#endif
996#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000997# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000998#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000999 /* special-case null pointer */
1000 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +00001001 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001002 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +00001003
Guido van Rossum78694d91998-09-18 14:14:13 +00001004}
1005
1006/* Get a C pointer from a long object (or an int object in some cases) */
1007
1008void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001009PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001010{
1011 /* This function will allow int or long objects. If vv is neither,
1012 then the PyLong_AsLong*() functions will raise the exception:
1013 PyExc_SystemError, "bad argument to internal function"
1014 */
Tim Peters70128a12001-06-16 08:48:40 +00001015#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001016 long x;
1017
Guido van Rossumddefaf32007-01-14 03:31:43 +00001018 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001019 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001020 else
1021 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001022#else
Tim Peters70128a12001-06-16 08:48:40 +00001023
1024#ifndef HAVE_LONG_LONG
1025# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1026#endif
1027#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001028# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001029#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001030 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001031
Guido van Rossumddefaf32007-01-14 03:31:43 +00001032 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001033 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001034 else
1035 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001036
1037#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001038
1039 if (x == -1 && PyErr_Occurred())
1040 return NULL;
1041 return (void *)x;
1042}
1043
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001044#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001045
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001046/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001047 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001048 */
1049
Tim Peterscf37dfc2001-06-14 18:42:50 +00001050#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001051
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001052/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001053
1054PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001055PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001056{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001057 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +00001058 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001059 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1060 int ndigits = 0;
1061 int negative = 0;
1062
Guido van Rossumddefaf32007-01-14 03:31:43 +00001063 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001064 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +00001065 /* avoid signed overflow on negation; see comments
1066 in PyLong_FromLong above. */
1067 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001068 negative = 1;
1069 }
Christian Heimesdae2a892008-04-19 00:55:37 +00001070 else {
1071 abs_ival = (unsigned PY_LONG_LONG)ival;
1072 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073
1074 /* Count the number of Python digits.
1075 We used to pick 5 ("big enough for anything"), but that's a
1076 waste of time and space given that 5*15 = 75 bits are rarely
1077 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001078 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079 while (t) {
1080 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001081 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001082 }
1083 v = _PyLong_New(ndigits);
1084 if (v != NULL) {
1085 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001086 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001087 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001089 *p++ = (digit)(t & PyLong_MASK);
1090 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091 }
1092 }
1093 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001094}
1095
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001096/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001097
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001098PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001099PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001100{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001101 PyLongObject *v;
1102 unsigned PY_LONG_LONG t;
1103 int ndigits = 0;
1104
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001105 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001106 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001107 /* Count the number of Python digits. */
1108 t = (unsigned PY_LONG_LONG)ival;
1109 while (t) {
1110 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001111 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001112 }
1113 v = _PyLong_New(ndigits);
1114 if (v != NULL) {
1115 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001116 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001117 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001118 *p++ = (digit)(ival & PyLong_MASK);
1119 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120 }
1121 }
1122 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001123}
1124
Martin v. Löwis18e16552006-02-15 17:27:45 +00001125/* Create a new long int object from a C Py_ssize_t. */
1126
1127PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001128PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001129{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001130 PyLongObject *v;
1131 size_t abs_ival;
1132 size_t t; /* unsigned so >> doesn't propagate sign bit */
1133 int ndigits = 0;
1134 int negative = 0;
1135
1136 CHECK_SMALL_INT(ival);
1137 if (ival < 0) {
1138 /* avoid signed overflow when ival = SIZE_T_MIN */
1139 abs_ival = (size_t)(-1-ival)+1;
1140 negative = 1;
1141 }
1142 else {
1143 abs_ival = (size_t)ival;
1144 }
1145
1146 /* Count the number of Python digits. */
1147 t = abs_ival;
1148 while (t) {
1149 ++ndigits;
1150 t >>= PyLong_SHIFT;
1151 }
1152 v = _PyLong_New(ndigits);
1153 if (v != NULL) {
1154 digit *p = v->ob_digit;
1155 Py_SIZE(v) = negative ? -ndigits : ndigits;
1156 t = abs_ival;
1157 while (t) {
1158 *p++ = (digit)(t & PyLong_MASK);
1159 t >>= PyLong_SHIFT;
1160 }
1161 }
1162 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001163}
1164
1165/* Create a new long int object from a C size_t. */
1166
1167PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001168PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001169{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001170 PyLongObject *v;
1171 size_t t;
1172 int ndigits = 0;
1173
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001174 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001175 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001176 /* Count the number of Python digits. */
1177 t = ival;
1178 while (t) {
1179 ++ndigits;
1180 t >>= PyLong_SHIFT;
1181 }
1182 v = _PyLong_New(ndigits);
1183 if (v != NULL) {
1184 digit *p = v->ob_digit;
1185 Py_SIZE(v) = ndigits;
1186 while (ival) {
1187 *p++ = (digit)(ival & PyLong_MASK);
1188 ival >>= PyLong_SHIFT;
1189 }
1190 }
1191 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001192}
1193
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001194/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001195 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001196
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001197PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001198PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001199{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001200 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001201 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001202 int one = 1;
1203 int res;
1204
Tim Petersd38b1c72001-09-30 05:09:37 +00001205 if (vv == NULL) {
1206 PyErr_BadInternalCall();
1207 return -1;
1208 }
1209 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001210 PyNumberMethods *nb;
1211 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001212 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1213 nb->nb_int == NULL) {
1214 PyErr_SetString(PyExc_TypeError, "an integer is required");
1215 return -1;
1216 }
1217 io = (*nb->nb_int) (vv);
1218 if (io == NULL)
1219 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001220 if (PyLong_Check(io)) {
1221 bytes = PyLong_AsLongLong(io);
1222 Py_DECREF(io);
1223 return bytes;
1224 }
1225 Py_DECREF(io);
1226 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001227 return -1;
1228 }
1229
Guido van Rossumddefaf32007-01-14 03:31:43 +00001230 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001231 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001232 case -1: return -v->ob_digit[0];
1233 case 0: return 0;
1234 case 1: return v->ob_digit[0];
1235 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001236 res = _PyLong_AsByteArray(
1237 (PyLongObject *)vv, (unsigned char *)&bytes,
1238 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001240 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001241 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001242 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001243 else
1244 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001245}
1246
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001247/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001248 Return -1 and set an error if overflow occurs. */
1249
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001250unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001251PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001252{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001253 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001254 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001255 int one = 1;
1256 int res;
1257
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001258 if (vv == NULL || !PyLong_Check(vv)) {
1259 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001260 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001261 }
1262
Guido van Rossumddefaf32007-01-14 03:31:43 +00001263 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001264 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001265 case 0: return 0;
1266 case 1: return v->ob_digit[0];
1267 }
1268
Tim Petersd1a7da62001-06-13 00:35:57 +00001269 res = _PyLong_AsByteArray(
1270 (PyLongObject *)vv, (unsigned char *)&bytes,
1271 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001272
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001273 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001274 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001275 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001276 else
1277 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001278}
Tim Petersd1a7da62001-06-13 00:35:57 +00001279
Thomas Hellera4ea6032003-04-17 18:55:45 +00001280/* Get a C unsigned long int from a long int object, ignoring the high bits.
1281 Returns -1 and sets an error condition if an error occurs. */
1282
Guido van Rossumddefaf32007-01-14 03:31:43 +00001283static unsigned PY_LONG_LONG
1284_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001285{
1286 register PyLongObject *v;
1287 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001288 Py_ssize_t i;
1289 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001290
1291 if (vv == NULL || !PyLong_Check(vv)) {
1292 PyErr_BadInternalCall();
1293 return (unsigned long) -1;
1294 }
1295 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001296 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001297 case 0: return 0;
1298 case 1: return v->ob_digit[0];
1299 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001300 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001301 sign = 1;
1302 x = 0;
1303 if (i < 0) {
1304 sign = -1;
1305 i = -i;
1306 }
1307 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001308 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001309 }
1310 return x * sign;
1311}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001312
1313unsigned PY_LONG_LONG
1314PyLong_AsUnsignedLongLongMask(register PyObject *op)
1315{
1316 PyNumberMethods *nb;
1317 PyLongObject *lo;
1318 unsigned PY_LONG_LONG val;
1319
1320 if (op && PyLong_Check(op))
1321 return _PyLong_AsUnsignedLongLongMask(op);
1322
1323 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1324 nb->nb_int == NULL) {
1325 PyErr_SetString(PyExc_TypeError, "an integer is required");
1326 return (unsigned PY_LONG_LONG)-1;
1327 }
1328
1329 lo = (PyLongObject*) (*nb->nb_int) (op);
1330 if (lo == NULL)
1331 return (unsigned PY_LONG_LONG)-1;
1332 if (PyLong_Check(lo)) {
1333 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1334 Py_DECREF(lo);
1335 if (PyErr_Occurred())
1336 return (unsigned PY_LONG_LONG)-1;
1337 return val;
1338 }
1339 else
1340 {
1341 Py_DECREF(lo);
1342 PyErr_SetString(PyExc_TypeError,
1343 "nb_int should return int object");
1344 return (unsigned PY_LONG_LONG)-1;
1345 }
1346}
Tim Petersd1a7da62001-06-13 00:35:57 +00001347#undef IS_LITTLE_ENDIAN
1348
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001349#endif /* HAVE_LONG_LONG */
1350
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001351#define CHECK_BINOP(v,w) \
1352 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001353 Py_INCREF(Py_NotImplemented); \
1354 return Py_NotImplemented; \
1355 }
1356
Tim Peters877a2122002-08-12 05:09:36 +00001357/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1358 * is modified in place, by adding y to it. Carries are propagated as far as
1359 * x[m-1], and the remaining carry (0 or 1) is returned.
1360 */
1361static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001362v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001363{
1364 int i;
1365 digit carry = 0;
1366
1367 assert(m >= n);
1368 for (i = 0; i < n; ++i) {
1369 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001370 x[i] = carry & PyLong_MASK;
1371 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001372 assert((carry & 1) == carry);
1373 }
1374 for (; carry && i < m; ++i) {
1375 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001376 x[i] = carry & PyLong_MASK;
1377 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001378 assert((carry & 1) == carry);
1379 }
1380 return carry;
1381}
1382
1383/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1384 * is modified in place, by subtracting y from it. Borrows are propagated as
1385 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1386 */
1387static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001388v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001389{
1390 int i;
1391 digit borrow = 0;
1392
1393 assert(m >= n);
1394 for (i = 0; i < n; ++i) {
1395 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001396 x[i] = borrow & PyLong_MASK;
1397 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001398 borrow &= 1; /* keep only 1 sign bit */
1399 }
1400 for (; borrow && i < m; ++i) {
1401 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001402 x[i] = borrow & PyLong_MASK;
1403 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001404 borrow &= 1;
1405 }
1406 return borrow;
1407}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001408
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001409/* Multiply by a single digit, ignoring the sign. */
1410
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001411static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001412mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001413{
1414 return muladd1(a, n, (digit)0);
1415}
1416
1417/* Multiply by a single digit and add a single digit, ignoring the sign. */
1418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001419static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001420muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001421{
Christian Heimes90aa7642007-12-19 02:45:37 +00001422 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001423 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001424 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001425 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001426
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001427 if (z == NULL)
1428 return NULL;
1429 for (i = 0; i < size_a; ++i) {
1430 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001431 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1432 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001433 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001434 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001435 return long_normalize(z);
1436}
1437
Tim Peters212e6142001-07-14 12:23:19 +00001438/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1439 in pout, and returning the remainder. pin and pout point at the LSD.
1440 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001441 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001442 immutable. */
1443
1444static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001445inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001446{
1447 twodigits rem = 0;
1448
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001449 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001450 pin += size;
1451 pout += size;
1452 while (--size >= 0) {
1453 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001454 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001455 *--pout = hi = (digit)(rem / n);
1456 rem -= hi * n;
1457 }
1458 return (digit)rem;
1459}
1460
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001461/* Divide a long integer by a digit, returning both the quotient
1462 (as function result) and the remainder (through *prem).
1463 The sign of a is ignored; n should not be zero. */
1464
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001465static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001466divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001467{
Christian Heimes90aa7642007-12-19 02:45:37 +00001468 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001469 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001470
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001471 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001472 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001473 if (z == NULL)
1474 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001475 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001476 return long_normalize(z);
1477}
1478
1479/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001480 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001481 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001482
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001483PyObject *
1484_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001485{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001486 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001487 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001488 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001489 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001490 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001491 int bits;
1492 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001493
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001494 if (a == NULL || !PyLong_Check(a)) {
1495 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001496 return NULL;
1497 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001498 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001499 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001500
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001501 /* Compute a rough upper bound for the length of the string */
1502 i = base;
1503 bits = 0;
1504 while (i > 1) {
1505 ++bits;
1506 i >>= 1;
1507 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001508 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001509 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001510 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001511 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001512 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001513 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001514 return NULL;
1515 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001516 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001517 if (str == NULL)
1518 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001519 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001520 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001521 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001522 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001523
Christian Heimes90aa7642007-12-19 02:45:37 +00001524 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001525 *--p = '0';
1526 }
1527 else if ((base & (base - 1)) == 0) {
1528 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001529 twodigits accum = 0;
1530 int accumbits = 0; /* # of bits in accum */
1531 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001532 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001533 while ((i >>= 1) > 1)
1534 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001535
1536 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001537 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001538 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001539 assert(accumbits >= basebits);
1540 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001541 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001542 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001543 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001544 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001545 accumbits -= basebits;
1546 accum >>= basebits;
1547 } while (i < size_a-1 ? accumbits >= basebits :
1548 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001549 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001550 }
1551 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001552 /* Not 0, and base not a power of 2. Divide repeatedly by
1553 base, but for speed use the highest power of base that
1554 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001555 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001556 digit *pin = a->ob_digit;
1557 PyLongObject *scratch;
1558 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001559 digit powbase = base; /* powbase == base ** power */
1560 int power = 1;
1561 for (;;) {
1562 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001563 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001564 break;
1565 powbase = (digit)newpow;
1566 ++power;
1567 }
Tim Peters212e6142001-07-14 12:23:19 +00001568
1569 /* Get a scratch area for repeated division. */
1570 scratch = _PyLong_New(size);
1571 if (scratch == NULL) {
1572 Py_DECREF(str);
1573 return NULL;
1574 }
1575
1576 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001577 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001578 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001579 digit rem = inplace_divrem1(scratch->ob_digit,
1580 pin, size, powbase);
1581 pin = scratch->ob_digit; /* no need to use a again */
1582 if (pin[size - 1] == 0)
1583 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001584 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001585 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001586 Py_DECREF(str);
1587 return NULL;
1588 })
Tim Peters212e6142001-07-14 12:23:19 +00001589
1590 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001591 assert(ntostore > 0);
1592 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001593 digit nextrem = (digit)(rem / base);
1594 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001595 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001596 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001597 *--p = c;
1598 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001599 --ntostore;
1600 /* Termination is a bit delicate: must not
1601 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001602 remaining quotient and rem are both 0. */
1603 } while (ntostore && (size || rem));
1604 } while (size != 0);
1605 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001606 }
1607
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001608 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001609 *--p = 'x';
1610 *--p = '0';
1611 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001612 else if (base == 8) {
1613 *--p = 'o';
1614 *--p = '0';
1615 }
1616 else if (base == 2) {
1617 *--p = 'b';
1618 *--p = '0';
1619 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001620 else if (base != 10) {
1621 *--p = '#';
1622 *--p = '0' + base%10;
1623 if (base > 10)
1624 *--p = '0' + base/10;
1625 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001626 if (sign)
1627 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001628 if (p != PyUnicode_AS_UNICODE(str)) {
1629 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001630 assert(p > q);
1631 do {
1632 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001633 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001634 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1635 Py_DECREF(str);
1636 return NULL;
1637 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001638 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001639 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001640}
1641
Thomas Wouters477c8d52006-05-27 19:21:47 +00001642/* Table of digit values for 8-bit string -> integer conversion.
1643 * '0' maps to 0, ..., '9' maps to 9.
1644 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1645 * All other indices map to 37.
1646 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001647 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001648 */
1649int _PyLong_DigitValue[256] = {
1650 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1651 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1652 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1653 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1654 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1655 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1656 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1657 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1658 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1659 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1660 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1661 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1662 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1663 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1664 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1665 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1666};
1667
1668/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001669 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1670 * non-digit (which may be *str!). A normalized long is returned.
1671 * The point to this routine is that it takes time linear in the number of
1672 * string characters.
1673 */
1674static PyLongObject *
1675long_from_binary_base(char **str, int base)
1676{
1677 char *p = *str;
1678 char *start = p;
1679 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001680 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001681 PyLongObject *z;
1682 twodigits accum;
1683 int bits_in_accum;
1684 digit *pdigit;
1685
1686 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1687 n = base;
1688 for (bits_per_char = -1; n; ++bits_per_char)
1689 n >>= 1;
1690 /* n <- total # of bits needed, while setting p to end-of-string */
1691 n = 0;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001692 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001693 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001694 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001695 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1696 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001697 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001698 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001699 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001700 return NULL;
1701 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001702 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001703 z = _PyLong_New(n);
1704 if (z == NULL)
1705 return NULL;
1706 /* Read string from right, and fill in long from left; i.e.,
1707 * from least to most significant in both.
1708 */
1709 accum = 0;
1710 bits_in_accum = 0;
1711 pdigit = z->ob_digit;
1712 while (--p >= start) {
Christian Heimesbbe741d2008-03-28 10:53:29 +00001713 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001714 assert(k >= 0 && k < base);
1715 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001716 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001717 if (bits_in_accum >= PyLong_SHIFT) {
1718 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001719 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001720 accum >>= PyLong_SHIFT;
1721 bits_in_accum -= PyLong_SHIFT;
1722 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001723 }
1724 }
1725 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001726 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001727 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001728 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001729 }
1730 while (pdigit - z->ob_digit < n)
1731 *pdigit++ = 0;
1732 return long_normalize(z);
1733}
1734
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001735PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001736PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001737{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001738 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001739 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001740 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001741 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001742 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001743
Guido van Rossum472c04f1996-12-05 21:57:21 +00001744 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001745 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001746 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001747 return NULL;
1748 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001749 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001750 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001751 if (*str == '+')
1752 ++str;
1753 else if (*str == '-') {
1754 ++str;
1755 sign = -1;
1756 }
1757 if (base == 0) {
1758 if (str[0] != '0')
1759 base = 10;
1760 else if (str[1] == 'x' || str[1] == 'X')
1761 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001762 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001763 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001764 else if (str[1] == 'b' || str[1] == 'B')
1765 base = 2;
1766 else {
1767 /* "old" (C-style) octal literal, now invalid.
1768 it might still be zero though */
1769 error_if_nonzero = 1;
1770 base = 10;
1771 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001772 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001773 if (str[0] == '0' &&
1774 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1775 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1776 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001777 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001778
Guido van Rossume6762971998-06-22 03:54:46 +00001779 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001780 if ((base & (base - 1)) == 0)
1781 z = long_from_binary_base(&str, base);
1782 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001783/***
1784Binary bases can be converted in time linear in the number of digits, because
1785Python's representation base is binary. Other bases (including decimal!) use
1786the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001787
Thomas Wouters477c8d52006-05-27 19:21:47 +00001788First some math: the largest integer that can be expressed in N base-B digits
1789is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1790case number of Python digits needed to hold it is the smallest integer n s.t.
1791
1792 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1793 BASE**n >= B**N [taking logs to base BASE]
1794 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1795
1796The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1797this quickly. A Python long with that much space is reserved near the start,
1798and the result is computed into it.
1799
1800The input string is actually treated as being in base base**i (i.e., i digits
1801are processed at a time), where two more static arrays hold:
1802
1803 convwidth_base[base] = the largest integer i such that base**i <= BASE
1804 convmultmax_base[base] = base ** convwidth_base[base]
1805
1806The first of these is the largest i such that i consecutive input digits
1807must fit in a single Python digit. The second is effectively the input
1808base we're really using.
1809
1810Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1811convmultmax_base[base], the result is "simply"
1812
1813 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1814
1815where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001816
1817Error analysis: as above, the number of Python digits `n` needed is worst-
1818case
1819
1820 n >= N * log(B)/log(BASE)
1821
1822where `N` is the number of input digits in base `B`. This is computed via
1823
1824 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1825
1826below. Two numeric concerns are how much space this can waste, and whether
1827the computed result can be too small. To be concrete, assume BASE = 2**15,
1828which is the default (and it's unlikely anyone changes that).
1829
1830Waste isn't a problem: provided the first input digit isn't 0, the difference
1831between the worst-case input with N digits and the smallest input with N
1832digits is about a factor of B, but B is small compared to BASE so at most
1833one allocated Python digit can remain unused on that count. If
1834N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1835and adding 1 returns a result 1 larger than necessary. However, that can't
1836happen: whenever B is a power of 2, long_from_binary_base() is called
1837instead, and it's impossible for B**i to be an integer power of 2**15 when
1838B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1839an exact integer when B is not a power of 2, since B**i has a prime factor
1840other than 2 in that case, but (2**15)**j's only prime factor is 2).
1841
1842The computed result can be too small if the true value of N*log(B)/log(BASE)
1843is a little bit larger than an exact integer, but due to roundoff errors (in
1844computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1845yields a numeric result a little less than that integer. Unfortunately, "how
1846close can a transcendental function get to an integer over some range?"
1847questions are generally theoretically intractable. Computer analysis via
1848continued fractions is practical: expand log(B)/log(BASE) via continued
1849fractions, giving a sequence i/j of "the best" rational approximations. Then
1850j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1851we can get very close to being in trouble, but very rarely. For example,
185276573 is a denominator in one of the continued-fraction approximations to
1853log(10)/log(2**15), and indeed:
1854
1855 >>> log(10)/log(2**15)*76573
1856 16958.000000654003
1857
1858is very close to an integer. If we were working with IEEE single-precision,
1859rounding errors could kill us. Finding worst cases in IEEE double-precision
1860requires better-than-double-precision log() functions, and Tim didn't bother.
1861Instead the code checks to see whether the allocated space is enough as each
1862new Python digit is added, and copies the whole thing to a larger long if not.
1863This should happen extremely rarely, and in fact I don't have a test case
1864that triggers it(!). Instead the code was tested by artificially allocating
1865just 1 digit at the start, so that the copying code was exercised for every
1866digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001867***/
1868 register twodigits c; /* current input character */
1869 Py_ssize_t size_z;
1870 int i;
1871 int convwidth;
1872 twodigits convmultmax, convmult;
1873 digit *pz, *pzstop;
1874 char* scan;
1875
1876 static double log_base_BASE[37] = {0.0e0,};
1877 static int convwidth_base[37] = {0,};
1878 static twodigits convmultmax_base[37] = {0,};
1879
1880 if (log_base_BASE[base] == 0.0) {
1881 twodigits convmax = base;
1882 int i = 1;
1883
1884 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001885 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001886 for (;;) {
1887 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001888 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001889 break;
1890 convmax = next;
1891 ++i;
1892 }
1893 convmultmax_base[base] = convmax;
1894 assert(i > 0);
1895 convwidth_base[base] = i;
1896 }
1897
1898 /* Find length of the string of numeric characters. */
1899 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001900 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001901 ++scan;
1902
1903 /* Create a long object that can contain the largest possible
1904 * integer with this base and length. Note that there's no
1905 * need to initialize z->ob_digit -- no slot is read up before
1906 * being stored into.
1907 */
1908 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001909 /* Uncomment next line to test exceedingly rare copy code */
1910 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001911 assert(size_z > 0);
1912 z = _PyLong_New(size_z);
1913 if (z == NULL)
1914 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001915 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001916
1917 /* `convwidth` consecutive input digits are treated as a single
1918 * digit in base `convmultmax`.
1919 */
1920 convwidth = convwidth_base[base];
1921 convmultmax = convmultmax_base[base];
1922
1923 /* Work ;-) */
1924 while (str < scan) {
1925 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001926 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00001927 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1928 c = (twodigits)(c * base +
Christian Heimesbbe741d2008-03-28 10:53:29 +00001929 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001930 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001931 }
1932
1933 convmult = convmultmax;
1934 /* Calculate the shift only if we couldn't get
1935 * convwidth digits.
1936 */
1937 if (i != convwidth) {
1938 convmult = base;
1939 for ( ; i > 1; --i)
1940 convmult *= base;
1941 }
1942
1943 /* Multiply z by convmult, and add c. */
1944 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001945 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001946 for (; pz < pzstop; ++pz) {
1947 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001948 *pz = (digit)(c & PyLong_MASK);
1949 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001950 }
1951 /* carry off the current end? */
1952 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001953 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001954 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001955 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001956 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001957 }
1958 else {
1959 PyLongObject *tmp;
1960 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001961 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001962 tmp = _PyLong_New(size_z + 1);
1963 if (tmp == NULL) {
1964 Py_DECREF(z);
1965 return NULL;
1966 }
1967 memcpy(tmp->ob_digit,
1968 z->ob_digit,
1969 sizeof(digit) * size_z);
1970 Py_DECREF(z);
1971 z = tmp;
1972 z->ob_digit[size_z] = (digit)c;
1973 ++size_z;
1974 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001975 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001976 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001977 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001978 if (z == NULL)
1979 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001980 if (error_if_nonzero) {
1981 /* reset the base to 0, else the exception message
1982 doesn't make too much sense */
1983 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00001984 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001985 goto onError;
1986 /* there might still be other problems, therefore base
1987 remains zero here for the same reason */
1988 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001989 if (str == start)
1990 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001991 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00001992 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001993 if (*str == 'L' || *str == 'l')
1994 str++;
1995 while (*str && isspace(Py_CHARMASK(*str)))
1996 str++;
1997 if (*str != '\0')
1998 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001999 if (pend)
2000 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00002001 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002002 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002003
2004 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002005 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002006 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002007 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002008 if (strobj == NULL)
2009 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002010 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002011 "invalid literal for int() with base %d: %R",
2012 base, strobj);
2013 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002014 return NULL;
2015}
2016
2017PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002018PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002019{
Walter Dörwald07e14762002-11-06 16:15:14 +00002020 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002021 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002022
Walter Dörwald07e14762002-11-06 16:15:14 +00002023 if (buffer == NULL)
2024 return NULL;
2025
2026 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2027 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002028 return NULL;
2029 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002030 result = PyLong_FromString(buffer, NULL, base);
2031 PyMem_FREE(buffer);
2032 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002033}
2034
Tim Peters9f688bf2000-07-07 15:53:28 +00002035/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002036static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002037 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002038static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00002039static int long_divrem(PyLongObject *, PyLongObject *,
2040 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002041
2042/* Long division with remainder, top-level routine */
2043
Guido van Rossume32e0141992-01-19 16:31:05 +00002044static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002045long_divrem(PyLongObject *a, PyLongObject *b,
2046 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002047{
Christian Heimes90aa7642007-12-19 02:45:37 +00002048 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002049 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002050
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002051 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002052 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002053 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002054 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002055 }
2056 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002057 (size_a == size_b &&
2058 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002059 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002060 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002061 if (*pdiv == NULL)
2062 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002063 Py_INCREF(a);
2064 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002065 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002066 }
2067 if (size_b == 1) {
2068 digit rem = 0;
2069 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002070 if (z == NULL)
2071 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002072 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002073 if (*prem == NULL) {
2074 Py_DECREF(z);
2075 return -1;
2076 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002077 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002078 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002080 if (z == NULL)
2081 return -1;
2082 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002083 /* Set the signs.
2084 The quotient z has the sign of a*b;
2085 the remainder r has the sign of a,
2086 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002087 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002088 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002089 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002090 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002091 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002092 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002093}
2094
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002095/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002096
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002097static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002098x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002099{
Christian Heimes90aa7642007-12-19 02:45:37 +00002100 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002101 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102 PyLongObject *v = mul1(v1, d);
2103 PyLongObject *w = mul1(w1, d);
2104 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002105 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002106
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002107 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002108 Py_XDECREF(v);
2109 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002110 return NULL;
2111 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002112
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002113 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002114 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
2115 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002116
Christian Heimes90aa7642007-12-19 02:45:37 +00002117 size_v = ABS(Py_SIZE(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002118 k = size_v - size_w;
2119 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002120
Thomas Wouters477c8d52006-05-27 19:21:47 +00002121 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002122 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2123 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002124 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002125 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002126
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002127 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002128 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002129 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002130 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002131 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002133 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002134 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002135 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002136 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002137
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002138 while (w->ob_digit[size_w-2]*q >
2139 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002140 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002141 + v->ob_digit[j-1]
2142 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002143 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002144 + v->ob_digit[j-2])
2145 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002146
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002147 for (i = 0; i < size_w && i+k < size_v; ++i) {
2148 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002149 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002150 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002151 + ((twodigits)zz << PyLong_SHIFT);
2152 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002153 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002154 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002155 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002156 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002157
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002158 if (i+k < size_v) {
2159 carry += v->ob_digit[i+k];
2160 v->ob_digit[i+k] = 0;
2161 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002162
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002163 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002164 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002165 else {
2166 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002167 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002168 carry = 0;
2169 for (i = 0; i < size_w && i+k < size_v; ++i) {
2170 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002171 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002172 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2173 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002174 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002175 }
2176 }
2177 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002178
Guido van Rossumc206c761995-01-10 15:23:19 +00002179 if (a == NULL)
2180 *prem = NULL;
2181 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002182 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002183 *prem = divrem1(v, d, &d);
2184 /* d receives the (unused) remainder */
2185 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002186 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002187 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002188 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002189 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002190 Py_DECREF(v);
2191 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002192 return a;
2193}
2194
2195/* Methods */
2196
2197static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002198long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002199{
Christian Heimes90aa7642007-12-19 02:45:37 +00002200 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002201}
2202
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002203static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002204long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002205{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002206 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002207}
2208
2209static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002210long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002211{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002212 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002213
Christian Heimes90aa7642007-12-19 02:45:37 +00002214 if (Py_SIZE(a) != Py_SIZE(b)) {
2215 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002216 sign = 0;
2217 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002218 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002219 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002220 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002221 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002222 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2223 ;
2224 if (i < 0)
2225 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002226 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002227 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002228 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002229 sign = -sign;
2230 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002231 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002232 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002233}
2234
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002235static PyObject *
2236long_richcompare(PyObject *self, PyObject *other, int op)
2237{
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002238 PyObject *result;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002239 CHECK_BINOP(self, other);
2240 result = Py_CmpToRich(op, long_compare((PyLongObject*)self,
2241 (PyLongObject*)other));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002242 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002243}
2244
Guido van Rossum9bfef441993-03-29 10:43:31 +00002245static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002246long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002247{
2248 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002249 Py_ssize_t i;
2250 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002251
2252 /* This is designed so that Python ints and longs with the
2253 same value hash to the same value, otherwise comparisons
2254 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002255 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002256 switch(i) {
2257 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2258 case 0: return 0;
2259 case 1: return v->ob_digit[0];
2260 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002261 sign = 1;
2262 x = 0;
2263 if (i < 0) {
2264 sign = -1;
2265 i = -(i);
2266 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002267#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Thomas Woutersce272b62007-09-19 21:19:28 +00002268 /* The following loop produces a C long x such that (unsigned long)x
2269 is congruent to the absolute value of v modulo ULONG_MAX. The
2270 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002271 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002272 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002273 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002274 x += v->ob_digit[i];
Thomas Woutersce272b62007-09-19 21:19:28 +00002275 /* If the addition above overflowed (thinking of x as
2276 unsigned), we compensate by incrementing. This preserves
2277 the value modulo ULONG_MAX. */
2278 if ((unsigned long)x < v->ob_digit[i])
2279 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002280 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002281#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002282 x = x * sign;
2283 if (x == -1)
2284 x = -2;
2285 return x;
2286}
2287
2288
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002289/* Add the absolute values of two long integers. */
2290
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002291static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002292x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002293{
Christian Heimes90aa7642007-12-19 02:45:37 +00002294 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002295 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002296 int i;
2297 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002298
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002299 /* Ensure a is the larger of the two: */
2300 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002301 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002302 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002303 size_a = size_b;
2304 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002305 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002306 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002307 if (z == NULL)
2308 return NULL;
2309 for (i = 0; i < size_b; ++i) {
2310 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002311 z->ob_digit[i] = carry & PyLong_MASK;
2312 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002313 }
2314 for (; i < size_a; ++i) {
2315 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002316 z->ob_digit[i] = carry & PyLong_MASK;
2317 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002318 }
2319 z->ob_digit[i] = carry;
2320 return long_normalize(z);
2321}
2322
2323/* Subtract the absolute values of two integers. */
2324
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002325static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002326x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002327{
Christian Heimes90aa7642007-12-19 02:45:37 +00002328 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002329 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002330 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002331 int sign = 1;
2332 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002333
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002334 /* Ensure a is the larger of the two: */
2335 if (size_a < size_b) {
2336 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002337 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002338 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002339 size_a = size_b;
2340 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002341 }
2342 else if (size_a == size_b) {
2343 /* Find highest digit where a and b differ: */
2344 i = size_a;
2345 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2346 ;
2347 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002348 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002349 if (a->ob_digit[i] < b->ob_digit[i]) {
2350 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002351 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002352 }
2353 size_a = size_b = i+1;
2354 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002355 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002356 if (z == NULL)
2357 return NULL;
2358 for (i = 0; i < size_b; ++i) {
2359 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002360 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002361 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002362 z->ob_digit[i] = borrow & PyLong_MASK;
2363 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002364 borrow &= 1; /* Keep only one sign bit */
2365 }
2366 for (; i < size_a; ++i) {
2367 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002368 z->ob_digit[i] = borrow & PyLong_MASK;
2369 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002370 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002371 }
2372 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002373 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002374 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002375 return long_normalize(z);
2376}
2377
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002378static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002379long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002380{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002381 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002382
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002383 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002384
Christian Heimes90aa7642007-12-19 02:45:37 +00002385 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002386 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002387 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002388 return result;
2389 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002390 if (Py_SIZE(a) < 0) {
2391 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002392 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002393 if (z != NULL && Py_SIZE(z) != 0)
2394 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002395 }
2396 else
2397 z = x_sub(b, a);
2398 }
2399 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002400 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002401 z = x_sub(a, b);
2402 else
2403 z = x_add(a, b);
2404 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002405 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002406}
2407
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002408static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002409long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002410{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002411 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002412
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002413 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002414
Christian Heimes90aa7642007-12-19 02:45:37 +00002415 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002416 PyObject* r;
2417 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002418 return r;
2419 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002420 if (Py_SIZE(a) < 0) {
2421 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002422 z = x_sub(a, b);
2423 else
2424 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002425 if (z != NULL && Py_SIZE(z) != 0)
2426 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002427 }
2428 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002429 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002430 z = x_add(a, b);
2431 else
2432 z = x_sub(a, b);
2433 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002434 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002435}
2436
Tim Peters5af4e6c2002-08-12 02:31:19 +00002437/* Grade school multiplication, ignoring the signs.
2438 * Returns the absolute value of the product, or NULL if error.
2439 */
2440static PyLongObject *
2441x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002442{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002443 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002444 Py_ssize_t size_a = ABS(Py_SIZE(a));
2445 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002446 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002447
Tim Peters5af4e6c2002-08-12 02:31:19 +00002448 z = _PyLong_New(size_a + size_b);
2449 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002450 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002451
Christian Heimes90aa7642007-12-19 02:45:37 +00002452 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002453 if (a == b) {
2454 /* Efficient squaring per HAC, Algorithm 14.16:
2455 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2456 * Gives slightly less than a 2x speedup when a == b,
2457 * via exploiting that each entry in the multiplication
2458 * pyramid appears twice (except for the size_a squares).
2459 */
2460 for (i = 0; i < size_a; ++i) {
2461 twodigits carry;
2462 twodigits f = a->ob_digit[i];
2463 digit *pz = z->ob_digit + (i << 1);
2464 digit *pa = a->ob_digit + i + 1;
2465 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002466
Tim Peters0973b992004-08-29 22:16:50 +00002467 SIGCHECK({
2468 Py_DECREF(z);
2469 return NULL;
2470 })
2471
2472 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002473 *pz++ = (digit)(carry & PyLong_MASK);
2474 carry >>= PyLong_SHIFT;
2475 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002476
2477 /* Now f is added in twice in each column of the
2478 * pyramid it appears. Same as adding f<<1 once.
2479 */
2480 f <<= 1;
2481 while (pa < paend) {
2482 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002483 *pz++ = (digit)(carry & PyLong_MASK);
2484 carry >>= PyLong_SHIFT;
2485 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002486 }
2487 if (carry) {
2488 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002489 *pz++ = (digit)(carry & PyLong_MASK);
2490 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002491 }
2492 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002493 *pz += (digit)(carry & PyLong_MASK);
2494 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002495 }
Tim Peters0973b992004-08-29 22:16:50 +00002496 }
2497 else { /* a is not the same as b -- gradeschool long mult */
2498 for (i = 0; i < size_a; ++i) {
2499 twodigits carry = 0;
2500 twodigits f = a->ob_digit[i];
2501 digit *pz = z->ob_digit + i;
2502 digit *pb = b->ob_digit;
2503 digit *pbend = b->ob_digit + size_b;
2504
2505 SIGCHECK({
2506 Py_DECREF(z);
2507 return NULL;
2508 })
2509
2510 while (pb < pbend) {
2511 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002512 *pz++ = (digit)(carry & PyLong_MASK);
2513 carry >>= PyLong_SHIFT;
2514 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002515 }
2516 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002517 *pz += (digit)(carry & PyLong_MASK);
2518 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002519 }
2520 }
Tim Peters44121a62002-08-12 06:17:58 +00002521 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002522}
2523
2524/* A helper for Karatsuba multiplication (k_mul).
2525 Takes a long "n" and an integer "size" representing the place to
2526 split, and sets low and high such that abs(n) == (high << size) + low,
2527 viewing the shift as being by digits. The sign bit is ignored, and
2528 the return values are >= 0.
2529 Returns 0 on success, -1 on failure.
2530*/
2531static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002532kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002533{
2534 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002535 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002536 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002537
2538 size_lo = MIN(size_n, size);
2539 size_hi = size_n - size_lo;
2540
2541 if ((hi = _PyLong_New(size_hi)) == NULL)
2542 return -1;
2543 if ((lo = _PyLong_New(size_lo)) == NULL) {
2544 Py_DECREF(hi);
2545 return -1;
2546 }
2547
2548 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2549 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2550
2551 *high = long_normalize(hi);
2552 *low = long_normalize(lo);
2553 return 0;
2554}
2555
Tim Peters60004642002-08-12 22:01:34 +00002556static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2557
Tim Peters5af4e6c2002-08-12 02:31:19 +00002558/* Karatsuba multiplication. Ignores the input signs, and returns the
2559 * absolute value of the product (or NULL if error).
2560 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2561 */
2562static PyLongObject *
2563k_mul(PyLongObject *a, PyLongObject *b)
2564{
Christian Heimes90aa7642007-12-19 02:45:37 +00002565 Py_ssize_t asize = ABS(Py_SIZE(a));
2566 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002567 PyLongObject *ah = NULL;
2568 PyLongObject *al = NULL;
2569 PyLongObject *bh = NULL;
2570 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002571 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002572 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002573 Py_ssize_t shift; /* the number of digits we split off */
2574 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002575
Tim Peters5af4e6c2002-08-12 02:31:19 +00002576 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2577 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2578 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002579 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002580 * By picking X to be a power of 2, "*X" is just shifting, and it's
2581 * been reduced to 3 multiplies on numbers half the size.
2582 */
2583
Tim Petersfc07e562002-08-12 02:54:10 +00002584 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002585 * is largest.
2586 */
Tim Peters738eda72002-08-12 15:08:20 +00002587 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002588 t1 = a;
2589 a = b;
2590 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002591
2592 i = asize;
2593 asize = bsize;
2594 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002595 }
2596
2597 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002598 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2599 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002600 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002601 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002602 else
2603 return x_mul(a, b);
2604 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002605
Tim Peters60004642002-08-12 22:01:34 +00002606 /* If a is small compared to b, splitting on b gives a degenerate
2607 * case with ah==0, and Karatsuba may be (even much) less efficient
2608 * than "grade school" then. However, we can still win, by viewing
2609 * b as a string of "big digits", each of width a->ob_size. That
2610 * leads to a sequence of balanced calls to k_mul.
2611 */
2612 if (2 * asize <= bsize)
2613 return k_lopsided_mul(a, b);
2614
Tim Petersd6974a52002-08-13 20:37:51 +00002615 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002616 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002617 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002618 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002619
Tim Peters0973b992004-08-29 22:16:50 +00002620 if (a == b) {
2621 bh = ah;
2622 bl = al;
2623 Py_INCREF(bh);
2624 Py_INCREF(bl);
2625 }
2626 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002627
Tim Petersd64c1de2002-08-12 17:36:03 +00002628 /* The plan:
2629 * 1. Allocate result space (asize + bsize digits: that's always
2630 * enough).
2631 * 2. Compute ah*bh, and copy into result at 2*shift.
2632 * 3. Compute al*bl, and copy into result at 0. Note that this
2633 * can't overlap with #2.
2634 * 4. Subtract al*bl from the result, starting at shift. This may
2635 * underflow (borrow out of the high digit), but we don't care:
2636 * we're effectively doing unsigned arithmetic mod
2637 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2638 * borrows and carries out of the high digit can be ignored.
2639 * 5. Subtract ah*bh from the result, starting at shift.
2640 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2641 * at shift.
2642 */
2643
2644 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002645 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002646 if (ret == NULL) goto fail;
2647#ifdef Py_DEBUG
2648 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002649 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002650#endif
Tim Peters44121a62002-08-12 06:17:58 +00002651
Tim Petersd64c1de2002-08-12 17:36:03 +00002652 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002653 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002654 assert(Py_SIZE(t1) >= 0);
2655 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002656 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002657 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002658
2659 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002660 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002661 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002662 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002663 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002664
Tim Petersd64c1de2002-08-12 17:36:03 +00002665 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002666 if ((t2 = k_mul(al, bl)) == NULL) {
2667 Py_DECREF(t1);
2668 goto fail;
2669 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002670 assert(Py_SIZE(t2) >= 0);
2671 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2672 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002673
2674 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002675 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002676 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002677 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002678
Tim Petersd64c1de2002-08-12 17:36:03 +00002679 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2680 * because it's fresher in cache.
2681 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002682 i = Py_SIZE(ret) - shift; /* # digits after shift */
2683 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002684 Py_DECREF(t2);
2685
Christian Heimes90aa7642007-12-19 02:45:37 +00002686 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002687 Py_DECREF(t1);
2688
Tim Petersd64c1de2002-08-12 17:36:03 +00002689 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002690 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2691 Py_DECREF(ah);
2692 Py_DECREF(al);
2693 ah = al = NULL;
2694
Tim Peters0973b992004-08-29 22:16:50 +00002695 if (a == b) {
2696 t2 = t1;
2697 Py_INCREF(t2);
2698 }
2699 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002700 Py_DECREF(t1);
2701 goto fail;
2702 }
2703 Py_DECREF(bh);
2704 Py_DECREF(bl);
2705 bh = bl = NULL;
2706
Tim Peters738eda72002-08-12 15:08:20 +00002707 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002708 Py_DECREF(t1);
2709 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002710 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002711 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002712
Tim Petersd6974a52002-08-13 20:37:51 +00002713 /* Add t3. It's not obvious why we can't run out of room here.
2714 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002715 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002716 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002717 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002718
Tim Peters5af4e6c2002-08-12 02:31:19 +00002719 return long_normalize(ret);
2720
2721 fail:
2722 Py_XDECREF(ret);
2723 Py_XDECREF(ah);
2724 Py_XDECREF(al);
2725 Py_XDECREF(bh);
2726 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002727 return NULL;
2728}
2729
Tim Petersd6974a52002-08-13 20:37:51 +00002730/* (*) Why adding t3 can't "run out of room" above.
2731
Tim Petersab86c2b2002-08-15 20:06:00 +00002732Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2733to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002734
Tim Petersab86c2b2002-08-15 20:06:00 +000027351. For any integer i, i = c(i/2) + f(i/2). In particular,
2736 bsize = c(bsize/2) + f(bsize/2).
27372. shift = f(bsize/2)
27383. asize <= bsize
27394. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2740 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002741
Tim Petersab86c2b2002-08-15 20:06:00 +00002742We allocated asize + bsize result digits, and add t3 into them at an offset
2743of shift. This leaves asize+bsize-shift allocated digit positions for t3
2744to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2745asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002746
Tim Petersab86c2b2002-08-15 20:06:00 +00002747bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2748at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002749
Tim Petersab86c2b2002-08-15 20:06:00 +00002750If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2751digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2752most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002753
Tim Petersab86c2b2002-08-15 20:06:00 +00002754The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002755
Tim Petersab86c2b2002-08-15 20:06:00 +00002756 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002757
Tim Petersab86c2b2002-08-15 20:06:00 +00002758and we have asize + c(bsize/2) available digit positions. We need to show
2759this is always enough. An instance of c(bsize/2) cancels out in both, so
2760the question reduces to whether asize digits is enough to hold
2761(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2762then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2763asize 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 +00002764digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002765asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002766c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2767is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2768bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002769
Tim Peters48d52c02002-08-14 17:07:32 +00002770Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2771clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2772ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002773*/
2774
Tim Peters60004642002-08-12 22:01:34 +00002775/* b has at least twice the digits of a, and a is big enough that Karatsuba
2776 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2777 * of slices, each with a->ob_size digits, and multiply the slices by a,
2778 * one at a time. This gives k_mul balanced inputs to work with, and is
2779 * also cache-friendly (we compute one double-width slice of the result
2780 * at a time, then move on, never bactracking except for the helpful
2781 * single-width slice overlap between successive partial sums).
2782 */
2783static PyLongObject *
2784k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2785{
Christian Heimes90aa7642007-12-19 02:45:37 +00002786 const Py_ssize_t asize = ABS(Py_SIZE(a));
2787 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002788 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002789 PyLongObject *ret;
2790 PyLongObject *bslice = NULL;
2791
2792 assert(asize > KARATSUBA_CUTOFF);
2793 assert(2 * asize <= bsize);
2794
2795 /* Allocate result space, and zero it out. */
2796 ret = _PyLong_New(asize + bsize);
2797 if (ret == NULL)
2798 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002799 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002800
2801 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002802 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002803 if (bslice == NULL)
2804 goto fail;
2805
2806 nbdone = 0;
2807 while (bsize > 0) {
2808 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002809 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002810
2811 /* Multiply the next slice of b by a. */
2812 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2813 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002814 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002815 product = k_mul(a, bslice);
2816 if (product == NULL)
2817 goto fail;
2818
2819 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002820 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2821 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002822 Py_DECREF(product);
2823
2824 bsize -= nbtouse;
2825 nbdone += nbtouse;
2826 }
2827
2828 Py_DECREF(bslice);
2829 return long_normalize(ret);
2830
2831 fail:
2832 Py_DECREF(ret);
2833 Py_XDECREF(bslice);
2834 return NULL;
2835}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002836
2837static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002838long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002839{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002840 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002841
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002842 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002843
Christian Heimes90aa7642007-12-19 02:45:37 +00002844 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002845 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002846 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002847 return r;
2848 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002849
Tim Petersd64c1de2002-08-12 17:36:03 +00002850 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002851 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002852 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002853 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002854 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002855}
2856
Guido van Rossume32e0141992-01-19 16:31:05 +00002857/* The / and % operators are now defined in terms of divmod().
2858 The expression a mod b has the value a - b*floor(a/b).
2859 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002860 |a| by |b|, with the sign of a. This is also expressed
2861 as a - b*trunc(a/b), if trunc truncates towards zero.
2862 Some examples:
2863 a b a rem b a mod b
2864 13 10 3 3
2865 -13 10 -3 7
2866 13 -10 3 -7
2867 -13 -10 -3 -3
2868 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002869 have different signs. We then subtract one from the 'div'
2870 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002871
Tim Peters47e52ee2004-08-30 02:44:38 +00002872/* Compute
2873 * *pdiv, *pmod = divmod(v, w)
2874 * NULL can be passed for pdiv or pmod, in which case that part of
2875 * the result is simply thrown away. The caller owns a reference to
2876 * each of these it requests (does not pass NULL for).
2877 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002878static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002879l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002880 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002881{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002882 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002883
Guido van Rossume32e0141992-01-19 16:31:05 +00002884 if (long_divrem(v, w, &div, &mod) < 0)
2885 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002886 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2887 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002888 PyLongObject *temp;
2889 PyLongObject *one;
2890 temp = (PyLongObject *) long_add(mod, w);
2891 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002892 mod = temp;
2893 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002894 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002895 return -1;
2896 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002897 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002898 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002899 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2900 Py_DECREF(mod);
2901 Py_DECREF(div);
2902 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002903 return -1;
2904 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002905 Py_DECREF(one);
2906 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002907 div = temp;
2908 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002909 if (pdiv != NULL)
2910 *pdiv = div;
2911 else
2912 Py_DECREF(div);
2913
2914 if (pmod != NULL)
2915 *pmod = mod;
2916 else
2917 Py_DECREF(mod);
2918
Guido van Rossume32e0141992-01-19 16:31:05 +00002919 return 0;
2920}
2921
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002922static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002923long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002924{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002925 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002926
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002927 CHECK_BINOP(a, b);
2928 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002929 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002930 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002931}
2932
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002933static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002934long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002935{
Tim Peterse2a60002001-09-04 06:17:36 +00002936 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002937 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002938
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002939 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002940 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2941 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002942 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002943 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002944 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002945 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2946 but should really be set correctly after sucessful calls to
2947 _PyLong_AsScaledDouble() */
2948 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002949
2950 if (bd == 0.0) {
2951 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002952 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002953 return NULL;
2954 }
2955
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002956 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002957 ad /= bd; /* overflow/underflow impossible here */
2958 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002959 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002960 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002961 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002962 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002963 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002964 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002965 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002966 goto overflow;
2967 return PyFloat_FromDouble(ad);
2968
2969overflow:
2970 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002971 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002972 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002973
Tim Peters20dab9f2001-09-04 05:31:47 +00002974}
2975
2976static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002977long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002978{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002979 PyLongObject *mod;
2980
2981 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002982
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002983 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002984 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002985 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002986}
2987
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002988static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002989long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002990{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002991 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002992 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002993
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002994 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002995
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002996 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002997 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002998 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002999 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003000 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003001 PyTuple_SetItem(z, 0, (PyObject *) div);
3002 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003003 }
3004 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003005 Py_DECREF(div);
3006 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003007 }
3008 return z;
3009}
3010
Tim Peters47e52ee2004-08-30 02:44:38 +00003011/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003012static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003013long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003014{
Tim Peters47e52ee2004-08-30 02:44:38 +00003015 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3016 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003017
Tim Peters47e52ee2004-08-30 02:44:38 +00003018 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003019 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003020 PyLongObject *temp = NULL;
3021
3022 /* 5-ary values. If the exponent is large enough, table is
3023 * precomputed so that table[i] == a**i % c for i in range(32).
3024 */
3025 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3026 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3027
3028 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003029 CHECK_BINOP(v, w);
3030 a = (PyLongObject*)v; Py_INCREF(a);
3031 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003032 if (PyLong_Check(x)) {
3033 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003034 Py_INCREF(x);
3035 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003036 else if (x == Py_None)
3037 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003038 else {
3039 Py_DECREF(a);
3040 Py_DECREF(b);
3041 Py_INCREF(Py_NotImplemented);
3042 return Py_NotImplemented;
3043 }
Tim Peters4c483c42001-09-05 06:24:58 +00003044
Christian Heimes90aa7642007-12-19 02:45:37 +00003045 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003046 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003047 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003048 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003049 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003050 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003051 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003052 /* else return a float. This works because we know
3053 that this calls float_pow() which converts its
3054 arguments to double. */
3055 Py_DECREF(a);
3056 Py_DECREF(b);
3057 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003058 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003059 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003060
3061 if (c) {
3062 /* if modulus == 0:
3063 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003064 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003065 PyErr_SetString(PyExc_ValueError,
3066 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003067 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003068 }
3069
3070 /* if modulus < 0:
3071 negativeOutput = True
3072 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003073 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003074 negativeOutput = 1;
3075 temp = (PyLongObject *)_PyLong_Copy(c);
3076 if (temp == NULL)
3077 goto Error;
3078 Py_DECREF(c);
3079 c = temp;
3080 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003081 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003082 }
3083
3084 /* if modulus == 1:
3085 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003086 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003087 z = (PyLongObject *)PyLong_FromLong(0L);
3088 goto Done;
3089 }
3090
3091 /* if base < 0:
3092 base = base % modulus
3093 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003094 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003095 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003096 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003097 Py_DECREF(a);
3098 a = temp;
3099 temp = NULL;
3100 }
3101 }
3102
3103 /* At this point a, b, and c are guaranteed non-negative UNLESS
3104 c is NULL, in which case a may be negative. */
3105
3106 z = (PyLongObject *)PyLong_FromLong(1L);
3107 if (z == NULL)
3108 goto Error;
3109
3110 /* Perform a modular reduction, X = X % c, but leave X alone if c
3111 * is NULL.
3112 */
3113#define REDUCE(X) \
3114 if (c != NULL) { \
3115 if (l_divmod(X, c, NULL, &temp) < 0) \
3116 goto Error; \
3117 Py_XDECREF(X); \
3118 X = temp; \
3119 temp = NULL; \
3120 }
3121
3122 /* Multiply two values, then reduce the result:
3123 result = X*Y % c. If c is NULL, skip the mod. */
3124#define MULT(X, Y, result) \
3125{ \
3126 temp = (PyLongObject *)long_mul(X, Y); \
3127 if (temp == NULL) \
3128 goto Error; \
3129 Py_XDECREF(result); \
3130 result = temp; \
3131 temp = NULL; \
3132 REDUCE(result) \
3133}
3134
Christian Heimes90aa7642007-12-19 02:45:37 +00003135 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003136 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3137 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003138 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003139 digit bi = b->ob_digit[i];
3140
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003141 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003142 MULT(z, z, z)
3143 if (bi & j)
3144 MULT(z, a, z)
3145 }
3146 }
3147 }
3148 else {
3149 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3150 Py_INCREF(z); /* still holds 1L */
3151 table[0] = z;
3152 for (i = 1; i < 32; ++i)
3153 MULT(table[i-1], a, table[i])
3154
Christian Heimes90aa7642007-12-19 02:45:37 +00003155 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003156 const digit bi = b->ob_digit[i];
3157
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003158 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003159 const int index = (bi >> j) & 0x1f;
3160 for (k = 0; k < 5; ++k)
3161 MULT(z, z, z)
3162 if (index)
3163 MULT(z, table[index], z)
3164 }
3165 }
3166 }
3167
Christian Heimes90aa7642007-12-19 02:45:37 +00003168 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003169 temp = (PyLongObject *)long_sub(z, c);
3170 if (temp == NULL)
3171 goto Error;
3172 Py_DECREF(z);
3173 z = temp;
3174 temp = NULL;
3175 }
3176 goto Done;
3177
3178 Error:
3179 if (z != NULL) {
3180 Py_DECREF(z);
3181 z = NULL;
3182 }
3183 /* fall through */
3184 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003185 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003186 for (i = 0; i < 32; ++i)
3187 Py_XDECREF(table[i]);
3188 }
Tim Petersde7990b2005-07-17 23:45:23 +00003189 Py_DECREF(a);
3190 Py_DECREF(b);
3191 Py_XDECREF(c);
3192 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003193 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003194}
3195
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003196static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003197long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003198{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003199 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003200 PyLongObject *x;
3201 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003202 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003203 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003204 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003205 if (w == NULL)
3206 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003207 x = (PyLongObject *) long_add(v, w);
3208 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003209 if (x == NULL)
3210 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003211 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003212 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003213}
3214
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003215static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003216long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003217{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003218 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003219 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003220 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003221 z = (PyLongObject *)_PyLong_Copy(v);
3222 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003223 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003224 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003225}
3226
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003227static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003228long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003229{
Christian Heimes90aa7642007-12-19 02:45:37 +00003230 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003231 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003232 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003233 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003234}
3235
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003236static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003237long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003238{
Christian Heimes90aa7642007-12-19 02:45:37 +00003239 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003240}
3241
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003242static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003243long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003244{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003245 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003246 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003247 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003248 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003249
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003250 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003251
Christian Heimes90aa7642007-12-19 02:45:37 +00003252 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003253 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003254 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003255 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003256 if (a1 == NULL)
3257 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003258 a2 = (PyLongObject *) long_rshift(a1, b);
3259 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003260 if (a2 == NULL)
3261 goto rshift_error;
3262 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003263 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003264 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003265 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003266
Neil Schemenauerba872e22001-01-04 01:46:03 +00003267 shiftby = PyLong_AsLong((PyObject *)b);
3268 if (shiftby == -1L && PyErr_Occurred())
3269 goto rshift_error;
3270 if (shiftby < 0) {
3271 PyErr_SetString(PyExc_ValueError,
3272 "negative shift count");
3273 goto rshift_error;
3274 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003275 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003276 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003277 if (newsize <= 0)
3278 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003279 loshift = shiftby % PyLong_SHIFT;
3280 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003281 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003282 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003283 z = _PyLong_New(newsize);
3284 if (z == NULL)
3285 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003286 if (Py_SIZE(a) < 0)
3287 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003288 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3289 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3290 if (i+1 < newsize)
3291 z->ob_digit[i] |=
3292 (a->ob_digit[j+1] << hishift) & himask;
3293 }
3294 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003295 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003296rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003297 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003298
Guido van Rossumc6913e71991-11-19 20:26:46 +00003299}
3300
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003301static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003302long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003303{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003304 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003305 PyLongObject *a = (PyLongObject*)v;
3306 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003307 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003308 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003309 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003310 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003311
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003312 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003313
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003314 shiftby = PyLong_AsLong((PyObject *)b);
3315 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003316 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003317 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003318 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003319 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003320 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003321 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003322 PyErr_SetString(PyExc_ValueError,
3323 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003324 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003325 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003326 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3327 wordshift = (int)shiftby / PyLong_SHIFT;
3328 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003329
Christian Heimes90aa7642007-12-19 02:45:37 +00003330 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003331 newsize = oldsize + wordshift;
3332 if (remshift)
3333 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003334 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003335 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003336 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003337 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003338 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003339 for (i = 0; i < wordshift; i++)
3340 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003342 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003343 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003344 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3345 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003346 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003347 if (remshift)
3348 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003349 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003350 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003351 z = long_normalize(z);
3352lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003353 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003354}
3355
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003356
3357/* Bitwise and/xor/or operations */
3358
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003359static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003360long_bitwise(PyLongObject *a,
3361 int op, /* '&', '|', '^' */
3362 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003363{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003364 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003365 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003366 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003367 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003368 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003369 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003370 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003371
Christian Heimes90aa7642007-12-19 02:45:37 +00003372 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003373 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003374 if (a == NULL)
3375 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003376 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003377 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003378 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003379 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003380 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003381 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003382 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003383 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003384 if (b == NULL) {
3385 Py_DECREF(a);
3386 return NULL;
3387 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003388 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003389 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003390 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003391 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003392 maskb = 0;
3393 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003394
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003395 negz = 0;
3396 switch (op) {
3397 case '^':
3398 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003399 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003400 negz = -1;
3401 }
3402 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003403 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003404 if (maska && maskb) {
3405 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003406 maska ^= PyLong_MASK;
3407 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003408 negz = -1;
3409 }
3410 break;
3411 case '|':
3412 if (maska || maskb) {
3413 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003414 maska ^= PyLong_MASK;
3415 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003416 negz = -1;
3417 }
3418 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003419 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003420
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003421 /* JRH: The original logic here was to allocate the result value (z)
3422 as the longer of the two operands. However, there are some cases
3423 where the result is guaranteed to be shorter than that: AND of two
3424 positives, OR of two negatives: use the shorter number. AND with
3425 mixed signs: use the positive number. OR with mixed signs: use the
3426 negative number. After the transformations above, op will be '&'
3427 iff one of these cases applies, and mask will be non-0 for operands
3428 whose length should be ignored.
3429 */
3430
Christian Heimes90aa7642007-12-19 02:45:37 +00003431 size_a = Py_SIZE(a);
3432 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003433 size_z = op == '&'
3434 ? (maska
3435 ? size_b
3436 : (maskb ? size_a : MIN(size_a, size_b)))
3437 : MAX(size_a, size_b);
3438 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003439 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003440 Py_DECREF(a);
3441 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003442 return NULL;
3443 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003444
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003445 for (i = 0; i < size_z; ++i) {
3446 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3447 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3448 switch (op) {
3449 case '&': z->ob_digit[i] = diga & digb; break;
3450 case '|': z->ob_digit[i] = diga | digb; break;
3451 case '^': z->ob_digit[i] = diga ^ digb; break;
3452 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003453 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003454
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003455 Py_DECREF(a);
3456 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003457 z = long_normalize(z);
3458 if (negz == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003459 return (PyObject *) maybe_small_long(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003460 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003461 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003462 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003463}
3464
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003465static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003466long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003467{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003468 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003469 CHECK_BINOP(a, b);
3470 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003471 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003472}
3473
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003474static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003475long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003476{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003477 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003478 CHECK_BINOP(a, b);
3479 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003480 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003481}
3482
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003483static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003484long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003485{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003486 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003487 CHECK_BINOP(a, b);
3488 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003489 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003490}
3491
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003492static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003493long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003494{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003495 if (PyLong_CheckExact(v))
3496 Py_INCREF(v);
3497 else
3498 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003499 return v;
3500}
3501
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003502static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003503long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003504{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003505 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003506 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003507 if (result == -1.0 && PyErr_Occurred())
3508 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003509 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003510}
3511
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003512static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003513long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003514
Tim Peters6d6c1a32001-08-02 04:15:00 +00003515static PyObject *
3516long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3517{
3518 PyObject *x = NULL;
3519 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003520 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521
Guido van Rossumbef14172001-08-29 15:47:46 +00003522 if (type != &PyLong_Type)
3523 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003524 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003525 &x, &base))
3526 return NULL;
3527 if (x == NULL)
3528 return PyLong_FromLong(0L);
3529 if (base == -909)
3530 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003531 else if (PyUnicode_Check(x))
3532 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3533 PyUnicode_GET_SIZE(x),
3534 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003535 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003536 /* Since PyLong_FromString doesn't have a length parameter,
3537 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003538 char *string;
Christian Heimes90aa7642007-12-19 02:45:37 +00003539 int size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003540 if (PyByteArray_Check(x))
3541 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003542 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003543 string = PyBytes_AS_STRING(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003544 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003545 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003546 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003547 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003548 "invalid literal for int() with base %d: %R",
3549 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003550 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003551 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003552 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003553 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003554 else {
3555 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003556 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003557 return NULL;
3558 }
3559}
3560
Guido van Rossumbef14172001-08-29 15:47:46 +00003561/* Wimpy, slow approach to tp_new calls for subtypes of long:
3562 first create a regular long from whatever arguments we got,
3563 then allocate a subtype instance and initialize it from
3564 the regular long. The regular long is then thrown away.
3565*/
3566static PyObject *
3567long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3568{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003569 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003570 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003571
3572 assert(PyType_IsSubtype(type, &PyLong_Type));
3573 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3574 if (tmp == NULL)
3575 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003576 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003577 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003578 if (n < 0)
3579 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003580 newobj = (PyLongObject *)type->tp_alloc(type, n);
3581 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003582 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003583 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003584 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003585 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003586 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003587 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003588 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003589 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003590 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003591}
3592
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003593static PyObject *
3594long_getnewargs(PyLongObject *v)
3595{
3596 return Py_BuildValue("(N)", _PyLong_Copy(v));
3597}
3598
Guido van Rossumb43daf72007-08-01 18:08:08 +00003599static PyObject *
3600long_getN(PyLongObject *v, void *context) {
Christian Heimesc36625b2008-01-04 13:33:00 +00003601 return PyLong_FromLong((Py_intptr_t)context);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003602}
3603
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003604static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003605long__format__(PyObject *self, PyObject *args)
3606{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003607 PyObject *format_spec;
3608
3609 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3610 return NULL;
3611 return _PyLong_FormatAdvanced(self,
3612 PyUnicode_AS_UNICODE(format_spec),
3613 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003614}
3615
3616
3617static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003618long_round(PyObject *self, PyObject *args)
3619{
3620#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3621 int ndigits = UNDEF_NDIGITS;
3622 double x;
3623 PyObject *res;
3624
3625 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3626 return NULL;
3627
3628 if (ndigits == UNDEF_NDIGITS)
3629 return long_long(self);
3630
3631 /* If called with two args, defer to float.__round__(). */
3632 x = PyLong_AsDouble(self);
3633 if (x == -1.0 && PyErr_Occurred())
3634 return NULL;
3635 self = PyFloat_FromDouble(x);
3636 if (self == NULL)
3637 return NULL;
3638 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3639 Py_DECREF(self);
3640 return res;
3641#undef UNDEF_NDIGITS
3642}
3643
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003644static PyObject *
3645long_sizeof(PyLongObject *v)
3646{
3647 Py_ssize_t res;
3648
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003649 res = sizeof(PyVarObject) + abs(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003650 return PyLong_FromSsize_t(res);
3651}
3652
Christian Heimes53876d92008-04-19 00:31:39 +00003653#if 0
3654static PyObject *
3655long_is_finite(PyObject *v)
3656{
3657 Py_RETURN_TRUE;
3658}
3659#endif
3660
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003661static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003662 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3663 "Returns self, the complex conjugate of any int."},
Christian Heimes53876d92008-04-19 00:31:39 +00003664#if 0
3665 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3666 "Returns always True."},
3667#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003668 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3669 "Truncating an Integral returns itself."},
3670 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3671 "Flooring an Integral returns itself."},
3672 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3673 "Ceiling of an Integral returns itself."},
3674 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3675 "Rounding an Integral returns itself.\n"
3676 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003677 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003678 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003679 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
3680 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003681 {NULL, NULL} /* sentinel */
3682};
3683
Guido van Rossumb43daf72007-08-01 18:08:08 +00003684static PyGetSetDef long_getset[] = {
3685 {"real",
3686 (getter)long_long, (setter)NULL,
3687 "the real part of a complex number",
3688 NULL},
3689 {"imag",
3690 (getter)long_getN, (setter)NULL,
3691 "the imaginary part of a complex number",
3692 (void*)0},
3693 {"numerator",
3694 (getter)long_long, (setter)NULL,
3695 "the numerator of a rational number in lowest terms",
3696 NULL},
3697 {"denominator",
3698 (getter)long_getN, (setter)NULL,
3699 "the denominator of a rational number in lowest terms",
3700 (void*)1},
3701 {NULL} /* Sentinel */
3702};
3703
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003704PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003705"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003706\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003707Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003708point argument will be truncated towards zero (this does not include a\n\
3709string representation of a floating point number!) When converting a\n\
3710string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003711converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003712
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003713static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003714 (binaryfunc) long_add, /*nb_add*/
3715 (binaryfunc) long_sub, /*nb_subtract*/
3716 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003717 long_mod, /*nb_remainder*/
3718 long_divmod, /*nb_divmod*/
3719 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003720 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003721 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003722 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003723 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003724 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003725 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003726 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003727 long_and, /*nb_and*/
3728 long_xor, /*nb_xor*/
3729 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003730 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003731 long_long, /*nb_long*/
3732 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003733 0, /* nb_inplace_add */
3734 0, /* nb_inplace_subtract */
3735 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003736 0, /* nb_inplace_remainder */
3737 0, /* nb_inplace_power */
3738 0, /* nb_inplace_lshift */
3739 0, /* nb_inplace_rshift */
3740 0, /* nb_inplace_and */
3741 0, /* nb_inplace_xor */
3742 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003743 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003744 long_true_divide, /* nb_true_divide */
3745 0, /* nb_inplace_floor_divide */
3746 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003747 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003748};
3749
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003750PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003751 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003752 "int", /* tp_name */
3753 /* See _PyLong_New for why this isn't
3754 sizeof(PyLongObject) - sizeof(digit) */
3755 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003757 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003758 0, /* tp_print */
3759 0, /* tp_getattr */
3760 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003761 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003762 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003763 &long_as_number, /* tp_as_number */
3764 0, /* tp_as_sequence */
3765 0, /* tp_as_mapping */
3766 (hashfunc)long_hash, /* tp_hash */
3767 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003768 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003769 PyObject_GenericGetAttr, /* tp_getattro */
3770 0, /* tp_setattro */
3771 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003772 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3773 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003774 long_doc, /* tp_doc */
3775 0, /* tp_traverse */
3776 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003777 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003778 0, /* tp_weaklistoffset */
3779 0, /* tp_iter */
3780 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003781 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003783 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784 0, /* tp_base */
3785 0, /* tp_dict */
3786 0, /* tp_descr_get */
3787 0, /* tp_descr_set */
3788 0, /* tp_dictoffset */
3789 0, /* tp_init */
3790 0, /* tp_alloc */
3791 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003792 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003793};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003794
3795int
3796_PyLong_Init(void)
3797{
3798#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003799 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003800 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003801
3802 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
3803 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
3804 if (Py_TYPE(v) == &PyLong_Type) {
3805 /* The element is already initialized, most likely
3806 * the Python interpreter was initialized before.
3807 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00003808 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003809 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003810
Christian Heimes48aa4b12008-02-01 16:56:30 +00003811 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
3812 _Py_NewReference(op);
3813 /* _Py_NewReference sets the ref count to 1 but
3814 * the ref count might be larger. Set the refcnt
3815 * to the original refcnt + 1 */
3816 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003817 assert(Py_SIZE(op) == size);
3818 assert(v->ob_digit[0] == abs(ival));
3819 }
3820 else {
3821 PyObject_INIT(v, &PyLong_Type);
3822 }
3823 Py_SIZE(v) = size;
3824 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003825 }
3826#endif
3827 return 1;
3828}
3829
3830void
3831PyLong_Fini(void)
3832{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003833 /* Integers are currently statically allocated. Py_DECREF is not
3834 needed, but Python must forget about the reference or multiple
3835 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003836#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003837 int i;
3838 PyLongObject *v = small_ints;
3839 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
3840 _Py_DEC_REFTOTAL;
3841 _Py_ForgetReference((PyObject*)v);
3842 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003843#endif
3844}