blob: a932df7edaaeada4df016a42b7249f83a3b0e549 [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) { \
Mark Dickinson50b2b6e2008-12-05 17:14:29 +000047 return get_small_int((int)ival); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000048 } 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;
Mark Dickinsond4624c32009-01-24 15:02:35 +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) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000186 /* negate: can't write this as abs_ival = -ival since that
187 invokes undefined behaviour when ival is LONG_MIN */
188 abs_ival = 0U-(unsigned long)ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000189 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000190 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000191 else {
192 abs_ival = (unsigned long)ival;
193 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000194
Mark Dickinsond4624c32009-01-24 15:02:35 +0000195 /* Fast path for single-digit ints */
196 if (!(abs_ival >> PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000197 v = _PyLong_New(1);
198 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000199 Py_SIZE(v) = sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000200 v->ob_digit[0] = Py_SAFE_DOWNCAST(
201 abs_ival, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000202 }
203 return (PyObject*)v;
204 }
205
206 /* 2 digits */
Mark Dickinsond4624c32009-01-24 15:02:35 +0000207 if (!(abs_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;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000211 v->ob_digit[0] = Py_SAFE_DOWNCAST(
212 abs_ival & PyLong_MASK, unsigned long, digit);
213 v->ob_digit[1] = Py_SAFE_DOWNCAST(
214 abs_ival >> PyLong_SHIFT, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000215 }
216 return (PyObject*)v;
217 }
218
219 /* Larger numbers: loop to determine number of digits */
Christian Heimesdae2a892008-04-19 00:55:37 +0000220 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000221 while (t) {
222 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000223 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000224 }
225 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000226 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000227 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000228 Py_SIZE(v) = ndigits*sign;
Christian Heimesdae2a892008-04-19 00:55:37 +0000229 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000230 while (t) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000231 *p++ = Py_SAFE_DOWNCAST(
232 t & PyLong_MASK, unsigned long, digit);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000233 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000234 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000235 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000236 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000237}
238
Guido van Rossum53756b11997-01-03 17:14:46 +0000239/* Create a new long int object from a C unsigned long int */
240
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000241PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000242PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000243{
Tim Petersce9de2f2001-06-14 04:56:19 +0000244 PyLongObject *v;
245 unsigned long t;
246 int ndigits = 0;
247
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000248 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000249 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000250 /* Count the number of Python digits. */
251 t = (unsigned long)ival;
252 while (t) {
253 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000254 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000255 }
256 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000257 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000258 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000259 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000260 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000261 *p++ = (digit)(ival & PyLong_MASK);
262 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000263 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000264 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000265 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000266}
267
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000268/* Create a new long int object from a C double */
269
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000270PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000272{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000273 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000274 double frac;
275 int i, ndig, expo, neg;
276 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000277 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000278 PyErr_SetString(PyExc_OverflowError,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000279 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000280 return NULL;
281 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000282 if (Py_IS_NAN(dval)) {
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000283 PyErr_SetString(PyExc_ValueError,
284 "cannot convert float NaN to integer");
Christian Heimes386cd1e2008-01-15 02:01:20 +0000285 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000286 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000287 if (dval < 0.0) {
288 neg = 1;
289 dval = -dval;
290 }
291 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
292 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000293 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000294 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000295 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000296 if (v == NULL)
297 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000298 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000299 for (i = ndig; --i >= 0; ) {
300 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000301 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000302 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000303 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000304 }
305 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000306 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000308}
309
Thomas Wouters89f507f2006-12-13 04:49:30 +0000310/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
311 * anything about what happens when a signed integer operation overflows,
312 * and some compilers think they're doing you a favor by being "clever"
313 * then. The bit pattern for the largest postive signed long is
314 * (unsigned long)LONG_MAX, and for the smallest negative signed long
315 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
316 * However, some other compilers warn about applying unary minus to an
317 * unsigned operand. Hence the weird "0-".
318 */
319#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
320#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
321
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000322/* Get a C long int from a long int object.
323 Returns -1 and sets an error condition if overflow occurs. */
324
325long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000326PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000327{
Guido van Rossumf7531811998-05-26 14:33:37 +0000328 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000330 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000331 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000332 Py_ssize_t i;
333 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000334 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000335
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000336 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000337 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000339 return -1;
340 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000341
342 if (!PyLong_Check(vv)) {
343 PyNumberMethods *nb;
344 if ((nb = vv->ob_type->tp_as_number) == NULL ||
345 nb->nb_int == NULL) {
346 PyErr_SetString(PyExc_TypeError, "an integer is required");
347 return -1;
348 }
349 vv = (*nb->nb_int) (vv);
350 if (vv == NULL)
351 return -1;
352 do_decref = 1;
353 if (!PyLong_Check(vv)) {
354 Py_DECREF(vv);
355 PyErr_SetString(PyExc_TypeError,
356 "nb_int should return int object");
357 return -1;
358 }
359 }
360
Georg Brandl61c31b02007-02-26 14:46:30 +0000361 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000362 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000363 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000364
Georg Brandl61c31b02007-02-26 14:46:30 +0000365 switch (i) {
366 case -1:
367 res = -v->ob_digit[0];
368 break;
369 case 0:
370 res = 0;
371 break;
372 case 1:
373 res = v->ob_digit[0];
374 break;
375 default:
376 sign = 1;
377 x = 0;
378 if (i < 0) {
379 sign = -1;
380 i = -(i);
381 }
382 while (--i >= 0) {
383 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000384 x = (x << PyLong_SHIFT) + v->ob_digit[i];
385 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000386 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000387 goto exit;
388 }
389 }
390 /* Haven't lost any bits, but casting to long requires extra care
391 * (see comment above).
392 */
393 if (x <= (unsigned long)LONG_MAX) {
394 res = (long)x * sign;
395 }
396 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
397 res = LONG_MIN;
398 }
399 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000400 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000401 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000402 }
403 }
404 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000405 if (do_decref) {
406 Py_DECREF(vv);
407 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000408 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000409}
410
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000411long
412PyLong_AsLong(PyObject *obj)
413{
414 int overflow;
415 long result = PyLong_AsLongAndOverflow(obj, &overflow);
416 if (overflow) {
417 /* XXX: could be cute and give a different
418 message for overflow == -1 */
419 PyErr_SetString(PyExc_OverflowError,
420 "Python int too large to convert to C long");
421 }
422 return result;
423}
424
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000425/* Get a Py_ssize_t from a long int object.
426 Returns -1 and sets an error condition if overflow occurs. */
427
428Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000429PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000430 register PyLongObject *v;
431 size_t x, prev;
432 Py_ssize_t i;
433 int sign;
434
435 if (vv == NULL || !PyLong_Check(vv)) {
436 PyErr_BadInternalCall();
437 return -1;
438 }
439 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000440 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000441 switch (i) {
442 case -1: return -v->ob_digit[0];
443 case 0: return 0;
444 case 1: return v->ob_digit[0];
445 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000446 sign = 1;
447 x = 0;
448 if (i < 0) {
449 sign = -1;
450 i = -(i);
451 }
452 while (--i >= 0) {
453 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000454 x = (x << PyLong_SHIFT) + v->ob_digit[i];
455 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000456 goto overflow;
457 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000458 /* Haven't lost any bits, but casting to a signed type requires
459 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000460 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461 if (x <= (size_t)PY_SSIZE_T_MAX) {
462 return (Py_ssize_t)x * sign;
463 }
464 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
465 return PY_SSIZE_T_MIN;
466 }
467 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468
469 overflow:
470 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000471 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000472 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000473}
474
Guido van Rossumd8c80482002-08-13 00:24:58 +0000475/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000476 Returns -1 and sets an error condition if overflow occurs. */
477
478unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000479PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000480{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000482 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000483 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000484
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485 if (vv == NULL || !PyLong_Check(vv)) {
486 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000487 return (unsigned long) -1;
488 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000490 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000491 x = 0;
492 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000494 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000495 return (unsigned long) -1;
496 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000497 switch (i) {
498 case 0: return 0;
499 case 1: return v->ob_digit[0];
500 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000501 while (--i >= 0) {
502 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000503 x = (x << PyLong_SHIFT) + v->ob_digit[i];
504 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000505 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000506 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000507 return (unsigned long) -1;
508 }
509 }
510 return x;
511}
512
513/* Get a C unsigned long int from a long int object.
514 Returns -1 and sets an error condition if overflow occurs. */
515
516size_t
517PyLong_AsSize_t(PyObject *vv)
518{
519 register PyLongObject *v;
520 size_t x, prev;
521 Py_ssize_t i;
522
523 if (vv == NULL || !PyLong_Check(vv)) {
524 PyErr_BadInternalCall();
525 return (unsigned long) -1;
526 }
527 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000528 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000529 x = 0;
530 if (i < 0) {
531 PyErr_SetString(PyExc_OverflowError,
532 "can't convert negative value to size_t");
533 return (size_t) -1;
534 }
535 switch (i) {
536 case 0: return 0;
537 case 1: return v->ob_digit[0];
538 }
539 while (--i >= 0) {
540 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000541 x = (x << PyLong_SHIFT) + v->ob_digit[i];
542 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000543 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000544 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000545 return (unsigned long) -1;
546 }
547 }
548 return x;
549}
550
Thomas Hellera4ea6032003-04-17 18:55:45 +0000551/* Get a C unsigned long int from a long int object, ignoring the high bits.
552 Returns -1 and sets an error condition if an error occurs. */
553
Guido van Rossumddefaf32007-01-14 03:31:43 +0000554static unsigned long
555_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000556{
557 register PyLongObject *v;
558 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000559 Py_ssize_t i;
560 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000561
562 if (vv == NULL || !PyLong_Check(vv)) {
563 PyErr_BadInternalCall();
564 return (unsigned long) -1;
565 }
566 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000567 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000568 switch (i) {
569 case 0: return 0;
570 case 1: return v->ob_digit[0];
571 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000572 sign = 1;
573 x = 0;
574 if (i < 0) {
575 sign = -1;
576 i = -i;
577 }
578 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000579 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000580 }
581 return x * sign;
582}
583
Guido van Rossumddefaf32007-01-14 03:31:43 +0000584unsigned long
585PyLong_AsUnsignedLongMask(register PyObject *op)
586{
587 PyNumberMethods *nb;
588 PyLongObject *lo;
589 unsigned long val;
590
591 if (op && PyLong_Check(op))
592 return _PyLong_AsUnsignedLongMask(op);
593
594 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
595 nb->nb_int == NULL) {
596 PyErr_SetString(PyExc_TypeError, "an integer is required");
597 return (unsigned long)-1;
598 }
599
600 lo = (PyLongObject*) (*nb->nb_int) (op);
601 if (lo == NULL)
602 return (unsigned long)-1;
603 if (PyLong_Check(lo)) {
604 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
605 Py_DECREF(lo);
606 if (PyErr_Occurred())
607 return (unsigned long)-1;
608 return val;
609 }
610 else
611 {
612 Py_DECREF(lo);
613 PyErr_SetString(PyExc_TypeError,
614 "nb_int should return int object");
615 return (unsigned long)-1;
616 }
617}
618
Tim Peters5b8132f2003-01-31 15:52:05 +0000619int
620_PyLong_Sign(PyObject *vv)
621{
622 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000623
624 assert(v != NULL);
625 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000626
Christian Heimes90aa7642007-12-19 02:45:37 +0000627 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000628}
629
Tim Petersbaefd9e2003-01-28 20:37:45 +0000630size_t
631_PyLong_NumBits(PyObject *vv)
632{
633 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000634 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000635 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000636
637 assert(v != NULL);
638 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000639 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000640 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
641 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000642 digit msd = v->ob_digit[ndigits - 1];
643
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000644 result = (ndigits - 1) * PyLong_SHIFT;
645 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000646 goto Overflow;
647 do {
648 ++result;
649 if (result == 0)
650 goto Overflow;
651 msd >>= 1;
652 } while (msd);
653 }
654 return result;
655
656Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000657 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000658 "to express in a platform size_t");
659 return (size_t)-1;
660}
661
Tim Peters2a9b3672001-06-11 21:23:58 +0000662PyObject *
663_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
664 int little_endian, int is_signed)
665{
666 const unsigned char* pstartbyte;/* LSB of bytes */
667 int incr; /* direction to move pstartbyte */
668 const unsigned char* pendbyte; /* MSB of bytes */
669 size_t numsignificantbytes; /* number of bytes that matter */
670 size_t ndigits; /* number of Python long digits */
671 PyLongObject* v; /* result */
672 int idigit = 0; /* next free index in v->ob_digit */
673
674 if (n == 0)
675 return PyLong_FromLong(0L);
676
677 if (little_endian) {
678 pstartbyte = bytes;
679 pendbyte = bytes + n - 1;
680 incr = 1;
681 }
682 else {
683 pstartbyte = bytes + n - 1;
684 pendbyte = bytes;
685 incr = -1;
686 }
687
688 if (is_signed)
689 is_signed = *pendbyte >= 0x80;
690
691 /* Compute numsignificantbytes. This consists of finding the most
692 significant byte. Leading 0 bytes are insignficant if the number
693 is positive, and leading 0xff bytes if negative. */
694 {
695 size_t i;
696 const unsigned char* p = pendbyte;
697 const int pincr = -incr; /* search MSB to LSB */
698 const unsigned char insignficant = is_signed ? 0xff : 0x00;
699
700 for (i = 0; i < n; ++i, p += pincr) {
701 if (*p != insignficant)
702 break;
703 }
704 numsignificantbytes = n - i;
705 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
706 actually has 2 significant bytes. OTOH, 0xff0001 ==
707 -0x00ffff, so we wouldn't *need* to bump it there; but we
708 do for 0xffff = -0x0001. To be safe without bothering to
709 check every case, bump it regardless. */
710 if (is_signed && numsignificantbytes < n)
711 ++numsignificantbytes;
712 }
713
714 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000715 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000716 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000717 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000718 if (ndigits > (size_t)INT_MAX)
719 return PyErr_NoMemory();
720 v = _PyLong_New((int)ndigits);
721 if (v == NULL)
722 return NULL;
723
724 /* Copy the bits over. The tricky parts are computing 2's-comp on
725 the fly for signed numbers, and dealing with the mismatch between
726 8-bit bytes and (probably) 15-bit Python digits.*/
727 {
728 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000729 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000730 twodigits accum = 0; /* sliding register */
731 unsigned int accumbits = 0; /* number of bits in accum */
732 const unsigned char* p = pstartbyte;
733
734 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000735 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000736 /* Compute correction for 2's comp, if needed. */
737 if (is_signed) {
738 thisbyte = (0xff ^ thisbyte) + carry;
739 carry = thisbyte >> 8;
740 thisbyte &= 0xff;
741 }
742 /* Because we're going LSB to MSB, thisbyte is
743 more significant than what's already in accum,
744 so needs to be prepended to accum. */
745 accum |= thisbyte << accumbits;
746 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000747 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000748 /* There's enough to fill a Python digit. */
749 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000750 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000751 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000752 accum >>= PyLong_SHIFT;
753 accumbits -= PyLong_SHIFT;
754 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000755 }
756 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000757 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000758 if (accumbits) {
759 assert(idigit < (int)ndigits);
760 v->ob_digit[idigit] = (digit)accum;
761 ++idigit;
762 }
763 }
764
Christian Heimes90aa7642007-12-19 02:45:37 +0000765 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000766 return (PyObject *)long_normalize(v);
767}
768
769int
770_PyLong_AsByteArray(PyLongObject* v,
771 unsigned char* bytes, size_t n,
772 int little_endian, int is_signed)
773{
774 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000775 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000776 twodigits accum; /* sliding register */
777 unsigned int accumbits; /* # bits in accum */
778 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
779 twodigits carry; /* for computing 2's-comp */
780 size_t j; /* # bytes filled */
781 unsigned char* p; /* pointer to next byte in bytes */
782 int pincr; /* direction to move p */
783
784 assert(v != NULL && PyLong_Check(v));
785
Christian Heimes90aa7642007-12-19 02:45:37 +0000786 if (Py_SIZE(v) < 0) {
787 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000788 if (!is_signed) {
789 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000790 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000791 return -1;
792 }
793 do_twos_comp = 1;
794 }
795 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000796 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000797 do_twos_comp = 0;
798 }
799
800 if (little_endian) {
801 p = bytes;
802 pincr = 1;
803 }
804 else {
805 p = bytes + n - 1;
806 pincr = -1;
807 }
808
Tim Peters898cf852001-06-13 20:50:08 +0000809 /* Copy over all the Python digits.
810 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000811 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000812 normalized. */
813 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000814 j = 0;
815 accum = 0;
816 accumbits = 0;
817 carry = do_twos_comp ? 1 : 0;
818 for (i = 0; i < ndigits; ++i) {
819 twodigits thisdigit = v->ob_digit[i];
820 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000821 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
822 carry = thisdigit >> PyLong_SHIFT;
823 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000824 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000825 /* Because we're going LSB to MSB, thisdigit is more
826 significant than what's already in accum, so needs to be
827 prepended to accum. */
828 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000829 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000830
Tim Petersede05092001-06-14 08:53:38 +0000831 /* The most-significant digit may be (probably is) at least
832 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000833 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000834 /* Count # of sign bits -- they needn't be stored,
835 * although for signed conversion we need later to
836 * make sure at least one sign bit gets stored.
837 * First shift conceptual sign bit to real sign bit.
838 */
839 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000840 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000841 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000842 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000843 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000844 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000845 }
Tim Petersede05092001-06-14 08:53:38 +0000846 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000847 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000848
Tim Peters2a9b3672001-06-11 21:23:58 +0000849 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000850 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000851 if (j >= n)
852 goto Overflow;
853 ++j;
854 *p = (unsigned char)(accum & 0xff);
855 p += pincr;
856 accumbits -= 8;
857 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000858 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000859 }
860
861 /* Store the straggler (if any). */
862 assert(accumbits < 8);
863 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000864 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000865 if (j >= n)
866 goto Overflow;
867 ++j;
868 if (do_twos_comp) {
869 /* Fill leading bits of the byte with sign bits
870 (appropriately pretending that the long had an
871 infinite supply of sign bits). */
872 accum |= (~(twodigits)0) << accumbits;
873 }
874 *p = (unsigned char)(accum & 0xff);
875 p += pincr;
876 }
Tim Peters05607ad2001-06-13 21:01:27 +0000877 else if (j == n && n > 0 && is_signed) {
878 /* The main loop filled the byte array exactly, so the code
879 just above didn't get to ensure there's a sign bit, and the
880 loop below wouldn't add one either. Make sure a sign bit
881 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000882 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000883 int sign_bit_set = msb >= 0x80;
884 assert(accumbits == 0);
885 if (sign_bit_set == do_twos_comp)
886 return 0;
887 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000888 goto Overflow;
889 }
Tim Peters05607ad2001-06-13 21:01:27 +0000890
891 /* Fill remaining bytes with copies of the sign bit. */
892 {
893 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
894 for ( ; j < n; ++j, p += pincr)
895 *p = signbyte;
896 }
897
Tim Peters2a9b3672001-06-11 21:23:58 +0000898 return 0;
899
900Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000901 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000902 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000903
Tim Peters2a9b3672001-06-11 21:23:58 +0000904}
905
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000906double
907_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
908{
909/* NBITS_WANTED should be > the number of bits in a double's precision,
910 but small enough so that 2**NBITS_WANTED is within the normal double
911 range. nbitsneeded is set to 1 less than that because the most-significant
912 Python digit contains at least 1 significant bit, but we don't want to
913 bother counting them (catering to the worst case cheaply).
914
915 57 is one more than VAX-D double precision; I (Tim) don't know of a double
916 format with more precision than that; it's 1 larger so that we add in at
917 least one round bit to stand in for the ignored least-significant bits.
918*/
919#define NBITS_WANTED 57
920 PyLongObject *v;
921 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000922 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000923 Py_ssize_t i;
924 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000925 int nbitsneeded;
926
927 if (vv == NULL || !PyLong_Check(vv)) {
928 PyErr_BadInternalCall();
929 return -1;
930 }
931 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000932 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000933 sign = 1;
934 if (i < 0) {
935 sign = -1;
936 i = -(i);
937 }
938 else if (i == 0) {
939 *exponent = 0;
940 return 0.0;
941 }
942 --i;
943 x = (double)v->ob_digit[i];
944 nbitsneeded = NBITS_WANTED - 1;
945 /* Invariant: i Python digits remain unaccounted for. */
946 while (i > 0 && nbitsneeded > 0) {
947 --i;
948 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000949 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000950 }
951 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000952 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000953 *exponent = i;
954 assert(x > 0.0);
955 return x * sign;
956#undef NBITS_WANTED
957}
958
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000959/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000960
961double
Tim Peters9f688bf2000-07-07 15:53:28 +0000962PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000963{
Thomas Wouters553489a2006-02-01 21:32:04 +0000964 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000965 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000966
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000967 if (vv == NULL || !PyLong_Check(vv)) {
968 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000969 return -1;
970 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000971 x = _PyLong_AsScaledDouble(vv, &e);
972 if (x == -1.0 && PyErr_Occurred())
973 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000974 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
975 set correctly after a successful _PyLong_AsScaledDouble() call */
976 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000977 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000978 goto overflow;
979 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000980 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000981 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000982 goto overflow;
983 return x;
984
985overflow:
986 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000987 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000988 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000989}
990
Guido van Rossum78694d91998-09-18 14:14:13 +0000991/* Create a new long (or int) object from a C pointer */
992
993PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000994PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000995{
Tim Peters70128a12001-06-16 08:48:40 +0000996#ifndef HAVE_LONG_LONG
997# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
998#endif
999#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001000# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001001#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +00001002 /* special-case null pointer */
1003 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +00001004 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001005 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +00001006
Guido van Rossum78694d91998-09-18 14:14:13 +00001007}
1008
1009/* Get a C pointer from a long object (or an int object in some cases) */
1010
1011void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001012PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001013{
1014 /* This function will allow int or long objects. If vv is neither,
1015 then the PyLong_AsLong*() functions will raise the exception:
1016 PyExc_SystemError, "bad argument to internal function"
1017 */
Tim Peters70128a12001-06-16 08:48:40 +00001018#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001019 long x;
1020
Guido van Rossumddefaf32007-01-14 03:31:43 +00001021 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001022 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001023 else
1024 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001025#else
Tim Peters70128a12001-06-16 08:48:40 +00001026
1027#ifndef HAVE_LONG_LONG
1028# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1029#endif
1030#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001031# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001032#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001033 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001034
Guido van Rossumddefaf32007-01-14 03:31:43 +00001035 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001036 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001037 else
1038 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001039
1040#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001041
1042 if (x == -1 && PyErr_Occurred())
1043 return NULL;
1044 return (void *)x;
1045}
1046
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001047#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001048
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001049/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001050 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001051 */
1052
Tim Peterscf37dfc2001-06-14 18:42:50 +00001053#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001054
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001055/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001056
1057PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001058PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001059{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001060 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +00001061 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001062 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1063 int ndigits = 0;
1064 int negative = 0;
1065
Guido van Rossumddefaf32007-01-14 03:31:43 +00001066 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001067 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +00001068 /* avoid signed overflow on negation; see comments
1069 in PyLong_FromLong above. */
1070 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071 negative = 1;
1072 }
Christian Heimesdae2a892008-04-19 00:55:37 +00001073 else {
1074 abs_ival = (unsigned PY_LONG_LONG)ival;
1075 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001076
1077 /* Count the number of Python digits.
1078 We used to pick 5 ("big enough for anything"), but that's a
1079 waste of time and space given that 5*15 = 75 bits are rarely
1080 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001081 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001082 while (t) {
1083 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001084 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001085 }
1086 v = _PyLong_New(ndigits);
1087 if (v != NULL) {
1088 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001089 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001090 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001092 *p++ = (digit)(t & PyLong_MASK);
1093 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001094 }
1095 }
1096 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001097}
1098
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001099/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001100
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001101PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001102PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001103{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001104 PyLongObject *v;
1105 unsigned PY_LONG_LONG t;
1106 int ndigits = 0;
1107
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001108 if (ival < PyLong_BASE)
Mark Dickinson50b2b6e2008-12-05 17:14:29 +00001109 return PyLong_FromLong((long)ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001110 /* Count the number of Python digits. */
1111 t = (unsigned PY_LONG_LONG)ival;
1112 while (t) {
1113 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001114 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001115 }
1116 v = _PyLong_New(ndigits);
1117 if (v != NULL) {
1118 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001119 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001121 *p++ = (digit)(ival & PyLong_MASK);
1122 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123 }
1124 }
1125 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001126}
1127
Martin v. Löwis18e16552006-02-15 17:27:45 +00001128/* Create a new long int object from a C Py_ssize_t. */
1129
1130PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001131PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001132{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001133 PyLongObject *v;
1134 size_t abs_ival;
1135 size_t t; /* unsigned so >> doesn't propagate sign bit */
1136 int ndigits = 0;
1137 int negative = 0;
1138
1139 CHECK_SMALL_INT(ival);
1140 if (ival < 0) {
1141 /* avoid signed overflow when ival = SIZE_T_MIN */
1142 abs_ival = (size_t)(-1-ival)+1;
1143 negative = 1;
1144 }
1145 else {
1146 abs_ival = (size_t)ival;
1147 }
1148
1149 /* Count the number of Python digits. */
1150 t = abs_ival;
1151 while (t) {
1152 ++ndigits;
1153 t >>= PyLong_SHIFT;
1154 }
1155 v = _PyLong_New(ndigits);
1156 if (v != NULL) {
1157 digit *p = v->ob_digit;
1158 Py_SIZE(v) = negative ? -ndigits : ndigits;
1159 t = abs_ival;
1160 while (t) {
1161 *p++ = (digit)(t & PyLong_MASK);
1162 t >>= PyLong_SHIFT;
1163 }
1164 }
1165 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001166}
1167
1168/* Create a new long int object from a C size_t. */
1169
1170PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001171PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001172{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001173 PyLongObject *v;
1174 size_t t;
1175 int ndigits = 0;
1176
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001177 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001178 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001179 /* Count the number of Python digits. */
1180 t = ival;
1181 while (t) {
1182 ++ndigits;
1183 t >>= PyLong_SHIFT;
1184 }
1185 v = _PyLong_New(ndigits);
1186 if (v != NULL) {
1187 digit *p = v->ob_digit;
1188 Py_SIZE(v) = ndigits;
1189 while (ival) {
1190 *p++ = (digit)(ival & PyLong_MASK);
1191 ival >>= PyLong_SHIFT;
1192 }
1193 }
1194 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001195}
1196
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001197/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001198 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001199
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001200PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001201PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001202{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001203 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001204 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001205 int one = 1;
1206 int res;
1207
Tim Petersd38b1c72001-09-30 05:09:37 +00001208 if (vv == NULL) {
1209 PyErr_BadInternalCall();
1210 return -1;
1211 }
1212 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001213 PyNumberMethods *nb;
1214 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001215 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1216 nb->nb_int == NULL) {
1217 PyErr_SetString(PyExc_TypeError, "an integer is required");
1218 return -1;
1219 }
1220 io = (*nb->nb_int) (vv);
1221 if (io == NULL)
1222 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001223 if (PyLong_Check(io)) {
1224 bytes = PyLong_AsLongLong(io);
1225 Py_DECREF(io);
1226 return bytes;
1227 }
1228 Py_DECREF(io);
1229 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001230 return -1;
1231 }
1232
Guido van Rossumddefaf32007-01-14 03:31:43 +00001233 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001234 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001235 case -1: return -v->ob_digit[0];
1236 case 0: return 0;
1237 case 1: return v->ob_digit[0];
1238 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001239 res = _PyLong_AsByteArray(
1240 (PyLongObject *)vv, (unsigned char *)&bytes,
1241 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001242
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001243 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001244 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001245 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001246 else
1247 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001248}
1249
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001250/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001251 Return -1 and set an error if overflow occurs. */
1252
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001253unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001254PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001255{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001256 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001257 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001258 int one = 1;
1259 int res;
1260
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001261 if (vv == NULL || !PyLong_Check(vv)) {
1262 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001263 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001264 }
1265
Guido van Rossumddefaf32007-01-14 03:31:43 +00001266 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001267 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001268 case 0: return 0;
1269 case 1: return v->ob_digit[0];
1270 }
1271
Tim Petersd1a7da62001-06-13 00:35:57 +00001272 res = _PyLong_AsByteArray(
1273 (PyLongObject *)vv, (unsigned char *)&bytes,
1274 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001275
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001276 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001277 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001278 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001279 else
1280 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001281}
Tim Petersd1a7da62001-06-13 00:35:57 +00001282
Thomas Hellera4ea6032003-04-17 18:55:45 +00001283/* Get a C unsigned long int from a long int object, ignoring the high bits.
1284 Returns -1 and sets an error condition if an error occurs. */
1285
Guido van Rossumddefaf32007-01-14 03:31:43 +00001286static unsigned PY_LONG_LONG
1287_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001288{
1289 register PyLongObject *v;
1290 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001291 Py_ssize_t i;
1292 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001293
1294 if (vv == NULL || !PyLong_Check(vv)) {
1295 PyErr_BadInternalCall();
1296 return (unsigned long) -1;
1297 }
1298 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001299 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001300 case 0: return 0;
1301 case 1: return v->ob_digit[0];
1302 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001303 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001304 sign = 1;
1305 x = 0;
1306 if (i < 0) {
1307 sign = -1;
1308 i = -i;
1309 }
1310 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001311 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001312 }
1313 return x * sign;
1314}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001315
1316unsigned PY_LONG_LONG
1317PyLong_AsUnsignedLongLongMask(register PyObject *op)
1318{
1319 PyNumberMethods *nb;
1320 PyLongObject *lo;
1321 unsigned PY_LONG_LONG val;
1322
1323 if (op && PyLong_Check(op))
1324 return _PyLong_AsUnsignedLongLongMask(op);
1325
1326 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1327 nb->nb_int == NULL) {
1328 PyErr_SetString(PyExc_TypeError, "an integer is required");
1329 return (unsigned PY_LONG_LONG)-1;
1330 }
1331
1332 lo = (PyLongObject*) (*nb->nb_int) (op);
1333 if (lo == NULL)
1334 return (unsigned PY_LONG_LONG)-1;
1335 if (PyLong_Check(lo)) {
1336 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1337 Py_DECREF(lo);
1338 if (PyErr_Occurred())
1339 return (unsigned PY_LONG_LONG)-1;
1340 return val;
1341 }
1342 else
1343 {
1344 Py_DECREF(lo);
1345 PyErr_SetString(PyExc_TypeError,
1346 "nb_int should return int object");
1347 return (unsigned PY_LONG_LONG)-1;
1348 }
1349}
Tim Petersd1a7da62001-06-13 00:35:57 +00001350#undef IS_LITTLE_ENDIAN
1351
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001352#endif /* HAVE_LONG_LONG */
1353
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001354#define CHECK_BINOP(v,w) \
1355 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001356 Py_INCREF(Py_NotImplemented); \
1357 return Py_NotImplemented; \
1358 }
1359
Tim Peters877a2122002-08-12 05:09:36 +00001360/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1361 * is modified in place, by adding y to it. Carries are propagated as far as
1362 * x[m-1], and the remaining carry (0 or 1) is returned.
1363 */
1364static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001365v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001366{
1367 int i;
1368 digit carry = 0;
1369
1370 assert(m >= n);
1371 for (i = 0; i < n; ++i) {
1372 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001373 x[i] = carry & PyLong_MASK;
1374 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001375 assert((carry & 1) == carry);
1376 }
1377 for (; carry && i < m; ++i) {
1378 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001379 x[i] = carry & PyLong_MASK;
1380 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001381 assert((carry & 1) == carry);
1382 }
1383 return carry;
1384}
1385
1386/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1387 * is modified in place, by subtracting y from it. Borrows are propagated as
1388 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1389 */
1390static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001391v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001392{
1393 int i;
1394 digit borrow = 0;
1395
1396 assert(m >= n);
1397 for (i = 0; i < n; ++i) {
1398 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001399 x[i] = borrow & PyLong_MASK;
1400 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001401 borrow &= 1; /* keep only 1 sign bit */
1402 }
1403 for (; borrow && i < m; ++i) {
1404 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001405 x[i] = borrow & PyLong_MASK;
1406 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001407 borrow &= 1;
1408 }
1409 return borrow;
1410}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001411
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001412/* Multiply by a single digit, ignoring the sign. */
1413
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001414static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001415mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001416{
1417 return muladd1(a, n, (digit)0);
1418}
1419
1420/* Multiply by a single digit and add a single digit, ignoring the sign. */
1421
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001422static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001423muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001424{
Christian Heimes90aa7642007-12-19 02:45:37 +00001425 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001426 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001427 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001428 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001429
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001430 if (z == NULL)
1431 return NULL;
1432 for (i = 0; i < size_a; ++i) {
1433 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001434 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1435 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001436 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001437 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001438 return long_normalize(z);
1439}
1440
Tim Peters212e6142001-07-14 12:23:19 +00001441/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1442 in pout, and returning the remainder. pin and pout point at the LSD.
1443 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001444 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001445 immutable. */
1446
1447static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001448inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001449{
1450 twodigits rem = 0;
1451
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001452 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001453 pin += size;
1454 pout += size;
1455 while (--size >= 0) {
1456 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001457 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001458 *--pout = hi = (digit)(rem / n);
1459 rem -= hi * n;
1460 }
1461 return (digit)rem;
1462}
1463
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001464/* Divide a long integer by a digit, returning both the quotient
1465 (as function result) and the remainder (through *prem).
1466 The sign of a is ignored; n should not be zero. */
1467
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001468static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001469divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001470{
Christian Heimes90aa7642007-12-19 02:45:37 +00001471 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001472 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001473
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001474 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001475 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001476 if (z == NULL)
1477 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001478 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001479 return long_normalize(z);
1480}
1481
1482/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001483 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001484 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001485
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001486PyObject *
1487_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001488{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001489 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001490 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001491 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001492 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001493 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001494 int bits;
1495 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001496
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001497 if (a == NULL || !PyLong_Check(a)) {
1498 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001499 return NULL;
1500 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001501 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001502 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001503
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001504 /* Compute a rough upper bound for the length of the string */
1505 i = base;
1506 bits = 0;
1507 while (i > 1) {
1508 ++bits;
1509 i >>= 1;
1510 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001511 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001512 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001513 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001514 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001515 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001516 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001517 return NULL;
1518 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001519 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001520 if (str == NULL)
1521 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001522 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001523 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001524 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001525 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001526
Christian Heimes90aa7642007-12-19 02:45:37 +00001527 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001528 *--p = '0';
1529 }
1530 else if ((base & (base - 1)) == 0) {
1531 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001532 twodigits accum = 0;
1533 int accumbits = 0; /* # of bits in accum */
1534 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001535 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001536 while ((i >>= 1) > 1)
1537 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001538
1539 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001540 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001541 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001542 assert(accumbits >= basebits);
1543 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001544 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001545 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001546 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001547 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001548 accumbits -= basebits;
1549 accum >>= basebits;
1550 } while (i < size_a-1 ? accumbits >= basebits :
1551 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001552 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001553 }
1554 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001555 /* Not 0, and base not a power of 2. Divide repeatedly by
1556 base, but for speed use the highest power of base that
1557 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001558 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001559 digit *pin = a->ob_digit;
1560 PyLongObject *scratch;
1561 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001562 digit powbase = base; /* powbase == base ** power */
1563 int power = 1;
1564 for (;;) {
1565 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001566 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001567 break;
1568 powbase = (digit)newpow;
1569 ++power;
1570 }
Tim Peters212e6142001-07-14 12:23:19 +00001571
1572 /* Get a scratch area for repeated division. */
1573 scratch = _PyLong_New(size);
1574 if (scratch == NULL) {
1575 Py_DECREF(str);
1576 return NULL;
1577 }
1578
1579 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001580 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001581 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001582 digit rem = inplace_divrem1(scratch->ob_digit,
1583 pin, size, powbase);
1584 pin = scratch->ob_digit; /* no need to use a again */
1585 if (pin[size - 1] == 0)
1586 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001587 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001588 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001589 Py_DECREF(str);
1590 return NULL;
1591 })
Tim Peters212e6142001-07-14 12:23:19 +00001592
1593 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001594 assert(ntostore > 0);
1595 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001596 digit nextrem = (digit)(rem / base);
1597 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001598 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001599 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001600 *--p = c;
1601 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001602 --ntostore;
1603 /* Termination is a bit delicate: must not
1604 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001605 remaining quotient and rem are both 0. */
1606 } while (ntostore && (size || rem));
1607 } while (size != 0);
1608 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001609 }
1610
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001611 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001612 *--p = 'x';
1613 *--p = '0';
1614 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001615 else if (base == 8) {
1616 *--p = 'o';
1617 *--p = '0';
1618 }
1619 else if (base == 2) {
1620 *--p = 'b';
1621 *--p = '0';
1622 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001623 else if (base != 10) {
1624 *--p = '#';
1625 *--p = '0' + base%10;
1626 if (base > 10)
1627 *--p = '0' + base/10;
1628 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001629 if (sign)
1630 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001631 if (p != PyUnicode_AS_UNICODE(str)) {
1632 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001633 assert(p > q);
1634 do {
1635 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001636 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001637 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1638 Py_DECREF(str);
1639 return NULL;
1640 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001641 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001642 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001643}
1644
Thomas Wouters477c8d52006-05-27 19:21:47 +00001645/* Table of digit values for 8-bit string -> integer conversion.
1646 * '0' maps to 0, ..., '9' maps to 9.
1647 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1648 * All other indices map to 37.
1649 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001650 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001651 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001652unsigned char _PyLong_DigitValue[256] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001653 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1654 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1655 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1656 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1657 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1658 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1659 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1660 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1661 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1662 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1663 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1664 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1665 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1666 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1667 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1668 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1669};
1670
1671/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001672 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1673 * non-digit (which may be *str!). A normalized long is returned.
1674 * The point to this routine is that it takes time linear in the number of
1675 * string characters.
1676 */
1677static PyLongObject *
1678long_from_binary_base(char **str, int base)
1679{
1680 char *p = *str;
1681 char *start = p;
1682 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001683 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001684 PyLongObject *z;
1685 twodigits accum;
1686 int bits_in_accum;
1687 digit *pdigit;
1688
1689 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1690 n = base;
1691 for (bits_per_char = -1; n; ++bits_per_char)
1692 n >>= 1;
1693 /* n <- total # of bits needed, while setting p to end-of-string */
1694 n = 0;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001695 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001696 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001697 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001698 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1699 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001700 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001701 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001702 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001703 return NULL;
1704 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001705 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001706 z = _PyLong_New(n);
1707 if (z == NULL)
1708 return NULL;
1709 /* Read string from right, and fill in long from left; i.e.,
1710 * from least to most significant in both.
1711 */
1712 accum = 0;
1713 bits_in_accum = 0;
1714 pdigit = z->ob_digit;
1715 while (--p >= start) {
Raymond Hettinger35631532009-01-09 03:58:09 +00001716 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001717 assert(k >= 0 && k < base);
1718 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001719 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001720 if (bits_in_accum >= PyLong_SHIFT) {
1721 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001722 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001723 accum >>= PyLong_SHIFT;
1724 bits_in_accum -= PyLong_SHIFT;
1725 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001726 }
1727 }
1728 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001729 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001730 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001731 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001732 }
1733 while (pdigit - z->ob_digit < n)
1734 *pdigit++ = 0;
1735 return long_normalize(z);
1736}
1737
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001738PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001739PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001740{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001741 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001742 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001743 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001744 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001745 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001746
Guido van Rossum472c04f1996-12-05 21:57:21 +00001747 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001748 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001749 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001750 return NULL;
1751 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001752 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001753 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001754 if (*str == '+')
1755 ++str;
1756 else if (*str == '-') {
1757 ++str;
1758 sign = -1;
1759 }
1760 if (base == 0) {
1761 if (str[0] != '0')
1762 base = 10;
1763 else if (str[1] == 'x' || str[1] == 'X')
1764 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001765 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001766 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001767 else if (str[1] == 'b' || str[1] == 'B')
1768 base = 2;
1769 else {
1770 /* "old" (C-style) octal literal, now invalid.
1771 it might still be zero though */
1772 error_if_nonzero = 1;
1773 base = 10;
1774 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001775 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001776 if (str[0] == '0' &&
1777 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1778 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1779 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001780 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001781
Guido van Rossume6762971998-06-22 03:54:46 +00001782 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001783 if ((base & (base - 1)) == 0)
1784 z = long_from_binary_base(&str, base);
1785 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001786/***
1787Binary bases can be converted in time linear in the number of digits, because
1788Python's representation base is binary. Other bases (including decimal!) use
1789the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001790
Thomas Wouters477c8d52006-05-27 19:21:47 +00001791First some math: the largest integer that can be expressed in N base-B digits
1792is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1793case number of Python digits needed to hold it is the smallest integer n s.t.
1794
1795 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1796 BASE**n >= B**N [taking logs to base BASE]
1797 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1798
1799The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1800this quickly. A Python long with that much space is reserved near the start,
1801and the result is computed into it.
1802
1803The input string is actually treated as being in base base**i (i.e., i digits
1804are processed at a time), where two more static arrays hold:
1805
1806 convwidth_base[base] = the largest integer i such that base**i <= BASE
1807 convmultmax_base[base] = base ** convwidth_base[base]
1808
1809The first of these is the largest i such that i consecutive input digits
1810must fit in a single Python digit. The second is effectively the input
1811base we're really using.
1812
1813Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1814convmultmax_base[base], the result is "simply"
1815
1816 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1817
1818where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001819
1820Error analysis: as above, the number of Python digits `n` needed is worst-
1821case
1822
1823 n >= N * log(B)/log(BASE)
1824
1825where `N` is the number of input digits in base `B`. This is computed via
1826
1827 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1828
1829below. Two numeric concerns are how much space this can waste, and whether
1830the computed result can be too small. To be concrete, assume BASE = 2**15,
1831which is the default (and it's unlikely anyone changes that).
1832
1833Waste isn't a problem: provided the first input digit isn't 0, the difference
1834between the worst-case input with N digits and the smallest input with N
1835digits is about a factor of B, but B is small compared to BASE so at most
1836one allocated Python digit can remain unused on that count. If
1837N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1838and adding 1 returns a result 1 larger than necessary. However, that can't
1839happen: whenever B is a power of 2, long_from_binary_base() is called
1840instead, and it's impossible for B**i to be an integer power of 2**15 when
1841B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1842an exact integer when B is not a power of 2, since B**i has a prime factor
1843other than 2 in that case, but (2**15)**j's only prime factor is 2).
1844
1845The computed result can be too small if the true value of N*log(B)/log(BASE)
1846is a little bit larger than an exact integer, but due to roundoff errors (in
1847computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1848yields a numeric result a little less than that integer. Unfortunately, "how
1849close can a transcendental function get to an integer over some range?"
1850questions are generally theoretically intractable. Computer analysis via
1851continued fractions is practical: expand log(B)/log(BASE) via continued
1852fractions, giving a sequence i/j of "the best" rational approximations. Then
1853j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1854we can get very close to being in trouble, but very rarely. For example,
185576573 is a denominator in one of the continued-fraction approximations to
1856log(10)/log(2**15), and indeed:
1857
1858 >>> log(10)/log(2**15)*76573
1859 16958.000000654003
1860
1861is very close to an integer. If we were working with IEEE single-precision,
1862rounding errors could kill us. Finding worst cases in IEEE double-precision
1863requires better-than-double-precision log() functions, and Tim didn't bother.
1864Instead the code checks to see whether the allocated space is enough as each
1865new Python digit is added, and copies the whole thing to a larger long if not.
1866This should happen extremely rarely, and in fact I don't have a test case
1867that triggers it(!). Instead the code was tested by artificially allocating
1868just 1 digit at the start, so that the copying code was exercised for every
1869digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001870***/
1871 register twodigits c; /* current input character */
1872 Py_ssize_t size_z;
1873 int i;
1874 int convwidth;
1875 twodigits convmultmax, convmult;
1876 digit *pz, *pzstop;
1877 char* scan;
1878
1879 static double log_base_BASE[37] = {0.0e0,};
1880 static int convwidth_base[37] = {0,};
1881 static twodigits convmultmax_base[37] = {0,};
1882
1883 if (log_base_BASE[base] == 0.0) {
1884 twodigits convmax = base;
1885 int i = 1;
1886
1887 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001888 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001889 for (;;) {
1890 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001891 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001892 break;
1893 convmax = next;
1894 ++i;
1895 }
1896 convmultmax_base[base] = convmax;
1897 assert(i > 0);
1898 convwidth_base[base] = i;
1899 }
1900
1901 /* Find length of the string of numeric characters. */
1902 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001903 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904 ++scan;
1905
1906 /* Create a long object that can contain the largest possible
1907 * integer with this base and length. Note that there's no
1908 * need to initialize z->ob_digit -- no slot is read up before
1909 * being stored into.
1910 */
1911 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001912 /* Uncomment next line to test exceedingly rare copy code */
1913 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001914 assert(size_z > 0);
1915 z = _PyLong_New(size_z);
1916 if (z == NULL)
1917 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001918 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001919
1920 /* `convwidth` consecutive input digits are treated as a single
1921 * digit in base `convmultmax`.
1922 */
1923 convwidth = convwidth_base[base];
1924 convmultmax = convmultmax_base[base];
1925
1926 /* Work ;-) */
1927 while (str < scan) {
1928 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001929 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00001930 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1931 c = (twodigits)(c * base +
Raymond Hettinger35631532009-01-09 03:58:09 +00001932 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001933 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001934 }
1935
1936 convmult = convmultmax;
1937 /* Calculate the shift only if we couldn't get
1938 * convwidth digits.
1939 */
1940 if (i != convwidth) {
1941 convmult = base;
1942 for ( ; i > 1; --i)
1943 convmult *= base;
1944 }
1945
1946 /* Multiply z by convmult, and add c. */
1947 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001948 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001949 for (; pz < pzstop; ++pz) {
1950 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001951 *pz = (digit)(c & PyLong_MASK);
1952 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001953 }
1954 /* carry off the current end? */
1955 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001956 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001957 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001958 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001959 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001960 }
1961 else {
1962 PyLongObject *tmp;
1963 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001964 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001965 tmp = _PyLong_New(size_z + 1);
1966 if (tmp == NULL) {
1967 Py_DECREF(z);
1968 return NULL;
1969 }
1970 memcpy(tmp->ob_digit,
1971 z->ob_digit,
1972 sizeof(digit) * size_z);
1973 Py_DECREF(z);
1974 z = tmp;
1975 z->ob_digit[size_z] = (digit)c;
1976 ++size_z;
1977 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001978 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001979 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001980 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001981 if (z == NULL)
1982 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001983 if (error_if_nonzero) {
1984 /* reset the base to 0, else the exception message
1985 doesn't make too much sense */
1986 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00001987 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001988 goto onError;
1989 /* there might still be other problems, therefore base
1990 remains zero here for the same reason */
1991 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001992 if (str == start)
1993 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001994 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00001995 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001996 while (*str && isspace(Py_CHARMASK(*str)))
1997 str++;
1998 if (*str != '\0')
1999 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002000 if (pend)
2001 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00002002 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002003 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002004
2005 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002006 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002007 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002008 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002009 if (strobj == NULL)
2010 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002011 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002012 "invalid literal for int() with base %d: %R",
2013 base, strobj);
2014 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002015 return NULL;
2016}
2017
2018PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002019PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002020{
Walter Dörwald07e14762002-11-06 16:15:14 +00002021 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002022 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002023
Walter Dörwald07e14762002-11-06 16:15:14 +00002024 if (buffer == NULL)
2025 return NULL;
2026
2027 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2028 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002029 return NULL;
2030 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002031 result = PyLong_FromString(buffer, NULL, base);
2032 PyMem_FREE(buffer);
2033 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002034}
2035
Tim Peters9f688bf2000-07-07 15:53:28 +00002036/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002037static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002038 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002039static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00002040static int long_divrem(PyLongObject *, PyLongObject *,
2041 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002042
2043/* Long division with remainder, top-level routine */
2044
Guido van Rossume32e0141992-01-19 16:31:05 +00002045static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002046long_divrem(PyLongObject *a, PyLongObject *b,
2047 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002048{
Christian Heimes90aa7642007-12-19 02:45:37 +00002049 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002050 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002051
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002052 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002053 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002054 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002055 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002056 }
2057 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002058 (size_a == size_b &&
2059 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002060 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002061 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002062 if (*pdiv == NULL)
2063 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002064 Py_INCREF(a);
2065 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002066 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002067 }
2068 if (size_b == 1) {
2069 digit rem = 0;
2070 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002071 if (z == NULL)
2072 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002073 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002074 if (*prem == NULL) {
2075 Py_DECREF(z);
2076 return -1;
2077 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002078 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002079 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002080 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002081 if (z == NULL)
2082 return -1;
2083 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084 /* Set the signs.
2085 The quotient z has the sign of a*b;
2086 the remainder r has the sign of a,
2087 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002088 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002089 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002090 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002091 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002092 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002093 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002094}
2095
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002096/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002097
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002098static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002099x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002100{
Christian Heimes90aa7642007-12-19 02:45:37 +00002101 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002102 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002103 PyLongObject *v = mul1(v1, d);
2104 PyLongObject *w = mul1(w1, d);
2105 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002106 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002107
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002108 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002109 Py_XDECREF(v);
2110 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002111 return NULL;
2112 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002113
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002114 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002115 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
2116 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002117
Christian Heimes90aa7642007-12-19 02:45:37 +00002118 size_v = ABS(Py_SIZE(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002119 k = size_v - size_w;
2120 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002121
Thomas Wouters477c8d52006-05-27 19:21:47 +00002122 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002123 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2124 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002125 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002126 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002127
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002128 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002129 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002130 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002131 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002132 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002133 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002134 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002135 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002136 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002137 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002138
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002139 while (w->ob_digit[size_w-2]*q >
2140 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002141 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002142 + v->ob_digit[j-1]
2143 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002144 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002145 + v->ob_digit[j-2])
2146 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002147
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002148 for (i = 0; i < size_w && i+k < size_v; ++i) {
2149 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002150 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002151 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002152 + ((twodigits)zz << PyLong_SHIFT);
2153 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002154 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002155 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002156 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002157 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002158
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002159 if (i+k < size_v) {
2160 carry += v->ob_digit[i+k];
2161 v->ob_digit[i+k] = 0;
2162 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002163
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002164 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002165 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002166 else {
2167 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002168 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002169 carry = 0;
2170 for (i = 0; i < size_w && i+k < size_v; ++i) {
2171 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002172 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002173 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2174 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002175 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002176 }
2177 }
2178 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002179
Guido van Rossumc206c761995-01-10 15:23:19 +00002180 if (a == NULL)
2181 *prem = NULL;
2182 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002183 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002184 *prem = divrem1(v, d, &d);
2185 /* d receives the (unused) remainder */
2186 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002187 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002188 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002189 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002190 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002191 Py_DECREF(v);
2192 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002193 return a;
2194}
2195
2196/* Methods */
2197
2198static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002199long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002200{
Christian Heimes90aa7642007-12-19 02:45:37 +00002201 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002202}
2203
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002204static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002205long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002206{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002207 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002208}
2209
2210static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002211long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002212{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002213 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002214
Christian Heimes90aa7642007-12-19 02:45:37 +00002215 if (Py_SIZE(a) != Py_SIZE(b)) {
2216 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002217 sign = 0;
2218 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002219 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002220 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002221 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002222 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002223 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2224 ;
2225 if (i < 0)
2226 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002227 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002228 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002229 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002230 sign = -sign;
2231 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002232 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002233 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002234}
2235
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002236#define TEST_COND(cond) \
2237 ((cond) ? Py_True : Py_False)
2238
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002239static PyObject *
2240long_richcompare(PyObject *self, PyObject *other, int op)
2241{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002242 int result;
2243 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002244 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002245 if (self == other)
2246 result = 0;
2247 else
2248 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2249 /* Convert the return value to a Boolean */
2250 switch (op) {
2251 case Py_EQ:
2252 v = TEST_COND(result == 0);
2253 break;
2254 case Py_NE:
2255 v = TEST_COND(result != 0);
2256 break;
2257 case Py_LE:
2258 v = TEST_COND(result <= 0);
2259 break;
2260 case Py_GE:
2261 v = TEST_COND(result >= 0);
2262 break;
2263 case Py_LT:
2264 v = TEST_COND(result == -1);
2265 break;
2266 case Py_GT:
2267 v = TEST_COND(result == 1);
2268 break;
2269 default:
2270 PyErr_BadArgument();
2271 return NULL;
2272 }
2273 Py_INCREF(v);
2274 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002275}
2276
Guido van Rossum9bfef441993-03-29 10:43:31 +00002277static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002278long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002279{
2280 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002281 Py_ssize_t i;
2282 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002283
2284 /* This is designed so that Python ints and longs with the
2285 same value hash to the same value, otherwise comparisons
2286 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002287 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002288 switch(i) {
2289 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2290 case 0: return 0;
2291 case 1: return v->ob_digit[0];
2292 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002293 sign = 1;
2294 x = 0;
2295 if (i < 0) {
2296 sign = -1;
2297 i = -(i);
2298 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002299#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Thomas Woutersce272b62007-09-19 21:19:28 +00002300 /* The following loop produces a C long x such that (unsigned long)x
2301 is congruent to the absolute value of v modulo ULONG_MAX. The
2302 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002303 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002304 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002305 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002306 x += v->ob_digit[i];
Thomas Woutersce272b62007-09-19 21:19:28 +00002307 /* If the addition above overflowed (thinking of x as
2308 unsigned), we compensate by incrementing. This preserves
2309 the value modulo ULONG_MAX. */
2310 if ((unsigned long)x < v->ob_digit[i])
2311 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002312 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002313#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002314 x = x * sign;
2315 if (x == -1)
2316 x = -2;
2317 return x;
2318}
2319
2320
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002321/* Add the absolute values of two long integers. */
2322
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002323static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002324x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002325{
Christian Heimes90aa7642007-12-19 02:45:37 +00002326 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002327 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002328 int i;
2329 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002330
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002331 /* Ensure a is the larger of the two: */
2332 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002333 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002334 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002335 size_a = size_b;
2336 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002337 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002338 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002339 if (z == NULL)
2340 return NULL;
2341 for (i = 0; i < size_b; ++i) {
2342 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002343 z->ob_digit[i] = carry & PyLong_MASK;
2344 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002345 }
2346 for (; i < size_a; ++i) {
2347 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002348 z->ob_digit[i] = carry & PyLong_MASK;
2349 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002350 }
2351 z->ob_digit[i] = carry;
2352 return long_normalize(z);
2353}
2354
2355/* Subtract the absolute values of two integers. */
2356
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002357static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002358x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002359{
Christian Heimes90aa7642007-12-19 02:45:37 +00002360 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002361 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002362 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002363 int sign = 1;
2364 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002365
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002366 /* Ensure a is the larger of the two: */
2367 if (size_a < size_b) {
2368 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002369 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002370 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002371 size_a = size_b;
2372 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002373 }
2374 else if (size_a == size_b) {
2375 /* Find highest digit where a and b differ: */
2376 i = size_a;
2377 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2378 ;
2379 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002380 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002381 if (a->ob_digit[i] < b->ob_digit[i]) {
2382 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002383 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002384 }
2385 size_a = size_b = i+1;
2386 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002387 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002388 if (z == NULL)
2389 return NULL;
2390 for (i = 0; i < size_b; ++i) {
2391 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002392 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002393 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002394 z->ob_digit[i] = borrow & PyLong_MASK;
2395 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002396 borrow &= 1; /* Keep only one sign bit */
2397 }
2398 for (; i < size_a; ++i) {
2399 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002400 z->ob_digit[i] = borrow & PyLong_MASK;
2401 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002402 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002403 }
2404 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002405 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002406 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002407 return long_normalize(z);
2408}
2409
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002410static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002411long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002412{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002413 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002414
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002415 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002416
Christian Heimes90aa7642007-12-19 02:45:37 +00002417 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002418 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002419 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002420 return result;
2421 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002422 if (Py_SIZE(a) < 0) {
2423 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002424 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
2429 z = x_sub(b, a);
2430 }
2431 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002432 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002433 z = x_sub(a, b);
2434 else
2435 z = x_add(a, b);
2436 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002437 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002438}
2439
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002440static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002441long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002442{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002443 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002444
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002445 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002446
Christian Heimes90aa7642007-12-19 02:45:37 +00002447 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002448 PyObject* r;
2449 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002450 return r;
2451 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002452 if (Py_SIZE(a) < 0) {
2453 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002454 z = x_sub(a, b);
2455 else
2456 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002457 if (z != NULL && Py_SIZE(z) != 0)
2458 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002459 }
2460 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002461 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002462 z = x_add(a, b);
2463 else
2464 z = x_sub(a, b);
2465 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002466 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002467}
2468
Tim Peters5af4e6c2002-08-12 02:31:19 +00002469/* Grade school multiplication, ignoring the signs.
2470 * Returns the absolute value of the product, or NULL if error.
2471 */
2472static PyLongObject *
2473x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002474{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002475 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002476 Py_ssize_t size_a = ABS(Py_SIZE(a));
2477 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002478 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002479
Tim Peters5af4e6c2002-08-12 02:31:19 +00002480 z = _PyLong_New(size_a + size_b);
2481 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002482 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002483
Christian Heimes90aa7642007-12-19 02:45:37 +00002484 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002485 if (a == b) {
2486 /* Efficient squaring per HAC, Algorithm 14.16:
2487 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2488 * Gives slightly less than a 2x speedup when a == b,
2489 * via exploiting that each entry in the multiplication
2490 * pyramid appears twice (except for the size_a squares).
2491 */
2492 for (i = 0; i < size_a; ++i) {
2493 twodigits carry;
2494 twodigits f = a->ob_digit[i];
2495 digit *pz = z->ob_digit + (i << 1);
2496 digit *pa = a->ob_digit + i + 1;
2497 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002498
Tim Peters0973b992004-08-29 22:16:50 +00002499 SIGCHECK({
2500 Py_DECREF(z);
2501 return NULL;
2502 })
2503
2504 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002505 *pz++ = (digit)(carry & PyLong_MASK);
2506 carry >>= PyLong_SHIFT;
2507 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002508
2509 /* Now f is added in twice in each column of the
2510 * pyramid it appears. Same as adding f<<1 once.
2511 */
2512 f <<= 1;
2513 while (pa < paend) {
2514 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002515 *pz++ = (digit)(carry & PyLong_MASK);
2516 carry >>= PyLong_SHIFT;
2517 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002518 }
2519 if (carry) {
2520 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002521 *pz++ = (digit)(carry & PyLong_MASK);
2522 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002523 }
2524 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002525 *pz += (digit)(carry & PyLong_MASK);
2526 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002527 }
Tim Peters0973b992004-08-29 22:16:50 +00002528 }
2529 else { /* a is not the same as b -- gradeschool long mult */
2530 for (i = 0; i < size_a; ++i) {
2531 twodigits carry = 0;
2532 twodigits f = a->ob_digit[i];
2533 digit *pz = z->ob_digit + i;
2534 digit *pb = b->ob_digit;
2535 digit *pbend = b->ob_digit + size_b;
2536
2537 SIGCHECK({
2538 Py_DECREF(z);
2539 return NULL;
2540 })
2541
2542 while (pb < pbend) {
2543 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002544 *pz++ = (digit)(carry & PyLong_MASK);
2545 carry >>= PyLong_SHIFT;
2546 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002547 }
2548 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002549 *pz += (digit)(carry & PyLong_MASK);
2550 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002551 }
2552 }
Tim Peters44121a62002-08-12 06:17:58 +00002553 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002554}
2555
2556/* A helper for Karatsuba multiplication (k_mul).
2557 Takes a long "n" and an integer "size" representing the place to
2558 split, and sets low and high such that abs(n) == (high << size) + low,
2559 viewing the shift as being by digits. The sign bit is ignored, and
2560 the return values are >= 0.
2561 Returns 0 on success, -1 on failure.
2562*/
2563static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002564kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002565{
2566 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002567 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002568 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002569
2570 size_lo = MIN(size_n, size);
2571 size_hi = size_n - size_lo;
2572
2573 if ((hi = _PyLong_New(size_hi)) == NULL)
2574 return -1;
2575 if ((lo = _PyLong_New(size_lo)) == NULL) {
2576 Py_DECREF(hi);
2577 return -1;
2578 }
2579
2580 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2581 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2582
2583 *high = long_normalize(hi);
2584 *low = long_normalize(lo);
2585 return 0;
2586}
2587
Tim Peters60004642002-08-12 22:01:34 +00002588static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2589
Tim Peters5af4e6c2002-08-12 02:31:19 +00002590/* Karatsuba multiplication. Ignores the input signs, and returns the
2591 * absolute value of the product (or NULL if error).
2592 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2593 */
2594static PyLongObject *
2595k_mul(PyLongObject *a, PyLongObject *b)
2596{
Christian Heimes90aa7642007-12-19 02:45:37 +00002597 Py_ssize_t asize = ABS(Py_SIZE(a));
2598 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002599 PyLongObject *ah = NULL;
2600 PyLongObject *al = NULL;
2601 PyLongObject *bh = NULL;
2602 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002603 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002604 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002605 Py_ssize_t shift; /* the number of digits we split off */
2606 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002607
Tim Peters5af4e6c2002-08-12 02:31:19 +00002608 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2609 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2610 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002611 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002612 * By picking X to be a power of 2, "*X" is just shifting, and it's
2613 * been reduced to 3 multiplies on numbers half the size.
2614 */
2615
Tim Petersfc07e562002-08-12 02:54:10 +00002616 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002617 * is largest.
2618 */
Tim Peters738eda72002-08-12 15:08:20 +00002619 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002620 t1 = a;
2621 a = b;
2622 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002623
2624 i = asize;
2625 asize = bsize;
2626 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002627 }
2628
2629 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002630 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2631 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002632 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002633 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002634 else
2635 return x_mul(a, b);
2636 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002637
Tim Peters60004642002-08-12 22:01:34 +00002638 /* If a is small compared to b, splitting on b gives a degenerate
2639 * case with ah==0, and Karatsuba may be (even much) less efficient
2640 * than "grade school" then. However, we can still win, by viewing
2641 * b as a string of "big digits", each of width a->ob_size. That
2642 * leads to a sequence of balanced calls to k_mul.
2643 */
2644 if (2 * asize <= bsize)
2645 return k_lopsided_mul(a, b);
2646
Tim Petersd6974a52002-08-13 20:37:51 +00002647 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002648 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002649 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002650 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002651
Tim Peters0973b992004-08-29 22:16:50 +00002652 if (a == b) {
2653 bh = ah;
2654 bl = al;
2655 Py_INCREF(bh);
2656 Py_INCREF(bl);
2657 }
2658 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002659
Tim Petersd64c1de2002-08-12 17:36:03 +00002660 /* The plan:
2661 * 1. Allocate result space (asize + bsize digits: that's always
2662 * enough).
2663 * 2. Compute ah*bh, and copy into result at 2*shift.
2664 * 3. Compute al*bl, and copy into result at 0. Note that this
2665 * can't overlap with #2.
2666 * 4. Subtract al*bl from the result, starting at shift. This may
2667 * underflow (borrow out of the high digit), but we don't care:
2668 * we're effectively doing unsigned arithmetic mod
2669 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2670 * borrows and carries out of the high digit can be ignored.
2671 * 5. Subtract ah*bh from the result, starting at shift.
2672 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2673 * at shift.
2674 */
2675
2676 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002677 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002678 if (ret == NULL) goto fail;
2679#ifdef Py_DEBUG
2680 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002681 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002682#endif
Tim Peters44121a62002-08-12 06:17:58 +00002683
Tim Petersd64c1de2002-08-12 17:36:03 +00002684 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002685 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002686 assert(Py_SIZE(t1) >= 0);
2687 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002688 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002689 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002690
2691 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002692 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002693 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002694 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002695 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002696
Tim Petersd64c1de2002-08-12 17:36:03 +00002697 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002698 if ((t2 = k_mul(al, bl)) == NULL) {
2699 Py_DECREF(t1);
2700 goto fail;
2701 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002702 assert(Py_SIZE(t2) >= 0);
2703 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2704 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002705
2706 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002707 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002708 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002709 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002710
Tim Petersd64c1de2002-08-12 17:36:03 +00002711 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2712 * because it's fresher in cache.
2713 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002714 i = Py_SIZE(ret) - shift; /* # digits after shift */
2715 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002716 Py_DECREF(t2);
2717
Christian Heimes90aa7642007-12-19 02:45:37 +00002718 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002719 Py_DECREF(t1);
2720
Tim Petersd64c1de2002-08-12 17:36:03 +00002721 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002722 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2723 Py_DECREF(ah);
2724 Py_DECREF(al);
2725 ah = al = NULL;
2726
Tim Peters0973b992004-08-29 22:16:50 +00002727 if (a == b) {
2728 t2 = t1;
2729 Py_INCREF(t2);
2730 }
2731 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002732 Py_DECREF(t1);
2733 goto fail;
2734 }
2735 Py_DECREF(bh);
2736 Py_DECREF(bl);
2737 bh = bl = NULL;
2738
Tim Peters738eda72002-08-12 15:08:20 +00002739 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002740 Py_DECREF(t1);
2741 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002742 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002743 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002744
Tim Petersd6974a52002-08-13 20:37:51 +00002745 /* Add t3. It's not obvious why we can't run out of room here.
2746 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002747 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002748 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002749 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002750
Tim Peters5af4e6c2002-08-12 02:31:19 +00002751 return long_normalize(ret);
2752
2753 fail:
2754 Py_XDECREF(ret);
2755 Py_XDECREF(ah);
2756 Py_XDECREF(al);
2757 Py_XDECREF(bh);
2758 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002759 return NULL;
2760}
2761
Tim Petersd6974a52002-08-13 20:37:51 +00002762/* (*) Why adding t3 can't "run out of room" above.
2763
Tim Petersab86c2b2002-08-15 20:06:00 +00002764Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2765to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002766
Tim Petersab86c2b2002-08-15 20:06:00 +000027671. For any integer i, i = c(i/2) + f(i/2). In particular,
2768 bsize = c(bsize/2) + f(bsize/2).
27692. shift = f(bsize/2)
27703. asize <= bsize
27714. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2772 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002773
Tim Petersab86c2b2002-08-15 20:06:00 +00002774We allocated asize + bsize result digits, and add t3 into them at an offset
2775of shift. This leaves asize+bsize-shift allocated digit positions for t3
2776to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2777asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002778
Tim Petersab86c2b2002-08-15 20:06:00 +00002779bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2780at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002781
Tim Petersab86c2b2002-08-15 20:06:00 +00002782If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2783digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2784most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002785
Tim Petersab86c2b2002-08-15 20:06:00 +00002786The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002787
Tim Petersab86c2b2002-08-15 20:06:00 +00002788 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002789
Tim Petersab86c2b2002-08-15 20:06:00 +00002790and we have asize + c(bsize/2) available digit positions. We need to show
2791this is always enough. An instance of c(bsize/2) cancels out in both, so
2792the question reduces to whether asize digits is enough to hold
2793(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2794then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2795asize 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 +00002796digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002797asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002798c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2799is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2800bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002801
Tim Peters48d52c02002-08-14 17:07:32 +00002802Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2803clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2804ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002805*/
2806
Tim Peters60004642002-08-12 22:01:34 +00002807/* b has at least twice the digits of a, and a is big enough that Karatsuba
2808 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2809 * of slices, each with a->ob_size digits, and multiply the slices by a,
2810 * one at a time. This gives k_mul balanced inputs to work with, and is
2811 * also cache-friendly (we compute one double-width slice of the result
2812 * at a time, then move on, never bactracking except for the helpful
2813 * single-width slice overlap between successive partial sums).
2814 */
2815static PyLongObject *
2816k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2817{
Christian Heimes90aa7642007-12-19 02:45:37 +00002818 const Py_ssize_t asize = ABS(Py_SIZE(a));
2819 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002820 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002821 PyLongObject *ret;
2822 PyLongObject *bslice = NULL;
2823
2824 assert(asize > KARATSUBA_CUTOFF);
2825 assert(2 * asize <= bsize);
2826
2827 /* Allocate result space, and zero it out. */
2828 ret = _PyLong_New(asize + bsize);
2829 if (ret == NULL)
2830 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002831 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002832
2833 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002834 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002835 if (bslice == NULL)
2836 goto fail;
2837
2838 nbdone = 0;
2839 while (bsize > 0) {
2840 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002841 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002842
2843 /* Multiply the next slice of b by a. */
2844 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2845 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002846 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002847 product = k_mul(a, bslice);
2848 if (product == NULL)
2849 goto fail;
2850
2851 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002852 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2853 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002854 Py_DECREF(product);
2855
2856 bsize -= nbtouse;
2857 nbdone += nbtouse;
2858 }
2859
2860 Py_DECREF(bslice);
2861 return long_normalize(ret);
2862
2863 fail:
2864 Py_DECREF(ret);
2865 Py_XDECREF(bslice);
2866 return NULL;
2867}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002868
2869static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002870long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002871{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002872 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002873
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002874 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002875
Christian Heimes90aa7642007-12-19 02:45:37 +00002876 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002877 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002878 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002879 return r;
2880 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002881
Tim Petersd64c1de2002-08-12 17:36:03 +00002882 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002883 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002884 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002885 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002886 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002887}
2888
Guido van Rossume32e0141992-01-19 16:31:05 +00002889/* The / and % operators are now defined in terms of divmod().
2890 The expression a mod b has the value a - b*floor(a/b).
2891 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002892 |a| by |b|, with the sign of a. This is also expressed
2893 as a - b*trunc(a/b), if trunc truncates towards zero.
2894 Some examples:
2895 a b a rem b a mod b
2896 13 10 3 3
2897 -13 10 -3 7
2898 13 -10 3 -7
2899 -13 -10 -3 -3
2900 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002901 have different signs. We then subtract one from the 'div'
2902 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002903
Tim Peters47e52ee2004-08-30 02:44:38 +00002904/* Compute
2905 * *pdiv, *pmod = divmod(v, w)
2906 * NULL can be passed for pdiv or pmod, in which case that part of
2907 * the result is simply thrown away. The caller owns a reference to
2908 * each of these it requests (does not pass NULL for).
2909 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002910static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002911l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002912 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002913{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002914 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002915
Guido van Rossume32e0141992-01-19 16:31:05 +00002916 if (long_divrem(v, w, &div, &mod) < 0)
2917 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002918 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2919 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002920 PyLongObject *temp;
2921 PyLongObject *one;
2922 temp = (PyLongObject *) long_add(mod, w);
2923 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002924 mod = temp;
2925 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002926 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002927 return -1;
2928 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002929 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002930 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002931 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2932 Py_DECREF(mod);
2933 Py_DECREF(div);
2934 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002935 return -1;
2936 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002937 Py_DECREF(one);
2938 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002939 div = temp;
2940 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002941 if (pdiv != NULL)
2942 *pdiv = div;
2943 else
2944 Py_DECREF(div);
2945
2946 if (pmod != NULL)
2947 *pmod = mod;
2948 else
2949 Py_DECREF(mod);
2950
Guido van Rossume32e0141992-01-19 16:31:05 +00002951 return 0;
2952}
2953
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002954static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002955long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002956{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002957 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002958
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002959 CHECK_BINOP(a, b);
2960 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002961 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002962 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002963}
2964
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002965static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002966long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002967{
Tim Peterse2a60002001-09-04 06:17:36 +00002968 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002969 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002970
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002971 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002972 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2973 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002974 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002975 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002976 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002977 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2978 but should really be set correctly after sucessful calls to
2979 _PyLong_AsScaledDouble() */
2980 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002981
2982 if (bd == 0.0) {
2983 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002984 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002985 return NULL;
2986 }
2987
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002988 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002989 ad /= bd; /* overflow/underflow impossible here */
2990 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002991 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002992 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002993 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002994 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002995 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002996 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002997 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002998 goto overflow;
2999 return PyFloat_FromDouble(ad);
3000
3001overflow:
3002 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003003 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00003004 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003005
Tim Peters20dab9f2001-09-04 05:31:47 +00003006}
3007
3008static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003009long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003010{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003011 PyLongObject *mod;
3012
3013 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003014
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003015 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003016 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003017 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003018}
3019
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003020static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003021long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003022{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003023 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003024 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003025
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003026 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003027
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003028 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003029 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003030 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003031 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003032 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003033 PyTuple_SetItem(z, 0, (PyObject *) div);
3034 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003035 }
3036 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003037 Py_DECREF(div);
3038 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003039 }
3040 return z;
3041}
3042
Tim Peters47e52ee2004-08-30 02:44:38 +00003043/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003044static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003045long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003046{
Tim Peters47e52ee2004-08-30 02:44:38 +00003047 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3048 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003049
Tim Peters47e52ee2004-08-30 02:44:38 +00003050 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003051 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003052 PyLongObject *temp = NULL;
3053
3054 /* 5-ary values. If the exponent is large enough, table is
3055 * precomputed so that table[i] == a**i % c for i in range(32).
3056 */
3057 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3058 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3059
3060 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003061 CHECK_BINOP(v, w);
3062 a = (PyLongObject*)v; Py_INCREF(a);
3063 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003064 if (PyLong_Check(x)) {
3065 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003066 Py_INCREF(x);
3067 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003068 else if (x == Py_None)
3069 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003070 else {
3071 Py_DECREF(a);
3072 Py_DECREF(b);
3073 Py_INCREF(Py_NotImplemented);
3074 return Py_NotImplemented;
3075 }
Tim Peters4c483c42001-09-05 06:24:58 +00003076
Christian Heimes90aa7642007-12-19 02:45:37 +00003077 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003078 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003079 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003080 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003081 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003082 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003083 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003084 /* else return a float. This works because we know
3085 that this calls float_pow() which converts its
3086 arguments to double. */
3087 Py_DECREF(a);
3088 Py_DECREF(b);
3089 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003090 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003091 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003092
3093 if (c) {
3094 /* if modulus == 0:
3095 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003096 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003097 PyErr_SetString(PyExc_ValueError,
3098 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003099 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003100 }
3101
3102 /* if modulus < 0:
3103 negativeOutput = True
3104 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003105 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003106 negativeOutput = 1;
3107 temp = (PyLongObject *)_PyLong_Copy(c);
3108 if (temp == NULL)
3109 goto Error;
3110 Py_DECREF(c);
3111 c = temp;
3112 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003113 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003114 }
3115
3116 /* if modulus == 1:
3117 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003118 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003119 z = (PyLongObject *)PyLong_FromLong(0L);
3120 goto Done;
3121 }
3122
3123 /* if base < 0:
3124 base = base % modulus
3125 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003126 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003127 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003128 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003129 Py_DECREF(a);
3130 a = temp;
3131 temp = NULL;
3132 }
3133 }
3134
3135 /* At this point a, b, and c are guaranteed non-negative UNLESS
3136 c is NULL, in which case a may be negative. */
3137
3138 z = (PyLongObject *)PyLong_FromLong(1L);
3139 if (z == NULL)
3140 goto Error;
3141
3142 /* Perform a modular reduction, X = X % c, but leave X alone if c
3143 * is NULL.
3144 */
3145#define REDUCE(X) \
3146 if (c != NULL) { \
3147 if (l_divmod(X, c, NULL, &temp) < 0) \
3148 goto Error; \
3149 Py_XDECREF(X); \
3150 X = temp; \
3151 temp = NULL; \
3152 }
3153
3154 /* Multiply two values, then reduce the result:
3155 result = X*Y % c. If c is NULL, skip the mod. */
3156#define MULT(X, Y, result) \
3157{ \
3158 temp = (PyLongObject *)long_mul(X, Y); \
3159 if (temp == NULL) \
3160 goto Error; \
3161 Py_XDECREF(result); \
3162 result = temp; \
3163 temp = NULL; \
3164 REDUCE(result) \
3165}
3166
Christian Heimes90aa7642007-12-19 02:45:37 +00003167 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003168 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3169 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003170 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003171 digit bi = b->ob_digit[i];
3172
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003173 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003174 MULT(z, z, z)
3175 if (bi & j)
3176 MULT(z, a, z)
3177 }
3178 }
3179 }
3180 else {
3181 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3182 Py_INCREF(z); /* still holds 1L */
3183 table[0] = z;
3184 for (i = 1; i < 32; ++i)
3185 MULT(table[i-1], a, table[i])
3186
Christian Heimes90aa7642007-12-19 02:45:37 +00003187 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003188 const digit bi = b->ob_digit[i];
3189
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003190 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003191 const int index = (bi >> j) & 0x1f;
3192 for (k = 0; k < 5; ++k)
3193 MULT(z, z, z)
3194 if (index)
3195 MULT(z, table[index], z)
3196 }
3197 }
3198 }
3199
Christian Heimes90aa7642007-12-19 02:45:37 +00003200 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003201 temp = (PyLongObject *)long_sub(z, c);
3202 if (temp == NULL)
3203 goto Error;
3204 Py_DECREF(z);
3205 z = temp;
3206 temp = NULL;
3207 }
3208 goto Done;
3209
3210 Error:
3211 if (z != NULL) {
3212 Py_DECREF(z);
3213 z = NULL;
3214 }
3215 /* fall through */
3216 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003217 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003218 for (i = 0; i < 32; ++i)
3219 Py_XDECREF(table[i]);
3220 }
Tim Petersde7990b2005-07-17 23:45:23 +00003221 Py_DECREF(a);
3222 Py_DECREF(b);
3223 Py_XDECREF(c);
3224 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003225 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003226}
3227
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003228static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003229long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003230{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003231 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003232 PyLongObject *x;
3233 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003234 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003235 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003236 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003237 if (w == NULL)
3238 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003239 x = (PyLongObject *) long_add(v, w);
3240 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003241 if (x == NULL)
3242 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003243 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003244 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003245}
3246
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003247static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003248long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003249{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003250 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003251 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003252 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003253 z = (PyLongObject *)_PyLong_Copy(v);
3254 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003255 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003256 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003257}
3258
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003259static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003260long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003261{
Christian Heimes90aa7642007-12-19 02:45:37 +00003262 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003263 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003264 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003265 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003266}
3267
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003268static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003269long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003270{
Christian Heimes90aa7642007-12-19 02:45:37 +00003271 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003272}
3273
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003274static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003275long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003276{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003277 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003278 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003279 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003280 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003281
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003282 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003283
Christian Heimes90aa7642007-12-19 02:45:37 +00003284 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003285 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003286 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003287 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003288 if (a1 == NULL)
3289 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003290 a2 = (PyLongObject *) long_rshift(a1, b);
3291 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003292 if (a2 == NULL)
3293 goto rshift_error;
3294 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003295 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003296 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003297 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003298
Neil Schemenauerba872e22001-01-04 01:46:03 +00003299 shiftby = PyLong_AsLong((PyObject *)b);
3300 if (shiftby == -1L && PyErr_Occurred())
3301 goto rshift_error;
3302 if (shiftby < 0) {
3303 PyErr_SetString(PyExc_ValueError,
3304 "negative shift count");
3305 goto rshift_error;
3306 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003307 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003308 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003309 if (newsize <= 0)
3310 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003311 loshift = shiftby % PyLong_SHIFT;
3312 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003313 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003314 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003315 z = _PyLong_New(newsize);
3316 if (z == NULL)
3317 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003318 if (Py_SIZE(a) < 0)
3319 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003320 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3321 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3322 if (i+1 < newsize)
3323 z->ob_digit[i] |=
3324 (a->ob_digit[j+1] << hishift) & himask;
3325 }
3326 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003327 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003328rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003329 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003330
Guido van Rossumc6913e71991-11-19 20:26:46 +00003331}
3332
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003333static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003334long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003335{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003336 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003337 PyLongObject *a = (PyLongObject*)v;
3338 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003339 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003340 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003341 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003342 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003343
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003344 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003345
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003346 shiftby = PyLong_AsLong((PyObject *)b);
3347 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003348 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003349 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003350 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003351 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003352 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003353 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003354 PyErr_SetString(PyExc_ValueError,
3355 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003356 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003357 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003358 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3359 wordshift = (int)shiftby / PyLong_SHIFT;
3360 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003361
Christian Heimes90aa7642007-12-19 02:45:37 +00003362 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003363 newsize = oldsize + wordshift;
3364 if (remshift)
3365 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003366 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003367 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003368 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003369 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003370 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003371 for (i = 0; i < wordshift; i++)
3372 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003373 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003374 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003375 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003376 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3377 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003378 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003379 if (remshift)
3380 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003381 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003382 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003383 z = long_normalize(z);
3384lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003385 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003386}
3387
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003388
3389/* Bitwise and/xor/or operations */
3390
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003391static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003392long_bitwise(PyLongObject *a,
3393 int op, /* '&', '|', '^' */
3394 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003395{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003396 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003397 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003398 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003399 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003400 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003401 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003402 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003403
Christian Heimes90aa7642007-12-19 02:45:37 +00003404 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003405 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003406 if (a == NULL)
3407 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003408 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003409 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003410 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003411 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003412 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003413 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003414 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003415 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003416 if (b == NULL) {
3417 Py_DECREF(a);
3418 return NULL;
3419 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003420 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003421 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003422 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003423 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003424 maskb = 0;
3425 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003426
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003427 negz = 0;
3428 switch (op) {
3429 case '^':
3430 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003431 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003432 negz = -1;
3433 }
3434 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003435 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003436 if (maska && maskb) {
3437 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003438 maska ^= PyLong_MASK;
3439 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003440 negz = -1;
3441 }
3442 break;
3443 case '|':
3444 if (maska || maskb) {
3445 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003446 maska ^= PyLong_MASK;
3447 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003448 negz = -1;
3449 }
3450 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003451 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003452
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003453 /* JRH: The original logic here was to allocate the result value (z)
3454 as the longer of the two operands. However, there are some cases
3455 where the result is guaranteed to be shorter than that: AND of two
3456 positives, OR of two negatives: use the shorter number. AND with
3457 mixed signs: use the positive number. OR with mixed signs: use the
3458 negative number. After the transformations above, op will be '&'
3459 iff one of these cases applies, and mask will be non-0 for operands
3460 whose length should be ignored.
3461 */
3462
Christian Heimes90aa7642007-12-19 02:45:37 +00003463 size_a = Py_SIZE(a);
3464 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003465 size_z = op == '&'
3466 ? (maska
3467 ? size_b
3468 : (maskb ? size_a : MIN(size_a, size_b)))
3469 : MAX(size_a, size_b);
3470 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003471 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003472 Py_DECREF(a);
3473 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003474 return NULL;
3475 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003476
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003477 for (i = 0; i < size_z; ++i) {
3478 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3479 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3480 switch (op) {
3481 case '&': z->ob_digit[i] = diga & digb; break;
3482 case '|': z->ob_digit[i] = diga | digb; break;
3483 case '^': z->ob_digit[i] = diga ^ digb; break;
3484 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003485 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003486
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003487 Py_DECREF(a);
3488 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003489 z = long_normalize(z);
3490 if (negz == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003491 return (PyObject *) maybe_small_long(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003492 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003493 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003494 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003495}
3496
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003497static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003498long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003499{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003500 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003501 CHECK_BINOP(a, b);
3502 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003503 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003504}
3505
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003506static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003507long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003508{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003509 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003510 CHECK_BINOP(a, b);
3511 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003512 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003513}
3514
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003515static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003516long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003517{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003518 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003519 CHECK_BINOP(a, b);
3520 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003521 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003522}
3523
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003524static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003525long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003526{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003527 if (PyLong_CheckExact(v))
3528 Py_INCREF(v);
3529 else
3530 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003531 return v;
3532}
3533
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003534static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003535long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003536{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003537 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003538 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003539 if (result == -1.0 && PyErr_Occurred())
3540 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003541 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003542}
3543
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003544static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003545long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003546
Tim Peters6d6c1a32001-08-02 04:15:00 +00003547static PyObject *
3548long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3549{
3550 PyObject *x = NULL;
3551 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003552 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003553
Guido van Rossumbef14172001-08-29 15:47:46 +00003554 if (type != &PyLong_Type)
3555 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003556 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003557 &x, &base))
3558 return NULL;
3559 if (x == NULL)
3560 return PyLong_FromLong(0L);
3561 if (base == -909)
3562 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003563 else if (PyUnicode_Check(x))
3564 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3565 PyUnicode_GET_SIZE(x),
3566 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003567 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003568 /* Since PyLong_FromString doesn't have a length parameter,
3569 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003570 char *string;
Christian Heimes90aa7642007-12-19 02:45:37 +00003571 int size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003572 if (PyByteArray_Check(x))
3573 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003574 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003575 string = PyBytes_AS_STRING(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003576 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003577 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003578 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003579 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003580 "invalid literal for int() with base %d: %R",
3581 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003582 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003583 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003584 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003585 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003586 else {
3587 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003588 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003589 return NULL;
3590 }
3591}
3592
Guido van Rossumbef14172001-08-29 15:47:46 +00003593/* Wimpy, slow approach to tp_new calls for subtypes of long:
3594 first create a regular long from whatever arguments we got,
3595 then allocate a subtype instance and initialize it from
3596 the regular long. The regular long is then thrown away.
3597*/
3598static PyObject *
3599long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3600{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003601 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003602 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003603
3604 assert(PyType_IsSubtype(type, &PyLong_Type));
3605 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3606 if (tmp == NULL)
3607 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003608 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003609 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003610 if (n < 0)
3611 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003612 newobj = (PyLongObject *)type->tp_alloc(type, n);
3613 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003614 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003615 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003616 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003617 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003618 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003619 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003620 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003621 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003622 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003623}
3624
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003625static PyObject *
3626long_getnewargs(PyLongObject *v)
3627{
3628 return Py_BuildValue("(N)", _PyLong_Copy(v));
3629}
3630
Guido van Rossumb43daf72007-08-01 18:08:08 +00003631static PyObject *
3632long_getN(PyLongObject *v, void *context) {
Christian Heimesc36625b2008-01-04 13:33:00 +00003633 return PyLong_FromLong((Py_intptr_t)context);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003634}
3635
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003636static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003637long__format__(PyObject *self, PyObject *args)
3638{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003639 PyObject *format_spec;
3640
3641 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3642 return NULL;
3643 return _PyLong_FormatAdvanced(self,
3644 PyUnicode_AS_UNICODE(format_spec),
3645 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003646}
3647
3648
3649static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003650long_round(PyObject *self, PyObject *args)
3651{
3652#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3653 int ndigits = UNDEF_NDIGITS;
3654 double x;
3655 PyObject *res;
3656
3657 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3658 return NULL;
3659
3660 if (ndigits == UNDEF_NDIGITS)
3661 return long_long(self);
3662
3663 /* If called with two args, defer to float.__round__(). */
3664 x = PyLong_AsDouble(self);
3665 if (x == -1.0 && PyErr_Occurred())
3666 return NULL;
3667 self = PyFloat_FromDouble(x);
3668 if (self == NULL)
3669 return NULL;
3670 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3671 Py_DECREF(self);
3672 return res;
3673#undef UNDEF_NDIGITS
3674}
3675
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003676static PyObject *
3677long_sizeof(PyLongObject *v)
3678{
3679 Py_ssize_t res;
3680
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003681 res = sizeof(PyVarObject) + abs(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003682 return PyLong_FromSsize_t(res);
3683}
3684
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003685static const unsigned char BitLengthTable[32] = {
3686 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
3687 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
3688};
3689
3690static PyObject *
3691long_bit_length(PyLongObject *v)
3692{
3693 PyLongObject *result, *x, *y;
3694 Py_ssize_t ndigits, msd_bits = 0;
3695 digit msd;
3696
3697 assert(v != NULL);
3698 assert(PyLong_Check(v));
3699
3700 ndigits = ABS(Py_SIZE(v));
3701 if (ndigits == 0)
3702 return PyLong_FromLong(0);
3703
3704 msd = v->ob_digit[ndigits-1];
3705 while (msd >= 32) {
3706 msd_bits += 6;
3707 msd >>= 6;
3708 }
3709 msd_bits += (long)(BitLengthTable[msd]);
3710
3711 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3712 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3713
3714 /* expression above may overflow; use Python integers instead */
3715 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3716 if (result == NULL)
3717 return NULL;
3718 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3719 if (x == NULL)
3720 goto error;
3721 y = (PyLongObject *)long_mul(result, x);
3722 Py_DECREF(x);
3723 if (y == NULL)
3724 goto error;
3725 Py_DECREF(result);
3726 result = y;
3727
3728 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3729 if (x == NULL)
3730 goto error;
3731 y = (PyLongObject *)long_add(result, x);
3732 Py_DECREF(x);
3733 if (y == NULL)
3734 goto error;
3735 Py_DECREF(result);
3736 result = y;
3737
3738 return (PyObject *)result;
3739
3740error:
3741 Py_DECREF(result);
3742 return NULL;
3743}
3744
3745PyDoc_STRVAR(long_bit_length_doc,
3746"int.bit_length() -> int\n\
3747\n\
3748Number of bits necessary to represent self in binary.\n\
3749>>> bin(37)\n\
3750'0b100101'\n\
3751>>> (37).bit_length()\n\
37526");
3753
Christian Heimes53876d92008-04-19 00:31:39 +00003754#if 0
3755static PyObject *
3756long_is_finite(PyObject *v)
3757{
3758 Py_RETURN_TRUE;
3759}
3760#endif
3761
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003762static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003763 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3764 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003765 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3766 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00003767#if 0
3768 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3769 "Returns always True."},
3770#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003771 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3772 "Truncating an Integral returns itself."},
3773 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3774 "Flooring an Integral returns itself."},
3775 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3776 "Ceiling of an Integral returns itself."},
3777 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3778 "Rounding an Integral returns itself.\n"
3779 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003780 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003781 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003782 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
3783 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003784 {NULL, NULL} /* sentinel */
3785};
3786
Guido van Rossumb43daf72007-08-01 18:08:08 +00003787static PyGetSetDef long_getset[] = {
3788 {"real",
3789 (getter)long_long, (setter)NULL,
3790 "the real part of a complex number",
3791 NULL},
3792 {"imag",
3793 (getter)long_getN, (setter)NULL,
3794 "the imaginary part of a complex number",
3795 (void*)0},
3796 {"numerator",
3797 (getter)long_long, (setter)NULL,
3798 "the numerator of a rational number in lowest terms",
3799 NULL},
3800 {"denominator",
3801 (getter)long_getN, (setter)NULL,
3802 "the denominator of a rational number in lowest terms",
3803 (void*)1},
3804 {NULL} /* Sentinel */
3805};
3806
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003807PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003808"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003809\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003810Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003811point argument will be truncated towards zero (this does not include a\n\
3812string representation of a floating point number!) When converting a\n\
3813string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003814converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003815
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003816static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003817 (binaryfunc) long_add, /*nb_add*/
3818 (binaryfunc) long_sub, /*nb_subtract*/
3819 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003820 long_mod, /*nb_remainder*/
3821 long_divmod, /*nb_divmod*/
3822 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003823 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003824 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003825 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003826 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003827 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003828 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003829 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003830 long_and, /*nb_and*/
3831 long_xor, /*nb_xor*/
3832 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003833 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00003834 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003835 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003836 0, /* nb_inplace_add */
3837 0, /* nb_inplace_subtract */
3838 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003839 0, /* nb_inplace_remainder */
3840 0, /* nb_inplace_power */
3841 0, /* nb_inplace_lshift */
3842 0, /* nb_inplace_rshift */
3843 0, /* nb_inplace_and */
3844 0, /* nb_inplace_xor */
3845 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003846 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003847 long_true_divide, /* nb_true_divide */
3848 0, /* nb_inplace_floor_divide */
3849 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003850 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003851};
3852
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003853PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003854 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003855 "int", /* tp_name */
3856 /* See _PyLong_New for why this isn't
3857 sizeof(PyLongObject) - sizeof(digit) */
3858 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003859 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003860 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003861 0, /* tp_print */
3862 0, /* tp_getattr */
3863 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003864 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003865 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866 &long_as_number, /* tp_as_number */
3867 0, /* tp_as_sequence */
3868 0, /* tp_as_mapping */
3869 (hashfunc)long_hash, /* tp_hash */
3870 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003871 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003872 PyObject_GenericGetAttr, /* tp_getattro */
3873 0, /* tp_setattro */
3874 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003875 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3876 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003877 long_doc, /* tp_doc */
3878 0, /* tp_traverse */
3879 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003880 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881 0, /* tp_weaklistoffset */
3882 0, /* tp_iter */
3883 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003884 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003886 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887 0, /* tp_base */
3888 0, /* tp_dict */
3889 0, /* tp_descr_get */
3890 0, /* tp_descr_set */
3891 0, /* tp_dictoffset */
3892 0, /* tp_init */
3893 0, /* tp_alloc */
3894 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003895 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003896};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003897
3898int
3899_PyLong_Init(void)
3900{
3901#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003902 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003903 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003904
3905 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
3906 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
3907 if (Py_TYPE(v) == &PyLong_Type) {
3908 /* The element is already initialized, most likely
3909 * the Python interpreter was initialized before.
3910 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00003911 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003912 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003913
Christian Heimes48aa4b12008-02-01 16:56:30 +00003914 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
3915 _Py_NewReference(op);
3916 /* _Py_NewReference sets the ref count to 1 but
3917 * the ref count might be larger. Set the refcnt
3918 * to the original refcnt + 1 */
3919 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003920 assert(Py_SIZE(op) == size);
3921 assert(v->ob_digit[0] == abs(ival));
3922 }
3923 else {
3924 PyObject_INIT(v, &PyLong_Type);
3925 }
3926 Py_SIZE(v) = size;
3927 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003928 }
3929#endif
3930 return 1;
3931}
3932
3933void
3934PyLong_Fini(void)
3935{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003936 /* Integers are currently statically allocated. Py_DECREF is not
3937 needed, but Python must forget about the reference or multiple
3938 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003939#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003940 int i;
3941 PyLongObject *v = small_ints;
3942 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
3943 _Py_DEC_REFTOTAL;
3944 _Py_ForgetReference((PyObject*)v);
3945 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003946#endif
3947}