blob: 376973eb0dbac4c3c83e5d4f96f94e68bc5dd7b1 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003/* Long (arbitrary precision) integer object implementation */
4
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00005/* XXX The functional organization of this file is terrible */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00008#include "longintrepr.h"
Mark Dickinsonefc82f72009-03-20 15:51:55 +00009#include "structseq.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +000010
Mark Dickinson6736cf82009-04-20 21:13:33 +000011#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000012#include <ctype.h>
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000013#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000014
Tim Peters5af4e6c2002-08-12 02:31:19 +000015/* For long multiplication, use the O(N**2) school algorithm unless
16 * both operands contain more than KARATSUBA_CUTOFF digits (this
Christian Heimes7f39c9f2008-01-25 12:18:43 +000017 * being an internal Python long digit, in base PyLong_BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000018 */
Tim Peters0973b992004-08-29 22:16:50 +000019#define KARATSUBA_CUTOFF 70
20#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000021
Tim Peters47e52ee2004-08-30 02:44:38 +000022/* For exponentiation, use the binary left-to-right algorithm
23 * unless the exponent contains more than FIVEARY_CUTOFF digits.
24 * In that case, do 5 bits at a time. The potential drawback is that
25 * a table of 2**5 intermediate results is computed.
26 */
27#define FIVEARY_CUTOFF 8
28
Guido van Rossume32e0141992-01-19 16:31:05 +000029#define ABS(x) ((x) < 0 ? -(x) : (x))
30
Tim Peters5af4e6c2002-08-12 02:31:19 +000031#undef MIN
32#undef MAX
33#define MAX(x, y) ((x) < (y) ? (y) : (x))
34#define MIN(x, y) ((x) > (y) ? (y) : (x))
35
Guido van Rossumc0b618a1997-05-02 03:12:38 +000036#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000037 if (--_Py_Ticker < 0) { \
38 _Py_Ticker = _Py_CheckInterval; \
Tim Petersd89fc222006-05-25 22:28:46 +000039 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000040 }
41
Mark Dickinson6736cf82009-04-20 21:13:33 +000042/* forward declaration */
43static int bits_in_digit(digit d);
44
Guido van Rossumedcc38a1991-05-05 20:09:44 +000045/* Normalize (remove leading zeros from) a long int object.
46 Doesn't attempt to free the storage--in most cases, due to the nature
47 of the algorithms used, this could save at most be one word anyway. */
48
Guido van Rossumc0b618a1997-05-02 03:12:38 +000049static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000050long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000051{
Christian Heimese93237d2007-12-19 02:37:44 +000052 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +000053 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000054
Guido van Rossumedcc38a1991-05-05 20:09:44 +000055 while (i > 0 && v->ob_digit[i-1] == 0)
56 --i;
57 if (i != j)
Christian Heimese93237d2007-12-19 02:37:44 +000058 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +000059 return v;
60}
61
62/* Allocate a new long int object with size digits.
63 Return NULL and set exception if we run out of memory. */
64
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000065#define MAX_LONG_DIGITS \
66 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
67
Guido van Rossumc0b618a1997-05-02 03:12:38 +000068PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000069_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000070{
Mark Dickinsonbcf6b182009-02-15 15:48:39 +000071 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000072 PyErr_SetString(PyExc_OverflowError,
73 "too many digits in integer");
Martin v. Löwis18e16552006-02-15 17:27:45 +000074 return NULL;
75 }
Christian Heimes4956d2b2008-01-18 19:12:56 +000076 /* coverity[ampersand_in_size] */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000077 /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect
78 overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000080}
81
Tim Peters64b5ce32001-09-10 20:52:51 +000082PyObject *
83_PyLong_Copy(PyLongObject *src)
84{
85 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +000086 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000087
88 assert(src != NULL);
89 i = src->ob_size;
90 if (i < 0)
91 i = -(i);
92 result = _PyLong_New(i);
93 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +000094 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +000095 while (--i >= 0)
96 result->ob_digit[i] = src->ob_digit[i];
97 }
98 return (PyObject *)result;
99}
100
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000101/* Create a new long int object from a C long int */
102
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000103PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000104PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000105{
Tim Petersce9de2f2001-06-14 04:56:19 +0000106 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000107 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000108 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
109 int ndigits = 0;
110 int negative = 0;
111
112 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000113 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
114 ANSI C says that the result of -ival is undefined when ival
115 == LONG_MIN. Hence the following workaround. */
116 abs_ival = (unsigned long)(-1-ival) + 1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000117 negative = 1;
118 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000119 else {
120 abs_ival = (unsigned long)ival;
121 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000122
123 /* Count the number of Python digits.
124 We used to pick 5 ("big enough for anything"), but that's a
125 waste of time and space given that 5*15 = 75 bits are rarely
126 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000127 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000128 while (t) {
129 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000130 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000131 }
132 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000133 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000134 digit *p = v->ob_digit;
135 v->ob_size = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000136 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000137 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000138 *p++ = (digit)(t & PyLong_MASK);
139 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000140 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000141 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000143}
144
Guido van Rossum53756b11997-01-03 17:14:46 +0000145/* Create a new long int object from a C unsigned long int */
146
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000148PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000149{
Tim Petersce9de2f2001-06-14 04:56:19 +0000150 PyLongObject *v;
151 unsigned long t;
152 int ndigits = 0;
153
154 /* Count the number of Python digits. */
155 t = (unsigned long)ival;
156 while (t) {
157 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000158 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000159 }
160 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000161 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000162 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000163 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000164 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000165 *p++ = (digit)(ival & PyLong_MASK);
166 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000167 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000168 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000169 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000170}
171
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000172/* Create a new long int object from a C double */
173
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000174PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000176{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000177 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000178 double frac;
179 int i, ndig, expo, neg;
180 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000181 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000182 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonb6467572008-08-04 21:30:09 +0000183 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000184 return NULL;
185 }
Christian Heimes8267d1d2008-01-04 00:37:34 +0000186 if (Py_IS_NAN(dval)) {
Mark Dickinsonb6467572008-08-04 21:30:09 +0000187 PyErr_SetString(PyExc_ValueError,
188 "cannot convert float NaN to integer");
189 return NULL;
Christian Heimes8267d1d2008-01-04 00:37:34 +0000190 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000191 if (dval < 0.0) {
192 neg = 1;
193 dval = -dval;
194 }
195 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
196 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000197 return PyLong_FromLong(0L);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000198 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000199 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000200 if (v == NULL)
201 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000202 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000203 for (i = ndig; --i >= 0; ) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000204 digit bits = (digit)frac;
205 v->ob_digit[i] = bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000206 frac = frac - (double)bits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000207 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000208 }
209 if (neg)
Christian Heimese93237d2007-12-19 02:37:44 +0000210 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000212}
213
Armin Rigo7ccbca92006-10-04 12:17:45 +0000214/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
215 * anything about what happens when a signed integer operation overflows,
216 * and some compilers think they're doing you a favor by being "clever"
217 * then. The bit pattern for the largest postive signed long is
218 * (unsigned long)LONG_MAX, and for the smallest negative signed long
219 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
220 * However, some other compilers warn about applying unary minus to an
221 * unsigned operand. Hence the weird "0-".
222 */
223#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
224#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
225
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000226/* Get a C long int from a long int object.
227 Returns -1 and sets an error condition if overflow occurs. */
228
229long
Tim Peters9f688bf2000-07-07 15:53:28 +0000230PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000231{
Guido van Rossumf7531811998-05-26 14:33:37 +0000232 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000233 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000234 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000235 Py_ssize_t i;
236 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000237
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238 if (vv == NULL || !PyLong_Check(vv)) {
Guido van Rossum7e35d572001-09-15 03:14:32 +0000239 if (vv != NULL && PyInt_Check(vv))
240 return PyInt_AsLong(vv);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000241 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000242 return -1;
243 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000245 i = v->ob_size;
246 sign = 1;
247 x = 0;
248 if (i < 0) {
249 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000250 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000251 }
252 while (--i >= 0) {
253 prev = x;
Mark Dickinson71adc932009-09-28 16:52:40 +0000254 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000255 if ((x >> PyLong_SHIFT) != prev)
Guido van Rossumf7531811998-05-26 14:33:37 +0000256 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000257 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000258 /* Haven't lost any bits, but casting to long requires extra care
259 * (see comment above).
260 */
261 if (x <= (unsigned long)LONG_MAX) {
262 return (long)x * sign;
263 }
264 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
265 return LONG_MIN;
266 }
267 /* else overflow */
Guido van Rossumf7531811998-05-26 14:33:37 +0000268
269 overflow:
270 PyErr_SetString(PyExc_OverflowError,
Skip Montanarobafedec2001-09-13 19:05:30 +0000271 "long int too large to convert to int");
Guido van Rossumf7531811998-05-26 14:33:37 +0000272 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000273}
274
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000275/* Get a Py_ssize_t from a long int object.
276 Returns -1 and sets an error condition if overflow occurs. */
277
278Py_ssize_t
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000279PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000280 register PyLongObject *v;
281 size_t x, prev;
282 Py_ssize_t i;
283 int sign;
284
285 if (vv == NULL || !PyLong_Check(vv)) {
286 PyErr_BadInternalCall();
287 return -1;
288 }
289 v = (PyLongObject *)vv;
290 i = v->ob_size;
291 sign = 1;
292 x = 0;
293 if (i < 0) {
294 sign = -1;
295 i = -(i);
296 }
297 while (--i >= 0) {
298 prev = x;
Mark Dickinson71adc932009-09-28 16:52:40 +0000299 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000300 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000301 goto overflow;
302 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000303 /* Haven't lost any bits, but casting to a signed type requires
304 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000305 */
Armin Rigo7ccbca92006-10-04 12:17:45 +0000306 if (x <= (size_t)PY_SSIZE_T_MAX) {
307 return (Py_ssize_t)x * sign;
308 }
309 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
310 return PY_SSIZE_T_MIN;
311 }
312 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000313
314 overflow:
315 PyErr_SetString(PyExc_OverflowError,
316 "long int too large to convert to int");
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000317 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000318}
319
Guido van Rossumd8c80482002-08-13 00:24:58 +0000320/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000321 Returns -1 and sets an error condition if overflow occurs. */
322
323unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000324PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000325{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000327 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000328 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000329
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000331 if (vv != NULL && PyInt_Check(vv)) {
332 long val = PyInt_AsLong(vv);
333 if (val < 0) {
334 PyErr_SetString(PyExc_OverflowError,
335 "can't convert negative value to unsigned long");
336 return (unsigned long) -1;
337 }
338 return val;
339 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000341 return (unsigned long) -1;
342 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000344 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000345 x = 0;
346 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000347 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000348 "can't convert negative value to unsigned long");
349 return (unsigned long) -1;
350 }
351 while (--i >= 0) {
352 prev = x;
Mark Dickinson71adc932009-09-28 16:52:40 +0000353 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000354 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000355 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000356 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000357 return (unsigned long) -1;
358 }
359 }
360 return x;
361}
362
Thomas Hellera4ea6032003-04-17 18:55:45 +0000363/* Get a C unsigned long int from a long int object, ignoring the high bits.
364 Returns -1 and sets an error condition if an error occurs. */
365
366unsigned long
367PyLong_AsUnsignedLongMask(PyObject *vv)
368{
369 register PyLongObject *v;
370 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000371 Py_ssize_t i;
372 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000373
374 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000375 if (vv != NULL && PyInt_Check(vv))
376 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000377 PyErr_BadInternalCall();
378 return (unsigned long) -1;
379 }
380 v = (PyLongObject *)vv;
381 i = v->ob_size;
382 sign = 1;
383 x = 0;
384 if (i < 0) {
385 sign = -1;
386 i = -i;
387 }
388 while (--i >= 0) {
Mark Dickinson71adc932009-09-28 16:52:40 +0000389 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000390 }
391 return x * sign;
392}
393
Tim Peters5b8132f2003-01-31 15:52:05 +0000394int
395_PyLong_Sign(PyObject *vv)
396{
397 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000398
399 assert(v != NULL);
400 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000401
Christian Heimese93237d2007-12-19 02:37:44 +0000402 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000403}
404
Tim Petersbaefd9e2003-01-28 20:37:45 +0000405size_t
406_PyLong_NumBits(PyObject *vv)
407{
408 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000409 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000410 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000411
412 assert(v != NULL);
413 assert(PyLong_Check(v));
Christian Heimese93237d2007-12-19 02:37:44 +0000414 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000415 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
416 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000417 digit msd = v->ob_digit[ndigits - 1];
418
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000419 result = (ndigits - 1) * PyLong_SHIFT;
420 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000421 goto Overflow;
422 do {
423 ++result;
424 if (result == 0)
425 goto Overflow;
426 msd >>= 1;
427 } while (msd);
428 }
429 return result;
430
431Overflow:
432 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
433 "to express in a platform size_t");
434 return (size_t)-1;
435}
436
Tim Peters2a9b3672001-06-11 21:23:58 +0000437PyObject *
438_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
439 int little_endian, int is_signed)
440{
441 const unsigned char* pstartbyte;/* LSB of bytes */
442 int incr; /* direction to move pstartbyte */
443 const unsigned char* pendbyte; /* MSB of bytes */
444 size_t numsignificantbytes; /* number of bytes that matter */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000445 Py_ssize_t ndigits; /* number of Python long digits */
Tim Peters2a9b3672001-06-11 21:23:58 +0000446 PyLongObject* v; /* result */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000447 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000448
449 if (n == 0)
450 return PyLong_FromLong(0L);
451
452 if (little_endian) {
453 pstartbyte = bytes;
454 pendbyte = bytes + n - 1;
455 incr = 1;
456 }
457 else {
458 pstartbyte = bytes + n - 1;
459 pendbyte = bytes;
460 incr = -1;
461 }
462
463 if (is_signed)
464 is_signed = *pendbyte >= 0x80;
465
466 /* Compute numsignificantbytes. This consists of finding the most
467 significant byte. Leading 0 bytes are insignficant if the number
468 is positive, and leading 0xff bytes if negative. */
469 {
470 size_t i;
471 const unsigned char* p = pendbyte;
472 const int pincr = -incr; /* search MSB to LSB */
473 const unsigned char insignficant = is_signed ? 0xff : 0x00;
474
475 for (i = 0; i < n; ++i, p += pincr) {
476 if (*p != insignficant)
477 break;
478 }
479 numsignificantbytes = n - i;
480 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
481 actually has 2 significant bytes. OTOH, 0xff0001 ==
482 -0x00ffff, so we wouldn't *need* to bump it there; but we
483 do for 0xffff = -0x0001. To be safe without bothering to
484 check every case, bump it regardless. */
485 if (is_signed && numsignificantbytes < n)
486 ++numsignificantbytes;
487 }
488
489 /* How many Python long digits do we need? We have
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000490 8*numsignificantbytes bits, and each Python long digit has
491 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
492 /* catch overflow before it happens */
493 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
494 PyErr_SetString(PyExc_OverflowError,
495 "byte array too long to convert to int");
496 return NULL;
497 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000498 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000499 v = _PyLong_New(ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000500 if (v == NULL)
501 return NULL;
502
503 /* Copy the bits over. The tricky parts are computing 2's-comp on
504 the fly for signed numbers, and dealing with the mismatch between
505 8-bit bytes and (probably) 15-bit Python digits.*/
506 {
507 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000508 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000509 twodigits accum = 0; /* sliding register */
510 unsigned int accumbits = 0; /* number of bits in accum */
511 const unsigned char* p = pstartbyte;
512
513 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000514 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000515 /* Compute correction for 2's comp, if needed. */
516 if (is_signed) {
517 thisbyte = (0xff ^ thisbyte) + carry;
518 carry = thisbyte >> 8;
519 thisbyte &= 0xff;
520 }
521 /* Because we're going LSB to MSB, thisbyte is
522 more significant than what's already in accum,
523 so needs to be prepended to accum. */
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000524 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000525 accumbits += 8;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000526 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000527 /* There's enough to fill a Python digit. */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000528 assert(idigit < ndigits);
529 v->ob_digit[idigit] = (digit)(accum &
530 PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000531 ++idigit;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000532 accum >>= PyLong_SHIFT;
533 accumbits -= PyLong_SHIFT;
534 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000535 }
536 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000537 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000538 if (accumbits) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000539 assert(idigit < ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000540 v->ob_digit[idigit] = (digit)accum;
541 ++idigit;
542 }
543 }
544
Christian Heimese93237d2007-12-19 02:37:44 +0000545 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000546 return (PyObject *)long_normalize(v);
547}
548
549int
550_PyLong_AsByteArray(PyLongObject* v,
551 unsigned char* bytes, size_t n,
552 int little_endian, int is_signed)
553{
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000554 Py_ssize_t i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000555 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000556 twodigits accum; /* sliding register */
557 unsigned int accumbits; /* # bits in accum */
558 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
Mark Dickinson1afe6dd2009-01-25 22:12:31 +0000559 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000560 size_t j; /* # bytes filled */
561 unsigned char* p; /* pointer to next byte in bytes */
562 int pincr; /* direction to move p */
563
564 assert(v != NULL && PyLong_Check(v));
565
Christian Heimese93237d2007-12-19 02:37:44 +0000566 if (Py_SIZE(v) < 0) {
567 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000568 if (!is_signed) {
Mark Dickinson4015f622009-02-10 15:46:50 +0000569 PyErr_SetString(PyExc_OverflowError,
Tim Peters2a9b3672001-06-11 21:23:58 +0000570 "can't convert negative long to unsigned");
571 return -1;
572 }
573 do_twos_comp = 1;
574 }
575 else {
Christian Heimese93237d2007-12-19 02:37:44 +0000576 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000577 do_twos_comp = 0;
578 }
579
580 if (little_endian) {
581 p = bytes;
582 pincr = 1;
583 }
584 else {
585 p = bytes + n - 1;
586 pincr = -1;
587 }
588
Tim Peters898cf852001-06-13 20:50:08 +0000589 /* Copy over all the Python digits.
590 It's crucial that every Python digit except for the MSD contribute
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000591 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000592 normalized. */
593 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000594 j = 0;
595 accum = 0;
596 accumbits = 0;
597 carry = do_twos_comp ? 1 : 0;
598 for (i = 0; i < ndigits; ++i) {
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000599 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000600 if (do_twos_comp) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000601 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
602 carry = thisdigit >> PyLong_SHIFT;
603 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000604 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000605 /* Because we're going LSB to MSB, thisdigit is more
606 significant than what's already in accum, so needs to be
607 prepended to accum. */
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000608 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000609
Tim Petersede05092001-06-14 08:53:38 +0000610 /* The most-significant digit may be (probably is) at least
611 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000612 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000613 /* Count # of sign bits -- they needn't be stored,
614 * although for signed conversion we need later to
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000615 * make sure at least one sign bit gets stored. */
616 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
617 thisdigit;
618 while (s != 0) {
619 s >>= 1;
620 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000621 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000622 }
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000623 else
624 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000625
Tim Peters2a9b3672001-06-11 21:23:58 +0000626 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000627 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000628 if (j >= n)
629 goto Overflow;
630 ++j;
631 *p = (unsigned char)(accum & 0xff);
632 p += pincr;
633 accumbits -= 8;
634 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000635 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000636 }
637
638 /* Store the straggler (if any). */
639 assert(accumbits < 8);
640 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000641 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000642 if (j >= n)
643 goto Overflow;
644 ++j;
645 if (do_twos_comp) {
646 /* Fill leading bits of the byte with sign bits
647 (appropriately pretending that the long had an
648 infinite supply of sign bits). */
649 accum |= (~(twodigits)0) << accumbits;
650 }
651 *p = (unsigned char)(accum & 0xff);
652 p += pincr;
653 }
Tim Peters05607ad2001-06-13 21:01:27 +0000654 else if (j == n && n > 0 && is_signed) {
655 /* The main loop filled the byte array exactly, so the code
656 just above didn't get to ensure there's a sign bit, and the
657 loop below wouldn't add one either. Make sure a sign bit
658 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000659 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000660 int sign_bit_set = msb >= 0x80;
661 assert(accumbits == 0);
662 if (sign_bit_set == do_twos_comp)
663 return 0;
664 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000665 goto Overflow;
666 }
Tim Peters05607ad2001-06-13 21:01:27 +0000667
668 /* Fill remaining bytes with copies of the sign bit. */
669 {
670 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
671 for ( ; j < n; ++j, p += pincr)
672 *p = signbyte;
673 }
674
Tim Peters2a9b3672001-06-11 21:23:58 +0000675 return 0;
676
677Overflow:
678 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
679 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000680
Tim Peters2a9b3672001-06-11 21:23:58 +0000681}
682
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000683double
684_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
685{
686/* NBITS_WANTED should be > the number of bits in a double's precision,
687 but small enough so that 2**NBITS_WANTED is within the normal double
688 range. nbitsneeded is set to 1 less than that because the most-significant
689 Python digit contains at least 1 significant bit, but we don't want to
690 bother counting them (catering to the worst case cheaply).
691
692 57 is one more than VAX-D double precision; I (Tim) don't know of a double
693 format with more precision than that; it's 1 larger so that we add in at
694 least one round bit to stand in for the ignored least-significant bits.
695*/
696#define NBITS_WANTED 57
697 PyLongObject *v;
698 double x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000699 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000700 Py_ssize_t i;
701 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000702 int nbitsneeded;
703
704 if (vv == NULL || !PyLong_Check(vv)) {
705 PyErr_BadInternalCall();
706 return -1;
707 }
708 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000709 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000710 sign = 1;
711 if (i < 0) {
712 sign = -1;
713 i = -(i);
714 }
715 else if (i == 0) {
716 *exponent = 0;
717 return 0.0;
718 }
719 --i;
720 x = (double)v->ob_digit[i];
721 nbitsneeded = NBITS_WANTED - 1;
722 /* Invariant: i Python digits remain unaccounted for. */
723 while (i > 0 && nbitsneeded > 0) {
724 --i;
725 x = x * multiplier + (double)v->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000726 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000727 }
728 /* There are i digits we didn't shift in. Pretending they're all
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000729 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000730 *exponent = i;
731 assert(x > 0.0);
732 return x * sign;
733#undef NBITS_WANTED
734}
735
Mark Dickinson6736cf82009-04-20 21:13:33 +0000736/* Get a C double from a long int object. Rounds to the nearest double,
737 using the round-half-to-even rule in the case of a tie. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000738
739double
Tim Peters9f688bf2000-07-07 15:53:28 +0000740PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000741{
Mark Dickinson6736cf82009-04-20 21:13:33 +0000742 PyLongObject *v = (PyLongObject *)vv;
743 Py_ssize_t rnd_digit, rnd_bit, m, n;
744 digit lsb, *d;
745 int round_up = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000746 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000747
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000748 if (vv == NULL || !PyLong_Check(vv)) {
749 PyErr_BadInternalCall();
Tim Peters9fffa3e2001-09-04 05:14:19 +0000750 return -1.0;
Mark Dickinson6736cf82009-04-20 21:13:33 +0000751 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000752
Mark Dickinson6736cf82009-04-20 21:13:33 +0000753 /* Notes on the method: for simplicity, assume v is positive and >=
754 2**DBL_MANT_DIG. (For negative v we just ignore the sign until the
755 end; for small v no rounding is necessary.) Write n for the number
756 of bits in v, so that 2**(n-1) <= v < 2**n, and n > DBL_MANT_DIG.
757
758 Some terminology: the *rounding bit* of v is the 1st bit of v that
759 will be rounded away (bit n - DBL_MANT_DIG - 1); the *parity bit*
760 is the bit immediately above. The round-half-to-even rule says
761 that we round up if the rounding bit is set, unless v is exactly
762 halfway between two floats and the parity bit is zero.
763
764 Write d[0] ... d[m] for the digits of v, least to most significant.
765 Let rnd_bit be the index of the rounding bit, and rnd_digit the
766 index of the PyLong digit containing the rounding bit. Then the
767 bits of the digit d[rnd_digit] look something like:
768
769 rounding bit
770 |
771 v
772 msb -> sssssrttttttttt <- lsb
773 ^
774 |
775 parity bit
776
777 where 's' represents a 'significant bit' that will be included in
778 the mantissa of the result, 'r' is the rounding bit, and 't'
779 represents a 'trailing bit' following the rounding bit. Note that
780 if the rounding bit is at the top of d[rnd_digit] then the parity
781 bit will be the lsb of d[rnd_digit+1]. If we set
782
783 lsb = 1 << (rnd_bit % PyLong_SHIFT)
784
785 then d[rnd_digit] & (PyLong_BASE - 2*lsb) selects just the
786 significant bits of d[rnd_digit], d[rnd_digit] & (lsb-1) gets the
787 trailing bits, and d[rnd_digit] & lsb gives the rounding bit.
788
789 We initialize the double x to the integer given by digits
790 d[rnd_digit:m-1], but with the rounding bit and trailing bits of
791 d[rnd_digit] masked out. So the value of x comes from the top
792 DBL_MANT_DIG bits of v, multiplied by 2*lsb. Note that in the loop
793 that produces x, all floating-point operations are exact (assuming
794 that FLT_RADIX==2). Now if we're rounding down, the value we want
795 to return is simply
796
797 x * 2**(PyLong_SHIFT * rnd_digit).
798
799 and if we're rounding up, it's
800
801 (x + 2*lsb) * 2**(PyLong_SHIFT * rnd_digit).
802
803 Under the round-half-to-even rule, we round up if, and only
804 if, the rounding bit is set *and* at least one of the
805 following three conditions is satisfied:
806
807 (1) the parity bit is set, or
808 (2) at least one of the trailing bits of d[rnd_digit] is set, or
809 (3) at least one of the digits d[i], 0 <= i < rnd_digit
810 is nonzero.
811
812 Finally, we have to worry about overflow. If v >= 2**DBL_MAX_EXP,
813 or equivalently n > DBL_MAX_EXP, then overflow occurs. If v <
814 2**DBL_MAX_EXP then we're usually safe, but there's a corner case
815 to consider: if v is very close to 2**DBL_MAX_EXP then it's
816 possible that v is rounded up to exactly 2**DBL_MAX_EXP, and then
817 again overflow occurs.
818 */
819
820 if (Py_SIZE(v) == 0)
821 return 0.0;
822 m = ABS(Py_SIZE(v)) - 1;
823 d = v->ob_digit;
824 assert(d[m]); /* v should be normalized */
825
826 /* fast path for case where 0 < abs(v) < 2**DBL_MANT_DIG */
827 if (m < DBL_MANT_DIG / PyLong_SHIFT ||
828 (m == DBL_MANT_DIG / PyLong_SHIFT &&
829 d[m] < (digit)1 << DBL_MANT_DIG%PyLong_SHIFT)) {
830 x = d[m];
831 while (--m >= 0)
832 x = x*PyLong_BASE + d[m];
833 return Py_SIZE(v) < 0 ? -x : x;
834 }
835
836 /* if m is huge then overflow immediately; otherwise, compute the
837 number of bits n in v. The condition below implies n (= #bits) >=
838 m * PyLong_SHIFT + 1 > DBL_MAX_EXP, hence v >= 2**DBL_MAX_EXP. */
839 if (m > (DBL_MAX_EXP-1)/PyLong_SHIFT)
840 goto overflow;
841 n = m * PyLong_SHIFT + bits_in_digit(d[m]);
842 if (n > DBL_MAX_EXP)
843 goto overflow;
844
845 /* find location of rounding bit */
846 assert(n > DBL_MANT_DIG); /* dealt with |v| < 2**DBL_MANT_DIG above */
847 rnd_bit = n - DBL_MANT_DIG - 1;
848 rnd_digit = rnd_bit/PyLong_SHIFT;
849 lsb = (digit)1 << (rnd_bit%PyLong_SHIFT);
850
851 /* Get top DBL_MANT_DIG bits of v. Assumes PyLong_SHIFT <
852 DBL_MANT_DIG, so we'll need bits from at least 2 digits of v. */
853 x = d[m];
854 assert(m > rnd_digit);
855 while (--m > rnd_digit)
856 x = x*PyLong_BASE + d[m];
857 x = x*PyLong_BASE + (d[m] & (PyLong_BASE-2*lsb));
858
859 /* decide whether to round up, using round-half-to-even */
860 assert(m == rnd_digit);
861 if (d[m] & lsb) { /* if (rounding bit is set) */
862 digit parity_bit;
863 if (lsb == PyLong_BASE/2)
864 parity_bit = d[m+1] & 1;
865 else
866 parity_bit = d[m] & 2*lsb;
867 if (parity_bit)
868 round_up = 1;
869 else if (d[m] & (lsb-1))
870 round_up = 1;
871 else {
872 while (--m >= 0) {
873 if (d[m]) {
874 round_up = 1;
875 break;
876 }
877 }
878 }
879 }
880
881 /* and round up if necessary */
882 if (round_up) {
883 x += 2*lsb;
884 if (n == DBL_MAX_EXP &&
885 x == ldexp((double)(2*lsb), DBL_MANT_DIG)) {
886 /* overflow corner case */
887 goto overflow;
888 }
889 }
890
891 /* shift, adjust for sign, and return */
892 x = ldexp(x, rnd_digit*PyLong_SHIFT);
893 return Py_SIZE(v) < 0 ? -x : x;
894
895 overflow:
Tim Peters9fffa3e2001-09-04 05:14:19 +0000896 PyErr_SetString(PyExc_OverflowError,
897 "long int too large to convert to float");
898 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000899}
900
Guido van Rossum78694d91998-09-18 14:14:13 +0000901/* Create a new long (or int) object from a C pointer */
902
903PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000904PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000905{
Tim Peters70128a12001-06-16 08:48:40 +0000906#if SIZEOF_VOID_P <= SIZEOF_LONG
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000907 if ((long)p < 0)
908 return PyLong_FromUnsignedLong((unsigned long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000909 return PyInt_FromLong((long)p);
910#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000911
Tim Peters70128a12001-06-16 08:48:40 +0000912#ifndef HAVE_LONG_LONG
913# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
914#endif
915#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000916# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000917#endif
918 /* optimize null pointers */
919 if (p == NULL)
920 return PyInt_FromLong(0);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000921 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000922
923#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000924}
925
926/* Get a C pointer from a long object (or an int object in some cases) */
927
928void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000929PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000930{
931 /* This function will allow int or long objects. If vv is neither,
932 then the PyLong_AsLong*() functions will raise the exception:
933 PyExc_SystemError, "bad argument to internal function"
934 */
Tim Peters70128a12001-06-16 08:48:40 +0000935#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000936 long x;
937
Tim Peters70128a12001-06-16 08:48:40 +0000938 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000939 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000940 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000941 x = PyLong_AsLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000942 else
943 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000944#else
Tim Peters70128a12001-06-16 08:48:40 +0000945
946#ifndef HAVE_LONG_LONG
947# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
948#endif
949#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000950# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000951#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000952 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000953
Tim Peters70128a12001-06-16 08:48:40 +0000954 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000955 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000956 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000957 x = PyLong_AsLongLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000958 else
959 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000960
961#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000962
963 if (x == -1 && PyErr_Occurred())
964 return NULL;
965 return (void *)x;
966}
967
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000968#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000969
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000970/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000971 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000972 */
973
Tim Peterscf37dfc2001-06-14 18:42:50 +0000974#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000975
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000976/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000977
978PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000979PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000980{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000981 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000982 unsigned PY_LONG_LONG abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000983 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
984 int ndigits = 0;
985 int negative = 0;
986
987 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000988 /* avoid signed overflow on negation; see comments
989 in PyLong_FromLong above. */
990 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000991 negative = 1;
992 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000993 else {
994 abs_ival = (unsigned PY_LONG_LONG)ival;
995 }
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000996
997 /* Count the number of Python digits.
998 We used to pick 5 ("big enough for anything"), but that's a
999 waste of time and space given that 5*15 = 75 bits are rarely
1000 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +00001001 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +00001002 while (t) {
1003 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001004 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +00001005 }
1006 v = _PyLong_New(ndigits);
1007 if (v != NULL) {
1008 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +00001009 Py_SIZE(v) = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +00001010 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +00001011 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001012 *p++ = (digit)(t & PyLong_MASK);
1013 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +00001014 }
1015 }
1016 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001017}
1018
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001019/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001020
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001021PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001022PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001023{
Bob Ippolitoa85bf202006-05-25 18:20:23 +00001024 PyLongObject *v;
1025 unsigned PY_LONG_LONG t;
1026 int ndigits = 0;
1027
1028 /* Count the number of Python digits. */
1029 t = (unsigned PY_LONG_LONG)ival;
1030 while (t) {
1031 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001032 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +00001033 }
1034 v = _PyLong_New(ndigits);
1035 if (v != NULL) {
1036 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +00001037 Py_SIZE(v) = ndigits;
Bob Ippolitoa85bf202006-05-25 18:20:23 +00001038 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001039 *p++ = (digit)(ival & PyLong_MASK);
1040 ival >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +00001041 }
1042 }
1043 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001044}
1045
Martin v. Löwis18e16552006-02-15 17:27:45 +00001046/* Create a new long int object from a C Py_ssize_t. */
1047
1048PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001049PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001050{
1051 Py_ssize_t bytes = ival;
1052 int one = 1;
1053 return _PyLong_FromByteArray(
1054 (unsigned char *)&bytes,
Kristján Valur Jónssonf0303942007-05-03 20:27:03 +00001055 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001056}
1057
1058/* Create a new long int object from a C size_t. */
1059
1060PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001061PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001062{
1063 size_t bytes = ival;
1064 int one = 1;
1065 return _PyLong_FromByteArray(
1066 (unsigned char *)&bytes,
1067 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
1068}
1069
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001070/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001071 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001072
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001073PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001074PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001075{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001076 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001077 int one = 1;
1078 int res;
1079
Tim Petersd38b1c72001-09-30 05:09:37 +00001080 if (vv == NULL) {
1081 PyErr_BadInternalCall();
1082 return -1;
1083 }
1084 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001085 PyNumberMethods *nb;
1086 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +00001087 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001088 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001089 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1090 nb->nb_int == NULL) {
1091 PyErr_SetString(PyExc_TypeError, "an integer is required");
1092 return -1;
1093 }
1094 io = (*nb->nb_int) (vv);
1095 if (io == NULL)
1096 return -1;
1097 if (PyInt_Check(io)) {
1098 bytes = PyInt_AsLong(io);
1099 Py_DECREF(io);
1100 return bytes;
1101 }
1102 if (PyLong_Check(io)) {
1103 bytes = PyLong_AsLongLong(io);
1104 Py_DECREF(io);
1105 return bytes;
1106 }
1107 Py_DECREF(io);
1108 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001109 return -1;
1110 }
1111
Tim Petersd1a7da62001-06-13 00:35:57 +00001112 res = _PyLong_AsByteArray(
1113 (PyLongObject *)vv, (unsigned char *)&bytes,
1114 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001115
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001116 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001117 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001118 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001119 else
1120 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001121}
1122
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001123/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001124 Return -1 and set an error if overflow occurs. */
1125
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001126unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001127PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001128{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001129 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001130 int one = 1;
1131 int res;
1132
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001133 if (vv == NULL || !PyLong_Check(vv)) {
1134 PyErr_BadInternalCall();
Skip Montanaro429433b2006-04-18 00:35:43 +00001135 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001136 }
1137
Tim Petersd1a7da62001-06-13 00:35:57 +00001138 res = _PyLong_AsByteArray(
1139 (PyLongObject *)vv, (unsigned char *)&bytes,
1140 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001141
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001142 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001143 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001144 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001145 else
1146 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001147}
Tim Petersd1a7da62001-06-13 00:35:57 +00001148
Thomas Hellera4ea6032003-04-17 18:55:45 +00001149/* Get a C unsigned long int from a long int object, ignoring the high bits.
1150 Returns -1 and sets an error condition if an error occurs. */
1151
1152unsigned PY_LONG_LONG
1153PyLong_AsUnsignedLongLongMask(PyObject *vv)
1154{
1155 register PyLongObject *v;
1156 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001157 Py_ssize_t i;
1158 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001159
1160 if (vv == NULL || !PyLong_Check(vv)) {
1161 PyErr_BadInternalCall();
1162 return (unsigned long) -1;
1163 }
1164 v = (PyLongObject *)vv;
1165 i = v->ob_size;
1166 sign = 1;
1167 x = 0;
1168 if (i < 0) {
1169 sign = -1;
1170 i = -i;
1171 }
1172 while (--i >= 0) {
Mark Dickinson71adc932009-09-28 16:52:40 +00001173 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001174 }
1175 return x * sign;
1176}
Tim Petersd1a7da62001-06-13 00:35:57 +00001177#undef IS_LITTLE_ENDIAN
1178
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001179#endif /* HAVE_LONG_LONG */
1180
Neil Schemenauerba872e22001-01-04 01:46:03 +00001181
1182static int
1183convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001184 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001185 *a = (PyLongObject *) v;
1186 Py_INCREF(v);
1187 }
1188 else if (PyInt_Check(v)) {
1189 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1190 }
1191 else {
1192 return 0;
1193 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001194 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001195 *b = (PyLongObject *) w;
1196 Py_INCREF(w);
1197 }
1198 else if (PyInt_Check(w)) {
1199 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1200 }
1201 else {
1202 Py_DECREF(*a);
1203 return 0;
1204 }
1205 return 1;
1206}
1207
1208#define CONVERT_BINOP(v, w, a, b) \
1209 if (!convert_binop(v, w, a, b)) { \
1210 Py_INCREF(Py_NotImplemented); \
1211 return Py_NotImplemented; \
1212 }
1213
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001214/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1215 2**k if d is nonzero, else 0. */
1216
1217static const unsigned char BitLengthTable[32] = {
1218 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1219 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1220};
1221
1222static int
1223bits_in_digit(digit d)
1224{
1225 int d_bits = 0;
1226 while (d >= 32) {
1227 d_bits += 6;
1228 d >>= 6;
1229 }
1230 d_bits += (int)BitLengthTable[d];
1231 return d_bits;
1232}
1233
Tim Peters877a2122002-08-12 05:09:36 +00001234/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1235 * is modified in place, by adding y to it. Carries are propagated as far as
1236 * x[m-1], and the remaining carry (0 or 1) is returned.
1237 */
1238static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001239v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001240{
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001241 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001242 digit carry = 0;
1243
1244 assert(m >= n);
1245 for (i = 0; i < n; ++i) {
1246 carry += x[i] + y[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001247 x[i] = carry & PyLong_MASK;
1248 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001249 assert((carry & 1) == carry);
1250 }
1251 for (; carry && i < m; ++i) {
1252 carry += x[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001253 x[i] = carry & PyLong_MASK;
1254 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001255 assert((carry & 1) == carry);
1256 }
1257 return carry;
1258}
1259
1260/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1261 * is modified in place, by subtracting y from it. Borrows are propagated as
1262 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1263 */
1264static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001265v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001266{
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001267 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001268 digit borrow = 0;
1269
1270 assert(m >= n);
1271 for (i = 0; i < n; ++i) {
1272 borrow = x[i] - y[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001273 x[i] = borrow & PyLong_MASK;
1274 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001275 borrow &= 1; /* keep only 1 sign bit */
1276 }
1277 for (; borrow && i < m; ++i) {
1278 borrow = x[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001279 x[i] = borrow & PyLong_MASK;
1280 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001281 borrow &= 1;
1282 }
1283 return borrow;
1284}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001285
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001286/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1287 * result in z[0:m], and return the d bits shifted out of the top.
1288 */
1289static digit
1290v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001291{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001292 Py_ssize_t i;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001293 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001294
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001295 assert(0 <= d && d < PyLong_SHIFT);
1296 for (i=0; i < m; i++) {
1297 twodigits acc = (twodigits)a[i] << d | carry;
1298 z[i] = (digit)acc & PyLong_MASK;
1299 carry = (digit)(acc >> PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001300 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00001301 return carry;
1302}
1303
1304/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1305 * result in z[0:m], and return the d bits shifted out of the bottom.
1306 */
1307static digit
1308v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1309{
1310 Py_ssize_t i;
1311 digit carry = 0;
1312 digit mask = ((digit)1 << d) - 1U;
1313
1314 assert(0 <= d && d < PyLong_SHIFT);
1315 for (i=m; i-- > 0;) {
1316 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1317 carry = (digit)acc & mask;
1318 z[i] = (digit)(acc >> d);
1319 }
1320 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001321}
1322
Tim Peters212e6142001-07-14 12:23:19 +00001323/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1324 in pout, and returning the remainder. pin and pout point at the LSD.
1325 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Eric Smith5e527eb2008-02-10 01:36:53 +00001326 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001327 immutable. */
1328
1329static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001330inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001331{
1332 twodigits rem = 0;
1333
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001334 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001335 pin += size;
1336 pout += size;
1337 while (--size >= 0) {
1338 digit hi;
Mark Dickinson71adc932009-09-28 16:52:40 +00001339 rem = (rem << PyLong_SHIFT) | *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001340 *--pout = hi = (digit)(rem / n);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001341 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001342 }
1343 return (digit)rem;
1344}
1345
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001346/* Divide a long integer by a digit, returning both the quotient
1347 (as function result) and the remainder (through *prem).
1348 The sign of a is ignored; n should not be zero. */
1349
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001350static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001351divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001352{
Christian Heimese93237d2007-12-19 02:37:44 +00001353 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001354 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001355
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001356 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001357 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001358 if (z == NULL)
1359 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001360 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001361 return long_normalize(z);
1362}
1363
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001364/* Convert a long integer to a base 10 string. Returns a new non-shared
1365 string. (Return value is non-shared so that callers can modify the
1366 returned value if necessary.) */
1367
1368static PyObject *
1369long_to_decimal_string(PyObject *aa, int addL)
1370{
1371 PyLongObject *scratch, *a;
1372 PyObject *str;
1373 Py_ssize_t size, strlen, size_a, i, j;
1374 digit *pout, *pin, rem, tenpow;
1375 char *p;
1376 int negative;
1377
1378 a = (PyLongObject *)aa;
1379 if (a == NULL || !PyLong_Check(a)) {
1380 PyErr_BadInternalCall();
1381 return NULL;
1382 }
1383 size_a = ABS(Py_SIZE(a));
1384 negative = Py_SIZE(a) < 0;
1385
1386 /* quick and dirty upper bound for the number of digits
1387 required to express a in base _PyLong_DECIMAL_BASE:
1388
1389 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1390
1391 But log2(a) < size_a * PyLong_SHIFT, and
1392 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1393 > 3 * _PyLong_DECIMAL_SHIFT
1394 */
1395 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1396 PyErr_SetString(PyExc_OverflowError,
1397 "long is too large to format");
1398 return NULL;
1399 }
1400 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1401 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1402 scratch = _PyLong_New(size);
1403 if (scratch == NULL)
1404 return NULL;
1405
1406 /* convert array of base _PyLong_BASE digits in pin to an array of
1407 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1408 Volume 2 (3rd edn), section 4.4, Method 1b). */
1409 pin = a->ob_digit;
1410 pout = scratch->ob_digit;
1411 size = 0;
1412 for (i = size_a; --i >= 0; ) {
1413 digit hi = pin[i];
1414 for (j = 0; j < size; j++) {
1415 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
Mark Dickinson40ee8612009-09-21 16:16:44 +00001416 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1417 pout[j] = (digit)(z - (twodigits)hi *
1418 _PyLong_DECIMAL_BASE);
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001419 }
1420 while (hi) {
1421 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1422 hi /= _PyLong_DECIMAL_BASE;
1423 }
1424 /* check for keyboard interrupt */
1425 SIGCHECK({
1426 Py_DECREF(scratch);
1427 return NULL;
1428 })
1429 }
1430 /* pout should have at least one digit, so that the case when a = 0
1431 works correctly */
1432 if (size == 0)
1433 pout[size++] = 0;
1434
1435 /* calculate exact length of output string, and allocate */
1436 strlen = (addL != 0) + negative +
1437 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1438 tenpow = 10;
1439 rem = pout[size-1];
1440 while (rem >= tenpow) {
1441 tenpow *= 10;
1442 strlen++;
1443 }
1444 str = PyString_FromStringAndSize(NULL, strlen);
1445 if (str == NULL) {
1446 Py_DECREF(scratch);
1447 return NULL;
1448 }
1449
1450 /* fill the string right-to-left */
1451 p = PyString_AS_STRING(str) + strlen;
1452 *p = '\0';
1453 if (addL)
1454 *--p = 'L';
1455 /* pout[0] through pout[size-2] contribute exactly
1456 _PyLong_DECIMAL_SHIFT digits each */
1457 for (i=0; i < size - 1; i++) {
1458 rem = pout[i];
1459 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1460 *--p = '0' + rem % 10;
1461 rem /= 10;
1462 }
1463 }
1464 /* pout[size-1]: always produce at least one decimal digit */
1465 rem = pout[i];
1466 do {
1467 *--p = '0' + rem % 10;
1468 rem /= 10;
1469 } while (rem != 0);
1470
1471 /* and sign */
1472 if (negative)
1473 *--p = '-';
1474
1475 /* check we've counted correctly */
1476 assert(p == PyString_AS_STRING(str));
1477 Py_DECREF(scratch);
1478 return (PyObject *)str;
1479}
1480
Eric Smith5e527eb2008-02-10 01:36:53 +00001481/* Convert the long to a string object with given base,
1482 appending a base prefix of 0[box] if base is 2, 8 or 16.
1483 Add a trailing "L" if addL is non-zero.
1484 If newstyle is zero, then use the pre-2.6 behavior of octal having
1485 a leading "0", instead of the prefix "0o" */
1486PyAPI_FUNC(PyObject *)
1487_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001488{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001489 register PyLongObject *a = (PyLongObject *)aa;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001490 PyStringObject *str;
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001491 Py_ssize_t i, sz;
Neal Norwitzc09efa82006-07-23 07:53:14 +00001492 Py_ssize_t size_a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001493 char *p;
1494 int bits;
1495 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001496
Mark Dickinsonaa2adc82009-09-16 22:10:56 +00001497 if (base == 10)
1498 return long_to_decimal_string((PyObject *)a, addL);
1499
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001500 if (a == NULL || !PyLong_Check(a)) {
1501 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001502 return NULL;
1503 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001504 assert(base >= 2 && base <= 36);
Christian Heimese93237d2007-12-19 02:37:44 +00001505 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001506
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001507 /* Compute a rough upper bound for the length of the string */
1508 i = base;
1509 bits = 0;
1510 while (i > 1) {
1511 ++bits;
1512 i >>= 1;
1513 }
Armin Rigo7ccbca92006-10-04 12:17:45 +00001514 i = 5 + (addL ? 1 : 0);
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001515 /* ensure we don't get signed overflow in sz calculation */
1516 if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00001517 PyErr_SetString(PyExc_OverflowError,
1518 "long is too large to format");
1519 return NULL;
1520 }
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001521 sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
1522 assert(sz >= 0);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001523 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001524 if (str == NULL)
1525 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001526 p = PyString_AS_STRING(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001527 *p = '\0';
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001528 if (addL)
1529 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001530 if (a->ob_size < 0)
1531 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001532
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001533 if (a->ob_size == 0) {
1534 *--p = '0';
1535 }
1536 else if ((base & (base - 1)) == 0) {
1537 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001538 twodigits accum = 0;
1539 int accumbits = 0; /* # of bits in accum */
1540 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001541 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001542 while ((i >>= 1) > 1)
1543 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001544
1545 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001546 accum |= (twodigits)a->ob_digit[i] << accumbits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001547 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001548 assert(accumbits >= basebits);
1549 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001550 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001551 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001552 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001553 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001554 accumbits -= basebits;
1555 accum >>= basebits;
1556 } while (i < size_a-1 ? accumbits >= basebits :
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001557 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001558 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001559 }
1560 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001561 /* Not 0, and base not a power of 2. Divide repeatedly by
1562 base, but for speed use the highest power of base that
1563 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001564 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001565 digit *pin = a->ob_digit;
1566 PyLongObject *scratch;
1567 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001568 digit powbase = base; /* powbase == base ** power */
1569 int power = 1;
1570 for (;;) {
Mark Dickinsonb6464872009-02-25 20:29:50 +00001571 twodigits newpow = powbase * (twodigits)base;
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001572 if (newpow >> PyLong_SHIFT)
1573 /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001574 break;
1575 powbase = (digit)newpow;
1576 ++power;
1577 }
Tim Peters212e6142001-07-14 12:23:19 +00001578
1579 /* Get a scratch area for repeated division. */
1580 scratch = _PyLong_New(size);
1581 if (scratch == NULL) {
1582 Py_DECREF(str);
1583 return NULL;
1584 }
1585
1586 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001587 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001588 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001589 digit rem = inplace_divrem1(scratch->ob_digit,
1590 pin, size, powbase);
1591 pin = scratch->ob_digit; /* no need to use a again */
1592 if (pin[size - 1] == 0)
1593 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001594 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001595 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001596 Py_DECREF(str);
1597 return NULL;
1598 })
Tim Peters212e6142001-07-14 12:23:19 +00001599
1600 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001601 assert(ntostore > 0);
1602 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001603 digit nextrem = (digit)(rem / base);
1604 char c = (char)(rem - nextrem * base);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001605 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001606 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001607 *--p = c;
1608 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001609 --ntostore;
1610 /* Termination is a bit delicate: must not
1611 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001612 remaining quotient and rem are both 0. */
1613 } while (ntostore && (size || rem));
1614 } while (size != 0);
1615 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001616 }
1617
Eric Smith5e527eb2008-02-10 01:36:53 +00001618 if (base == 2) {
1619 *--p = 'b';
1620 *--p = '0';
1621 }
1622 else if (base == 8) {
Mark Dickinson1f4fc092009-09-13 11:56:13 +00001623 if (newstyle) {
Eric Smith5e527eb2008-02-10 01:36:53 +00001624 *--p = 'o';
Guido van Rossum2c475421992-08-14 15:13:07 +00001625 *--p = '0';
Eric Smith5e527eb2008-02-10 01:36:53 +00001626 }
1627 else
1628 if (size_a != 0)
1629 *--p = '0';
Guido van Rossum2c475421992-08-14 15:13:07 +00001630 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001631 else if (base == 16) {
1632 *--p = 'x';
1633 *--p = '0';
1634 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001635 else if (base != 10) {
1636 *--p = '#';
1637 *--p = '0' + base%10;
1638 if (base > 10)
1639 *--p = '0' + base/10;
1640 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001641 if (sign)
1642 *--p = sign;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001643 if (p != PyString_AS_STRING(str)) {
1644 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001645 assert(p > q);
1646 do {
1647 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001648 q--;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001649 _PyString_Resize((PyObject **)&str,
1650 (Py_ssize_t) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001651 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001652 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001653}
1654
Tim Petersda53afa2006-05-25 17:34:03 +00001655/* Table of digit values for 8-bit string -> integer conversion.
1656 * '0' maps to 0, ..., '9' maps to 9.
1657 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1658 * All other indices map to 37.
1659 * Note that when converting a base B string, a char c is a legitimate
1660 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1661 */
1662int _PyLong_DigitValue[256] = {
Tim Peters696cf432006-05-24 21:10:40 +00001663 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 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1667 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1668 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1669 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1670 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1671 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1672 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1673 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1674 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1675 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1676 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1677 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1678 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Tim Peters696cf432006-05-24 21:10:40 +00001679};
1680
1681/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001682 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1683 * non-digit (which may be *str!). A normalized long is returned.
1684 * The point to this routine is that it takes time linear in the number of
1685 * string characters.
1686 */
1687static PyLongObject *
1688long_from_binary_base(char **str, int base)
1689{
1690 char *p = *str;
1691 char *start = p;
1692 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001693 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001694 PyLongObject *z;
1695 twodigits accum;
1696 int bits_in_accum;
1697 digit *pdigit;
1698
1699 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1700 n = base;
1701 for (bits_per_char = -1; n; ++bits_per_char)
1702 n >>= 1;
1703 /* n <- total # of bits needed, while setting p to end-of-string */
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001704 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001705 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001706 *str = p;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001707 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1708 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001709 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001710 PyErr_SetString(PyExc_ValueError,
1711 "long string too large to convert");
1712 return NULL;
1713 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001714 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001715 z = _PyLong_New(n);
1716 if (z == NULL)
1717 return NULL;
1718 /* Read string from right, and fill in long from left; i.e.,
1719 * from least to most significant in both.
1720 */
1721 accum = 0;
1722 bits_in_accum = 0;
1723 pdigit = z->ob_digit;
1724 while (--p >= start) {
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001725 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001726 assert(k >= 0 && k < base);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001727 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001728 bits_in_accum += bits_per_char;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001729 if (bits_in_accum >= PyLong_SHIFT) {
1730 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001731 assert(pdigit - z->ob_digit <= n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001732 accum >>= PyLong_SHIFT;
1733 bits_in_accum -= PyLong_SHIFT;
1734 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001735 }
1736 }
1737 if (bits_in_accum) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001738 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001739 *pdigit++ = (digit)accum;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001740 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001741 }
1742 while (pdigit - z->ob_digit < n)
1743 *pdigit++ = 0;
1744 return long_normalize(z);
1745}
1746
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001747PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001748PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001749{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001750 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001751 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001752 PyLongObject *z;
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001753 PyObject *strobj, *strrepr;
1754 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001755
Guido van Rossum472c04f1996-12-05 21:57:21 +00001756 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001757 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001758 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001759 return NULL;
1760 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001761 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001762 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001763 if (*str == '+')
1764 ++str;
1765 else if (*str == '-') {
1766 ++str;
1767 sign = -1;
1768 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001769 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001770 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001771 if (base == 0) {
Eric Smith9ff19b52008-03-17 17:32:20 +00001772 /* No base given. Deduce the base from the contents
1773 of the string */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001774 if (str[0] != '0')
1775 base = 10;
1776 else if (str[1] == 'x' || str[1] == 'X')
1777 base = 16;
Eric Smith9ff19b52008-03-17 17:32:20 +00001778 else if (str[1] == 'o' || str[1] == 'O')
1779 base = 8;
1780 else if (str[1] == 'b' || str[1] == 'B')
1781 base = 2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001782 else
Eric Smith9ff19b52008-03-17 17:32:20 +00001783 /* "old" (C-style) octal literal, still valid in
1784 2.x, although illegal in 3.x */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001785 base = 8;
1786 }
Eric Smith9ff19b52008-03-17 17:32:20 +00001787 /* Whether or not we were deducing the base, skip leading chars
1788 as needed */
1789 if (str[0] == '0' &&
1790 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1791 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1792 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001793 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001794
Guido van Rossume6762971998-06-22 03:54:46 +00001795 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001796 if ((base & (base - 1)) == 0)
1797 z = long_from_binary_base(&str, base);
1798 else {
Tim Peters696cf432006-05-24 21:10:40 +00001799/***
1800Binary bases can be converted in time linear in the number of digits, because
1801Python's representation base is binary. Other bases (including decimal!) use
1802the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001803
Tim Peters696cf432006-05-24 21:10:40 +00001804First some math: the largest integer that can be expressed in N base-B digits
1805is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1806case number of Python digits needed to hold it is the smallest integer n s.t.
1807
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001808 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1809 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1810 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001811
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001812The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
Tim Peters696cf432006-05-24 21:10:40 +00001813this quickly. A Python long with that much space is reserved near the start,
1814and the result is computed into it.
1815
1816The input string is actually treated as being in base base**i (i.e., i digits
1817are processed at a time), where two more static arrays hold:
1818
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001819 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
Tim Peters696cf432006-05-24 21:10:40 +00001820 convmultmax_base[base] = base ** convwidth_base[base]
1821
1822The first of these is the largest i such that i consecutive input digits
1823must fit in a single Python digit. The second is effectively the input
1824base we're really using.
1825
1826Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1827convmultmax_base[base], the result is "simply"
1828
1829 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1830
1831where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001832
1833Error analysis: as above, the number of Python digits `n` needed is worst-
1834case
1835
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001836 n >= N * log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001837
1838where `N` is the number of input digits in base `B`. This is computed via
1839
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001840 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001841
1842below. Two numeric concerns are how much space this can waste, and whether
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001843the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
Tim Peters9faa3ed2006-05-30 15:53:34 +00001844which is the default (and it's unlikely anyone changes that).
1845
1846Waste isn't a problem: provided the first input digit isn't 0, the difference
1847between the worst-case input with N digits and the smallest input with N
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001848digits is about a factor of B, but B is small compared to PyLong_BASE so at most
Tim Peters9faa3ed2006-05-30 15:53:34 +00001849one allocated Python digit can remain unused on that count. If
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001850N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001851and adding 1 returns a result 1 larger than necessary. However, that can't
1852happen: whenever B is a power of 2, long_from_binary_base() is called
1853instead, and it's impossible for B**i to be an integer power of 2**15 when
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001854B is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be
Tim Peters9faa3ed2006-05-30 15:53:34 +00001855an exact integer when B is not a power of 2, since B**i has a prime factor
1856other than 2 in that case, but (2**15)**j's only prime factor is 2).
1857
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001858The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001859is a little bit larger than an exact integer, but due to roundoff errors (in
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001860computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001861yields a numeric result a little less than that integer. Unfortunately, "how
1862close can a transcendental function get to an integer over some range?"
1863questions are generally theoretically intractable. Computer analysis via
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001864continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
Tim Peters9faa3ed2006-05-30 15:53:34 +00001865fractions, giving a sequence i/j of "the best" rational approximations. Then
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001866j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001867we can get very close to being in trouble, but very rarely. For example,
186876573 is a denominator in one of the continued-fraction approximations to
1869log(10)/log(2**15), and indeed:
1870
1871 >>> log(10)/log(2**15)*76573
1872 16958.000000654003
1873
1874is very close to an integer. If we were working with IEEE single-precision,
1875rounding errors could kill us. Finding worst cases in IEEE double-precision
1876requires better-than-double-precision log() functions, and Tim didn't bother.
1877Instead the code checks to see whether the allocated space is enough as each
1878new Python digit is added, and copies the whole thing to a larger long if not.
1879This should happen extremely rarely, and in fact I don't have a test case
1880that triggers it(!). Instead the code was tested by artificially allocating
1881just 1 digit at the start, so that the copying code was exercised for every
1882digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001883***/
1884 register twodigits c; /* current input character */
1885 Py_ssize_t size_z;
1886 int i;
1887 int convwidth;
1888 twodigits convmultmax, convmult;
1889 digit *pz, *pzstop;
1890 char* scan;
1891
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001892 static double log_base_PyLong_BASE[37] = {0.0e0,};
Tim Peters696cf432006-05-24 21:10:40 +00001893 static int convwidth_base[37] = {0,};
1894 static twodigits convmultmax_base[37] = {0,};
1895
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001896 if (log_base_PyLong_BASE[base] == 0.0) {
Tim Peters696cf432006-05-24 21:10:40 +00001897 twodigits convmax = base;
1898 int i = 1;
1899
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001900 log_base_PyLong_BASE[base] = log((double)base) /
1901 log((double)PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001902 for (;;) {
1903 twodigits next = convmax * base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001904 if (next > PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001905 break;
1906 convmax = next;
1907 ++i;
1908 }
1909 convmultmax_base[base] = convmax;
1910 assert(i > 0);
1911 convwidth_base[base] = i;
1912 }
1913
1914 /* Find length of the string of numeric characters. */
1915 scan = str;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001916 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Tim Peters696cf432006-05-24 21:10:40 +00001917 ++scan;
1918
1919 /* Create a long object that can contain the largest possible
1920 * integer with this base and length. Note that there's no
1921 * need to initialize z->ob_digit -- no slot is read up before
1922 * being stored into.
1923 */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001924 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001925 /* Uncomment next line to test exceedingly rare copy code */
1926 /* size_z = 1; */
Tim Peters696cf432006-05-24 21:10:40 +00001927 assert(size_z > 0);
1928 z = _PyLong_New(size_z);
1929 if (z == NULL)
1930 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00001931 Py_SIZE(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001932
1933 /* `convwidth` consecutive input digits are treated as a single
1934 * digit in base `convmultmax`.
1935 */
1936 convwidth = convwidth_base[base];
1937 convmultmax = convmultmax_base[base];
1938
1939 /* Work ;-) */
1940 while (str < scan) {
1941 /* grab up to convwidth digits from the input string */
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001942 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Tim Peters696cf432006-05-24 21:10:40 +00001943 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1944 c = (twodigits)(c * base +
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001945 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001946 assert(c < PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001947 }
1948
1949 convmult = convmultmax;
1950 /* Calculate the shift only if we couldn't get
1951 * convwidth digits.
1952 */
1953 if (i != convwidth) {
1954 convmult = base;
1955 for ( ; i > 1; --i)
1956 convmult *= base;
1957 }
1958
1959 /* Multiply z by convmult, and add c. */
1960 pz = z->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +00001961 pzstop = pz + Py_SIZE(z);
Tim Peters696cf432006-05-24 21:10:40 +00001962 for (; pz < pzstop; ++pz) {
1963 c += (twodigits)*pz * convmult;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001964 *pz = (digit)(c & PyLong_MASK);
1965 c >>= PyLong_SHIFT;
Tim Peters696cf432006-05-24 21:10:40 +00001966 }
1967 /* carry off the current end? */
1968 if (c) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001969 assert(c < PyLong_BASE);
Christian Heimese93237d2007-12-19 02:37:44 +00001970 if (Py_SIZE(z) < size_z) {
Tim Peters9faa3ed2006-05-30 15:53:34 +00001971 *pz = (digit)c;
Christian Heimese93237d2007-12-19 02:37:44 +00001972 ++Py_SIZE(z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001973 }
1974 else {
1975 PyLongObject *tmp;
1976 /* Extremely rare. Get more space. */
Christian Heimese93237d2007-12-19 02:37:44 +00001977 assert(Py_SIZE(z) == size_z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001978 tmp = _PyLong_New(size_z + 1);
1979 if (tmp == NULL) {
1980 Py_DECREF(z);
1981 return NULL;
1982 }
1983 memcpy(tmp->ob_digit,
1984 z->ob_digit,
1985 sizeof(digit) * size_z);
1986 Py_DECREF(z);
1987 z = tmp;
1988 z->ob_digit[size_z] = (digit)c;
1989 ++size_z;
1990 }
Tim Peters696cf432006-05-24 21:10:40 +00001991 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001992 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001993 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001994 if (z == NULL)
1995 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001996 if (str == start)
1997 goto onError;
Tim Peters696cf432006-05-24 21:10:40 +00001998 if (sign < 0)
Christian Heimese93237d2007-12-19 02:37:44 +00001999 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00002000 if (*str == 'L' || *str == 'l')
2001 str++;
2002 while (*str && isspace(Py_CHARMASK(*str)))
2003 str++;
2004 if (*str != '\0')
2005 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002006 if (pend)
2007 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002008 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002009
2010 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002011 Py_XDECREF(z);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00002012 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002013 strobj = PyString_FromStringAndSize(orig_str, slen);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00002014 if (strobj == NULL)
2015 return NULL;
2016 strrepr = PyObject_Repr(strobj);
2017 Py_DECREF(strobj);
2018 if (strrepr == NULL)
2019 return NULL;
2020 PyErr_Format(PyExc_ValueError,
2021 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002022 base, PyString_AS_STRING(strrepr));
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00002023 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002024 return NULL;
2025}
2026
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002027#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00002028PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002029PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002030{
Walter Dörwald07e14762002-11-06 16:15:14 +00002031 PyObject *result;
Anthony Baxter377be112006-04-11 06:54:30 +00002032 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002033
Walter Dörwald07e14762002-11-06 16:15:14 +00002034 if (buffer == NULL)
2035 return NULL;
2036
2037 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2038 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002039 return NULL;
2040 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002041 result = PyLong_FromString(buffer, NULL, base);
2042 PyMem_FREE(buffer);
2043 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002044}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002045#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002046
Tim Peters9f688bf2000-07-07 15:53:28 +00002047/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002048static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002049 (PyLongObject *, PyLongObject *, PyLongObject **);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002050static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002051
2052/* Long division with remainder, top-level routine */
2053
Guido van Rossume32e0141992-01-19 16:31:05 +00002054static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002055long_divrem(PyLongObject *a, PyLongObject *b,
2056 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057{
Christian Heimese93237d2007-12-19 02:37:44 +00002058 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002059 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002060
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002061 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002062 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00002063 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002064 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002065 }
2066 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002067 (size_a == size_b &&
2068 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002069 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002070 *pdiv = _PyLong_New(0);
Georg Brandlc02e1312007-04-11 17:16:24 +00002071 if (*pdiv == NULL)
2072 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002073 Py_INCREF(a);
2074 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002075 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002076 }
2077 if (size_b == 1) {
2078 digit rem = 0;
2079 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002080 if (z == NULL)
2081 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002082 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Georg Brandlc02e1312007-04-11 17:16:24 +00002083 if (*prem == NULL) {
2084 Py_DECREF(z);
2085 return -1;
2086 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002087 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002088 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002089 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002090 if (z == NULL)
2091 return -1;
2092 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002093 /* Set the signs.
2094 The quotient z has the sign of a*b;
2095 the remainder r has the sign of a,
2096 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00002097 if ((a->ob_size < 0) != (b->ob_size < 0))
2098 z->ob_size = -(z->ob_size);
2099 if (a->ob_size < 0 && (*prem)->ob_size != 0)
2100 (*prem)->ob_size = -((*prem)->ob_size);
2101 *pdiv = z;
2102 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002103}
2104
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002105/* Unsigned long division with remainder -- the algorithm. The arguments v1
2106 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002107
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002108static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002109x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002110{
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002111 PyLongObject *v, *w, *a;
2112 Py_ssize_t i, k, size_v, size_w;
2113 int d;
2114 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2115 twodigits vv;
2116 sdigit zhi;
2117 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002118
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002119 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2120 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2121 handle the special case when the initial estimate q for a quotient
2122 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2123 that won't overflow a digit. */
2124
2125 /* allocate space; w will also be used to hold the final remainder */
2126 size_v = ABS(Py_SIZE(v1));
2127 size_w = ABS(Py_SIZE(w1));
2128 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2129 v = _PyLong_New(size_v+1);
2130 if (v == NULL) {
2131 *prem = NULL;
2132 return NULL;
2133 }
2134 w = _PyLong_New(size_w);
2135 if (w == NULL) {
2136 Py_DECREF(v);
2137 *prem = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002138 return NULL;
2139 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002140
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002141 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2142 shift v1 left by the same amount. Results go into w and v. */
2143 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2144 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2145 assert(carry == 0);
2146 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2147 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2148 v->ob_digit[size_v] = carry;
2149 size_v++;
2150 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002151
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002152 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2153 at most (and usually exactly) k = size_v - size_w digits. */
Neal Norwitzc6a989a2006-05-10 06:57:58 +00002154 k = size_v - size_w;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002155 assert(k >= 0);
2156 a = _PyLong_New(k);
2157 if (a == NULL) {
2158 Py_DECREF(w);
2159 Py_DECREF(v);
2160 *prem = NULL;
2161 return NULL;
2162 }
2163 v0 = v->ob_digit;
2164 w0 = w->ob_digit;
2165 wm1 = w0[size_w-1];
2166 wm2 = w0[size_w-2];
2167 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2168 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2169 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002170
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002171 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002172 Py_DECREF(a);
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002173 Py_DECREF(w);
2174 Py_DECREF(v);
2175 *prem = NULL;
2176 return NULL;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002177 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002178
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002179 /* estimate quotient digit q; may overestimate by 1 (rare) */
2180 vtop = vk[size_w];
2181 assert(vtop <= wm1);
2182 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2183 q = (digit)(vv / wm1);
2184 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2185 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2186 | vk[size_w-2])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002187 --q;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002188 r += wm1;
2189 if (r >= PyLong_BASE)
2190 break;
2191 }
2192 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002193
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002194 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2195 zhi = 0;
2196 for (i = 0; i < size_w; ++i) {
2197 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2198 -PyLong_BASE * q <= z < PyLong_BASE */
2199 z = (sdigit)vk[i] + zhi -
2200 (stwodigits)q * (stwodigits)w0[i];
2201 vk[i] = (digit)z & PyLong_MASK;
2202 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2203 z, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002204 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002205
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002206 /* add w back if q was too large (this branch taken rarely) */
2207 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2208 if ((sdigit)vtop + zhi < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002209 carry = 0;
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002210 for (i = 0; i < size_w; ++i) {
2211 carry += vk[i] + w0[i];
2212 vk[i] = carry & PyLong_MASK;
2213 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002214 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002215 --q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002216 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002217
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002218 /* store quotient digit */
2219 assert(q < PyLong_BASE);
2220 *--ak = q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002221 }
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002222
2223 /* unshift remainder; we reuse w to store the result */
2224 carry = v_rshift(w0, v0, size_w, d);
2225 assert(carry==0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002226 Py_DECREF(v);
Mark Dickinson0b666bf2009-03-23 18:25:13 +00002227
2228 *prem = long_normalize(w);
2229 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002230}
2231
2232/* Methods */
2233
2234static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002235long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002236{
Christian Heimese93237d2007-12-19 02:37:44 +00002237 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002238}
2239
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002240static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002241long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002242{
Eric Smith5e527eb2008-02-10 01:36:53 +00002243 return _PyLong_Format(v, 10, 1, 0);
Fred Drake121ee271999-12-23 15:41:28 +00002244}
2245
2246static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002247long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00002248{
Eric Smith5e527eb2008-02-10 01:36:53 +00002249 return _PyLong_Format(v, 10, 0, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002250}
2251
2252static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002253long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002254{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002255 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002256
Christian Heimese93237d2007-12-19 02:37:44 +00002257 if (Py_SIZE(a) != Py_SIZE(b)) {
2258 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002259 sign = 0;
2260 else
Christian Heimese93237d2007-12-19 02:37:44 +00002261 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002262 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002263 else {
Christian Heimese93237d2007-12-19 02:37:44 +00002264 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002265 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2266 ;
2267 if (i < 0)
2268 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002269 else {
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00002270 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimese93237d2007-12-19 02:37:44 +00002271 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002272 sign = -sign;
2273 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002274 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002275 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002276}
2277
Guido van Rossum9bfef441993-03-29 10:43:31 +00002278static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002279long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002280{
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00002281 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002282 Py_ssize_t i;
2283 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002284
2285 /* This is designed so that Python ints and longs with the
2286 same value hash to the same value, otherwise comparisons
2287 of mapping keys will turn out weird */
2288 i = v->ob_size;
2289 sign = 1;
2290 x = 0;
2291 if (i < 0) {
2292 sign = -1;
2293 i = -(i);
2294 }
Mark Dickinsona0eae032009-01-26 21:40:08 +00002295 /* The following loop produces a C unsigned long x such that x is
2296 congruent to the absolute value of v modulo ULONG_MAX. The
2297 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002298 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002299 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00002300 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002301 x += v->ob_digit[i];
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00002302 /* If the addition above overflowed we compensate by
2303 incrementing. This preserves the value modulo
2304 ULONG_MAX. */
2305 if (x < v->ob_digit[i])
Facundo Batistad544df72007-09-19 15:10:06 +00002306 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002307 }
2308 x = x * sign;
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00002309 if (x == (unsigned long)-1)
2310 x = (unsigned long)-2;
2311 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002312}
2313
2314
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002315/* Add the absolute values of two long integers. */
2316
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002317static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002318x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002319{
Christian Heimese93237d2007-12-19 02:37:44 +00002320 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002321 PyLongObject *z;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00002322 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002323 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002324
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002325 /* Ensure a is the larger of the two: */
2326 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002327 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002328 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002329 size_a = size_b;
2330 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002331 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002332 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002333 if (z == NULL)
2334 return NULL;
2335 for (i = 0; i < size_b; ++i) {
2336 carry += a->ob_digit[i] + b->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002337 z->ob_digit[i] = carry & PyLong_MASK;
2338 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002339 }
2340 for (; i < size_a; ++i) {
2341 carry += a->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002342 z->ob_digit[i] = carry & PyLong_MASK;
2343 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002344 }
2345 z->ob_digit[i] = carry;
2346 return long_normalize(z);
2347}
2348
2349/* Subtract the absolute values of two integers. */
2350
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002351static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002352x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002353{
Christian Heimese93237d2007-12-19 02:37:44 +00002354 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002355 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002356 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002357 int sign = 1;
2358 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002359
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002360 /* Ensure a is the larger of the two: */
2361 if (size_a < size_b) {
2362 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002363 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002364 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002365 size_a = size_b;
2366 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002367 }
2368 else if (size_a == size_b) {
2369 /* Find highest digit where a and b differ: */
2370 i = size_a;
2371 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2372 ;
2373 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002374 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002375 if (a->ob_digit[i] < b->ob_digit[i]) {
2376 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002377 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002378 }
2379 size_a = size_b = i+1;
2380 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002381 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002382 if (z == NULL)
2383 return NULL;
2384 for (i = 0; i < size_b; ++i) {
2385 /* The following assumes unsigned arithmetic
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002386 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002387 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002388 z->ob_digit[i] = borrow & PyLong_MASK;
2389 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002390 borrow &= 1; /* Keep only one sign bit */
2391 }
2392 for (; i < size_a; ++i) {
2393 borrow = a->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002394 z->ob_digit[i] = borrow & PyLong_MASK;
2395 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002396 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002397 }
2398 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002399 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002400 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002401 return long_normalize(z);
2402}
2403
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002404static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002405long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002406{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002407 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002408
Neil Schemenauerba872e22001-01-04 01:46:03 +00002409 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2410
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002411 if (a->ob_size < 0) {
2412 if (b->ob_size < 0) {
2413 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002414 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002415 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002416 }
2417 else
2418 z = x_sub(b, a);
2419 }
2420 else {
2421 if (b->ob_size < 0)
2422 z = x_sub(a, b);
2423 else
2424 z = x_add(a, b);
2425 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002426 Py_DECREF(a);
2427 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002428 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002429}
2430
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002431static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002432long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002433{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002434 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002435
Neil Schemenauerba872e22001-01-04 01:46:03 +00002436 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2437
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002438 if (a->ob_size < 0) {
2439 if (b->ob_size < 0)
2440 z = x_sub(a, b);
2441 else
2442 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002443 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002444 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002445 }
2446 else {
2447 if (b->ob_size < 0)
2448 z = x_add(a, b);
2449 else
2450 z = x_sub(a, b);
2451 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002452 Py_DECREF(a);
2453 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002454 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002455}
2456
Tim Peters5af4e6c2002-08-12 02:31:19 +00002457/* Grade school multiplication, ignoring the signs.
2458 * Returns the absolute value of the product, or NULL if error.
2459 */
2460static PyLongObject *
2461x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002462{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002463 PyLongObject *z;
Christian Heimese93237d2007-12-19 02:37:44 +00002464 Py_ssize_t size_a = ABS(Py_SIZE(a));
2465 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002466 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002467
Tim Peters5af4e6c2002-08-12 02:31:19 +00002468 z = _PyLong_New(size_a + size_b);
2469 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002470 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002471
Christian Heimese93237d2007-12-19 02:37:44 +00002472 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002473 if (a == b) {
2474 /* Efficient squaring per HAC, Algorithm 14.16:
2475 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2476 * Gives slightly less than a 2x speedup when a == b,
2477 * via exploiting that each entry in the multiplication
2478 * pyramid appears twice (except for the size_a squares).
2479 */
2480 for (i = 0; i < size_a; ++i) {
2481 twodigits carry;
2482 twodigits f = a->ob_digit[i];
2483 digit *pz = z->ob_digit + (i << 1);
2484 digit *pa = a->ob_digit + i + 1;
2485 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002486
Tim Peters0973b992004-08-29 22:16:50 +00002487 SIGCHECK({
2488 Py_DECREF(z);
2489 return NULL;
2490 })
2491
2492 carry = *pz + f * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002493 *pz++ = (digit)(carry & PyLong_MASK);
2494 carry >>= PyLong_SHIFT;
2495 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002496
2497 /* Now f is added in twice in each column of the
2498 * pyramid it appears. Same as adding f<<1 once.
2499 */
2500 f <<= 1;
2501 while (pa < paend) {
2502 carry += *pz + *pa++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002503 *pz++ = (digit)(carry & PyLong_MASK);
2504 carry >>= PyLong_SHIFT;
2505 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002506 }
2507 if (carry) {
2508 carry += *pz;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002509 *pz++ = (digit)(carry & PyLong_MASK);
2510 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002511 }
2512 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002513 *pz += (digit)(carry & PyLong_MASK);
2514 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002515 }
Tim Peters0973b992004-08-29 22:16:50 +00002516 }
2517 else { /* a is not the same as b -- gradeschool long mult */
2518 for (i = 0; i < size_a; ++i) {
2519 twodigits carry = 0;
2520 twodigits f = a->ob_digit[i];
2521 digit *pz = z->ob_digit + i;
2522 digit *pb = b->ob_digit;
2523 digit *pbend = b->ob_digit + size_b;
2524
2525 SIGCHECK({
2526 Py_DECREF(z);
2527 return NULL;
2528 })
2529
2530 while (pb < pbend) {
2531 carry += *pz + *pb++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002532 *pz++ = (digit)(carry & PyLong_MASK);
2533 carry >>= PyLong_SHIFT;
2534 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002535 }
2536 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002537 *pz += (digit)(carry & PyLong_MASK);
2538 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002539 }
2540 }
Tim Peters44121a62002-08-12 06:17:58 +00002541 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002542}
2543
2544/* A helper for Karatsuba multiplication (k_mul).
2545 Takes a long "n" and an integer "size" representing the place to
2546 split, and sets low and high such that abs(n) == (high << size) + low,
2547 viewing the shift as being by digits. The sign bit is ignored, and
2548 the return values are >= 0.
2549 Returns 0 on success, -1 on failure.
2550*/
2551static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002552kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002553{
2554 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002555 Py_ssize_t size_lo, size_hi;
Christian Heimese93237d2007-12-19 02:37:44 +00002556 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002557
2558 size_lo = MIN(size_n, size);
2559 size_hi = size_n - size_lo;
2560
2561 if ((hi = _PyLong_New(size_hi)) == NULL)
2562 return -1;
2563 if ((lo = _PyLong_New(size_lo)) == NULL) {
2564 Py_DECREF(hi);
2565 return -1;
2566 }
2567
2568 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2569 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2570
2571 *high = long_normalize(hi);
2572 *low = long_normalize(lo);
2573 return 0;
2574}
2575
Tim Peters60004642002-08-12 22:01:34 +00002576static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2577
Tim Peters5af4e6c2002-08-12 02:31:19 +00002578/* Karatsuba multiplication. Ignores the input signs, and returns the
2579 * absolute value of the product (or NULL if error).
2580 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2581 */
2582static PyLongObject *
2583k_mul(PyLongObject *a, PyLongObject *b)
2584{
Christian Heimese93237d2007-12-19 02:37:44 +00002585 Py_ssize_t asize = ABS(Py_SIZE(a));
2586 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002587 PyLongObject *ah = NULL;
2588 PyLongObject *al = NULL;
2589 PyLongObject *bh = NULL;
2590 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002591 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002592 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002593 Py_ssize_t shift; /* the number of digits we split off */
2594 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002595
Tim Peters5af4e6c2002-08-12 02:31:19 +00002596 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2597 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2598 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002599 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002600 * By picking X to be a power of 2, "*X" is just shifting, and it's
2601 * been reduced to 3 multiplies on numbers half the size.
2602 */
2603
Tim Petersfc07e562002-08-12 02:54:10 +00002604 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002605 * is largest.
2606 */
Tim Peters738eda72002-08-12 15:08:20 +00002607 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002608 t1 = a;
2609 a = b;
2610 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002611
2612 i = asize;
2613 asize = bsize;
2614 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002615 }
2616
2617 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002618 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2619 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002620 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002621 return _PyLong_New(0);
2622 else
2623 return x_mul(a, b);
2624 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002625
Tim Peters60004642002-08-12 22:01:34 +00002626 /* If a is small compared to b, splitting on b gives a degenerate
2627 * case with ah==0, and Karatsuba may be (even much) less efficient
2628 * than "grade school" then. However, we can still win, by viewing
2629 * b as a string of "big digits", each of width a->ob_size. That
2630 * leads to a sequence of balanced calls to k_mul.
2631 */
2632 if (2 * asize <= bsize)
2633 return k_lopsided_mul(a, b);
2634
Tim Petersd6974a52002-08-13 20:37:51 +00002635 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002636 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002637 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002638 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002639
Tim Peters0973b992004-08-29 22:16:50 +00002640 if (a == b) {
2641 bh = ah;
2642 bl = al;
2643 Py_INCREF(bh);
2644 Py_INCREF(bl);
2645 }
2646 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002647
Tim Petersd64c1de2002-08-12 17:36:03 +00002648 /* The plan:
2649 * 1. Allocate result space (asize + bsize digits: that's always
2650 * enough).
2651 * 2. Compute ah*bh, and copy into result at 2*shift.
2652 * 3. Compute al*bl, and copy into result at 0. Note that this
2653 * can't overlap with #2.
2654 * 4. Subtract al*bl from the result, starting at shift. This may
2655 * underflow (borrow out of the high digit), but we don't care:
2656 * we're effectively doing unsigned arithmetic mod
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002657 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
Tim Petersd64c1de2002-08-12 17:36:03 +00002658 * borrows and carries out of the high digit can be ignored.
2659 * 5. Subtract ah*bh from the result, starting at shift.
2660 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2661 * at shift.
2662 */
2663
2664 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002665 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002666 if (ret == NULL) goto fail;
2667#ifdef Py_DEBUG
2668 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002669 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002670#endif
Tim Peters44121a62002-08-12 06:17:58 +00002671
Tim Petersd64c1de2002-08-12 17:36:03 +00002672 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002673 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002674 assert(Py_SIZE(t1) >= 0);
2675 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002676 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimese93237d2007-12-19 02:37:44 +00002677 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002678
2679 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimese93237d2007-12-19 02:37:44 +00002680 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002681 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002682 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002683 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002684
Tim Petersd64c1de2002-08-12 17:36:03 +00002685 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002686 if ((t2 = k_mul(al, bl)) == NULL) {
2687 Py_DECREF(t1);
2688 goto fail;
2689 }
Christian Heimese93237d2007-12-19 02:37:44 +00002690 assert(Py_SIZE(t2) >= 0);
2691 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2692 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002693
2694 /* Zero out remaining digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002695 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002696 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002697 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002698
Tim Petersd64c1de2002-08-12 17:36:03 +00002699 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2700 * because it's fresher in cache.
2701 */
Christian Heimese93237d2007-12-19 02:37:44 +00002702 i = Py_SIZE(ret) - shift; /* # digits after shift */
2703 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002704 Py_DECREF(t2);
2705
Christian Heimese93237d2007-12-19 02:37:44 +00002706 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002707 Py_DECREF(t1);
2708
Tim Petersd64c1de2002-08-12 17:36:03 +00002709 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002710 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2711 Py_DECREF(ah);
2712 Py_DECREF(al);
2713 ah = al = NULL;
2714
Tim Peters0973b992004-08-29 22:16:50 +00002715 if (a == b) {
2716 t2 = t1;
2717 Py_INCREF(t2);
2718 }
2719 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002720 Py_DECREF(t1);
2721 goto fail;
2722 }
2723 Py_DECREF(bh);
2724 Py_DECREF(bl);
2725 bh = bl = NULL;
2726
Tim Peters738eda72002-08-12 15:08:20 +00002727 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002728 Py_DECREF(t1);
2729 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002730 if (t3 == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002731 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002732
Tim Petersd6974a52002-08-13 20:37:51 +00002733 /* Add t3. It's not obvious why we can't run out of room here.
2734 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002735 */
Christian Heimese93237d2007-12-19 02:37:44 +00002736 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002737 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002738
Tim Peters5af4e6c2002-08-12 02:31:19 +00002739 return long_normalize(ret);
2740
2741 fail:
2742 Py_XDECREF(ret);
2743 Py_XDECREF(ah);
2744 Py_XDECREF(al);
2745 Py_XDECREF(bh);
2746 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002747 return NULL;
2748}
2749
Tim Petersd6974a52002-08-13 20:37:51 +00002750/* (*) Why adding t3 can't "run out of room" above.
2751
Tim Petersab86c2b2002-08-15 20:06:00 +00002752Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2753to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002754
Tim Petersab86c2b2002-08-15 20:06:00 +000027551. For any integer i, i = c(i/2) + f(i/2). In particular,
2756 bsize = c(bsize/2) + f(bsize/2).
27572. shift = f(bsize/2)
27583. asize <= bsize
27594. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2760 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002761
Tim Petersab86c2b2002-08-15 20:06:00 +00002762We allocated asize + bsize result digits, and add t3 into them at an offset
2763of shift. This leaves asize+bsize-shift allocated digit positions for t3
2764to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2765asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002766
Tim Petersab86c2b2002-08-15 20:06:00 +00002767bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2768at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002769
Tim Petersab86c2b2002-08-15 20:06:00 +00002770If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2771digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2772most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002773
Tim Petersab86c2b2002-08-15 20:06:00 +00002774The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002775
Tim Petersab86c2b2002-08-15 20:06:00 +00002776 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002777
Tim Petersab86c2b2002-08-15 20:06:00 +00002778and we have asize + c(bsize/2) available digit positions. We need to show
2779this is always enough. An instance of c(bsize/2) cancels out in both, so
2780the question reduces to whether asize digits is enough to hold
2781(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2782then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2783asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002784digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002785asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002786c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2787is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2788bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002789
Tim Peters48d52c02002-08-14 17:07:32 +00002790Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2791clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2792ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002793*/
2794
Tim Peters60004642002-08-12 22:01:34 +00002795/* b has at least twice the digits of a, and a is big enough that Karatsuba
2796 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2797 * of slices, each with a->ob_size digits, and multiply the slices by a,
2798 * one at a time. This gives k_mul balanced inputs to work with, and is
2799 * also cache-friendly (we compute one double-width slice of the result
2800 * at a time, then move on, never bactracking except for the helpful
2801 * single-width slice overlap between successive partial sums).
2802 */
2803static PyLongObject *
2804k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2805{
Christian Heimese93237d2007-12-19 02:37:44 +00002806 const Py_ssize_t asize = ABS(Py_SIZE(a));
2807 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002808 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002809 PyLongObject *ret;
2810 PyLongObject *bslice = NULL;
2811
2812 assert(asize > KARATSUBA_CUTOFF);
2813 assert(2 * asize <= bsize);
2814
2815 /* Allocate result space, and zero it out. */
2816 ret = _PyLong_New(asize + bsize);
2817 if (ret == NULL)
2818 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002819 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002820
2821 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002822 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002823 if (bslice == NULL)
2824 goto fail;
2825
2826 nbdone = 0;
2827 while (bsize > 0) {
2828 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002829 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002830
2831 /* Multiply the next slice of b by a. */
2832 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2833 nbtouse * sizeof(digit));
Christian Heimese93237d2007-12-19 02:37:44 +00002834 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002835 product = k_mul(a, bslice);
2836 if (product == NULL)
2837 goto fail;
2838
2839 /* Add into result. */
Christian Heimese93237d2007-12-19 02:37:44 +00002840 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2841 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002842 Py_DECREF(product);
2843
2844 bsize -= nbtouse;
2845 nbdone += nbtouse;
2846 }
2847
2848 Py_DECREF(bslice);
2849 return long_normalize(ret);
2850
2851 fail:
2852 Py_DECREF(ret);
2853 Py_XDECREF(bslice);
2854 return NULL;
2855}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002856
2857static PyObject *
2858long_mul(PyLongObject *v, PyLongObject *w)
2859{
2860 PyLongObject *a, *b, *z;
2861
2862 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002863 Py_INCREF(Py_NotImplemented);
2864 return Py_NotImplemented;
2865 }
2866
Tim Petersd64c1de2002-08-12 17:36:03 +00002867 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002868 /* Negate if exactly one of the inputs is negative. */
2869 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002870 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002871 Py_DECREF(a);
2872 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002873 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002874}
2875
Guido van Rossume32e0141992-01-19 16:31:05 +00002876/* The / and % operators are now defined in terms of divmod().
2877 The expression a mod b has the value a - b*floor(a/b).
2878 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002879 |a| by |b|, with the sign of a. This is also expressed
2880 as a - b*trunc(a/b), if trunc truncates towards zero.
2881 Some examples:
2882 a b a rem b a mod b
2883 13 10 3 3
2884 -13 10 -3 7
2885 13 -10 3 -7
2886 -13 -10 -3 -3
2887 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002888 have different signs. We then subtract one from the 'div'
2889 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002890
Tim Peters47e52ee2004-08-30 02:44:38 +00002891/* Compute
2892 * *pdiv, *pmod = divmod(v, w)
2893 * NULL can be passed for pdiv or pmod, in which case that part of
2894 * the result is simply thrown away. The caller owns a reference to
2895 * each of these it requests (does not pass NULL for).
2896 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002897static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002898l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002899 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002900{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002901 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002902
Guido van Rossume32e0141992-01-19 16:31:05 +00002903 if (long_divrem(v, w, &div, &mod) < 0)
2904 return -1;
Christian Heimese93237d2007-12-19 02:37:44 +00002905 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2906 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002907 PyLongObject *temp;
2908 PyLongObject *one;
2909 temp = (PyLongObject *) long_add(mod, w);
2910 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002911 mod = temp;
2912 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002913 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002914 return -1;
2915 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002916 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002917 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002918 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2919 Py_DECREF(mod);
2920 Py_DECREF(div);
2921 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002922 return -1;
2923 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002924 Py_DECREF(one);
2925 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002926 div = temp;
2927 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002928 if (pdiv != NULL)
2929 *pdiv = div;
2930 else
2931 Py_DECREF(div);
2932
2933 if (pmod != NULL)
2934 *pmod = mod;
2935 else
2936 Py_DECREF(mod);
2937
Guido van Rossume32e0141992-01-19 16:31:05 +00002938 return 0;
2939}
2940
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002941static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002942long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002943{
Tim Peters47e52ee2004-08-30 02:44:38 +00002944 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002945
2946 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002947 if (l_divmod(a, b, &div, NULL) < 0)
2948 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002949 Py_DECREF(a);
2950 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002951 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002952}
2953
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002954static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002955long_classic_div(PyObject *v, PyObject *w)
2956{
Tim Peters47e52ee2004-08-30 02:44:38 +00002957 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002958
2959 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002960 if (Py_DivisionWarningFlag &&
2961 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2962 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002963 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002964 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002965 Py_DECREF(a);
2966 Py_DECREF(b);
2967 return (PyObject *)div;
2968}
2969
2970static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002971long_true_divide(PyObject *v, PyObject *w)
2972{
Tim Peterse2a60002001-09-04 06:17:36 +00002973 PyLongObject *a, *b;
2974 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002975 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002976
2977 CONVERT_BINOP(v, w, &a, &b);
2978 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2979 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002980 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2981 Py_DECREF(a);
2982 Py_DECREF(b);
2983 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002984 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002985 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2986 but should really be set correctly after sucessful calls to
2987 _PyLong_AsScaledDouble() */
2988 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002989
2990 if (bd == 0.0) {
2991 PyErr_SetString(PyExc_ZeroDivisionError,
2992 "long division or modulo by zero");
2993 return NULL;
2994 }
2995
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002996 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002997 ad /= bd; /* overflow/underflow impossible here */
2998 aexp -= bexp;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002999 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00003000 goto overflow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003001 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00003002 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003003 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003004 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00003005 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003006 goto overflow;
3007 return PyFloat_FromDouble(ad);
3008
3009overflow:
3010 PyErr_SetString(PyExc_OverflowError,
3011 "long/long too large for a float");
3012 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003013
Tim Peters20dab9f2001-09-04 05:31:47 +00003014}
3015
3016static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003017long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00003018{
Tim Peters47e52ee2004-08-30 02:44:38 +00003019 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003020
3021 CONVERT_BINOP(v, w, &a, &b);
3022
Tim Peters47e52ee2004-08-30 02:44:38 +00003023 if (l_divmod(a, b, NULL, &mod) < 0)
3024 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003025 Py_DECREF(a);
3026 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003027 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003028}
3029
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003030static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003031long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003032{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003033 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003034 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003035
3036 CONVERT_BINOP(v, w, &a, &b);
3037
3038 if (l_divmod(a, b, &div, &mod) < 0) {
3039 Py_DECREF(a);
3040 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003041 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003042 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003043 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003044 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003045 PyTuple_SetItem(z, 0, (PyObject *) div);
3046 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003047 }
3048 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003049 Py_DECREF(div);
3050 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003051 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003052 Py_DECREF(a);
3053 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003054 return z;
3055}
3056
Tim Peters47e52ee2004-08-30 02:44:38 +00003057/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003058static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003059long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003060{
Tim Peters47e52ee2004-08-30 02:44:38 +00003061 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3062 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003063
Tim Peters47e52ee2004-08-30 02:44:38 +00003064 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003065 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003066 PyLongObject *temp = NULL;
3067
3068 /* 5-ary values. If the exponent is large enough, table is
3069 * precomputed so that table[i] == a**i % c for i in range(32).
3070 */
3071 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3072 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3073
3074 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003075 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003076 if (PyLong_Check(x)) {
3077 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003078 Py_INCREF(x);
3079 }
Tim Petersde7990b2005-07-17 23:45:23 +00003080 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003081 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00003082 if (c == NULL)
3083 goto Error;
3084 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003085 else if (x == Py_None)
3086 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003087 else {
3088 Py_DECREF(a);
3089 Py_DECREF(b);
3090 Py_INCREF(Py_NotImplemented);
3091 return Py_NotImplemented;
3092 }
Tim Peters4c483c42001-09-05 06:24:58 +00003093
Christian Heimese93237d2007-12-19 02:37:44 +00003094 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003095 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003096 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003097 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003098 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003099 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003100 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003101 /* else return a float. This works because we know
3102 that this calls float_pow() which converts its
3103 arguments to double. */
3104 Py_DECREF(a);
3105 Py_DECREF(b);
3106 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003107 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003108 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003109
3110 if (c) {
3111 /* if modulus == 0:
3112 raise ValueError() */
Christian Heimese93237d2007-12-19 02:37:44 +00003113 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003114 PyErr_SetString(PyExc_ValueError,
3115 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003116 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003117 }
3118
3119 /* if modulus < 0:
3120 negativeOutput = True
3121 modulus = -modulus */
Christian Heimese93237d2007-12-19 02:37:44 +00003122 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003123 negativeOutput = 1;
3124 temp = (PyLongObject *)_PyLong_Copy(c);
3125 if (temp == NULL)
3126 goto Error;
3127 Py_DECREF(c);
3128 c = temp;
3129 temp = NULL;
3130 c->ob_size = - c->ob_size;
3131 }
3132
3133 /* if modulus == 1:
3134 return 0 */
Christian Heimese93237d2007-12-19 02:37:44 +00003135 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003136 z = (PyLongObject *)PyLong_FromLong(0L);
3137 goto Done;
3138 }
3139
3140 /* if base < 0:
3141 base = base % modulus
3142 Having the base positive just makes things easier. */
Christian Heimese93237d2007-12-19 02:37:44 +00003143 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003144 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003145 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003146 Py_DECREF(a);
3147 a = temp;
3148 temp = NULL;
3149 }
3150 }
3151
3152 /* At this point a, b, and c are guaranteed non-negative UNLESS
3153 c is NULL, in which case a may be negative. */
3154
3155 z = (PyLongObject *)PyLong_FromLong(1L);
3156 if (z == NULL)
3157 goto Error;
3158
3159 /* Perform a modular reduction, X = X % c, but leave X alone if c
3160 * is NULL.
3161 */
3162#define REDUCE(X) \
3163 if (c != NULL) { \
3164 if (l_divmod(X, c, NULL, &temp) < 0) \
3165 goto Error; \
3166 Py_XDECREF(X); \
3167 X = temp; \
3168 temp = NULL; \
3169 }
3170
3171 /* Multiply two values, then reduce the result:
3172 result = X*Y % c. If c is NULL, skip the mod. */
3173#define MULT(X, Y, result) \
3174{ \
3175 temp = (PyLongObject *)long_mul(X, Y); \
3176 if (temp == NULL) \
3177 goto Error; \
3178 Py_XDECREF(result); \
3179 result = temp; \
3180 temp = NULL; \
3181 REDUCE(result) \
3182}
3183
Christian Heimese93237d2007-12-19 02:37:44 +00003184 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003185 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3186 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimese93237d2007-12-19 02:37:44 +00003187 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003188 digit bi = b->ob_digit[i];
3189
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00003190 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003191 MULT(z, z, z)
3192 if (bi & j)
3193 MULT(z, a, z)
3194 }
3195 }
3196 }
3197 else {
3198 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3199 Py_INCREF(z); /* still holds 1L */
3200 table[0] = z;
3201 for (i = 1; i < 32; ++i)
3202 MULT(table[i-1], a, table[i])
3203
Christian Heimese93237d2007-12-19 02:37:44 +00003204 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003205 const digit bi = b->ob_digit[i];
3206
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003207 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003208 const int index = (bi >> j) & 0x1f;
3209 for (k = 0; k < 5; ++k)
3210 MULT(z, z, z)
3211 if (index)
3212 MULT(z, table[index], z)
3213 }
3214 }
3215 }
3216
Christian Heimese93237d2007-12-19 02:37:44 +00003217 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003218 temp = (PyLongObject *)long_sub(z, c);
3219 if (temp == NULL)
3220 goto Error;
3221 Py_DECREF(z);
3222 z = temp;
3223 temp = NULL;
3224 }
3225 goto Done;
3226
3227 Error:
3228 if (z != NULL) {
3229 Py_DECREF(z);
3230 z = NULL;
3231 }
3232 /* fall through */
3233 Done:
Christian Heimese93237d2007-12-19 02:37:44 +00003234 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003235 for (i = 0; i < 32; ++i)
3236 Py_XDECREF(table[i]);
3237 }
Tim Petersde7990b2005-07-17 23:45:23 +00003238 Py_DECREF(a);
3239 Py_DECREF(b);
3240 Py_XDECREF(c);
3241 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003242 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003243}
3244
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003245static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003246long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003247{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003248 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003249 PyLongObject *x;
3250 PyLongObject *w;
3251 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003252 if (w == NULL)
3253 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003254 x = (PyLongObject *) long_add(v, w);
3255 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003256 if (x == NULL)
3257 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00003258 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003259 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003260}
3261
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003262static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003263long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003264{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003265 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003266 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003267 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003268 Py_INCREF(v);
3269 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003270 }
Tim Peters69c2de32001-09-11 22:31:33 +00003271 z = (PyLongObject *)_PyLong_Copy(v);
3272 if (z != NULL)
3273 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003274 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003275}
3276
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003277static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003278long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003279{
3280 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003281 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003282 else
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003283 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003284}
3285
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003286static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003287long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003288{
Christian Heimese93237d2007-12-19 02:37:44 +00003289 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003290}
3291
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003292static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003293long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003294{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003295 PyLongObject *a, *b;
3296 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003297 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003298 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003299 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003300
Neil Schemenauerba872e22001-01-04 01:46:03 +00003301 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3302
Christian Heimese93237d2007-12-19 02:37:44 +00003303 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003304 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003305 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003306 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003307 if (a1 == NULL)
3308 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003309 a2 = (PyLongObject *) long_rshift(a1, b);
3310 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003311 if (a2 == NULL)
3312 goto rshift_error;
3313 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003314 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003315 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003316 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003317
Neil Schemenauerba872e22001-01-04 01:46:03 +00003318 shiftby = PyLong_AsLong((PyObject *)b);
3319 if (shiftby == -1L && PyErr_Occurred())
3320 goto rshift_error;
3321 if (shiftby < 0) {
3322 PyErr_SetString(PyExc_ValueError,
3323 "negative shift count");
3324 goto rshift_error;
3325 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003326 wordshift = shiftby / PyLong_SHIFT;
Christian Heimese93237d2007-12-19 02:37:44 +00003327 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003328 if (newsize <= 0) {
3329 z = _PyLong_New(0);
3330 Py_DECREF(a);
3331 Py_DECREF(b);
3332 return (PyObject *)z;
3333 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003334 loshift = shiftby % PyLong_SHIFT;
3335 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003336 lomask = ((digit)1 << hishift) - 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003337 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003338 z = _PyLong_New(newsize);
3339 if (z == NULL)
3340 goto rshift_error;
Christian Heimese93237d2007-12-19 02:37:44 +00003341 if (Py_SIZE(a) < 0)
3342 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003343 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3344 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3345 if (i+1 < newsize)
3346 z->ob_digit[i] |=
3347 (a->ob_digit[j+1] << hishift) & himask;
3348 }
3349 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003350 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003351rshift_error:
3352 Py_DECREF(a);
3353 Py_DECREF(b);
3354 return (PyObject *) z;
3355
Guido van Rossumc6913e71991-11-19 20:26:46 +00003356}
3357
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003358static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003359long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003360{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003361 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003362 PyLongObject *a, *b;
3363 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003364 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003365 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003366 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003367
Neil Schemenauerba872e22001-01-04 01:46:03 +00003368 CONVERT_BINOP(v, w, &a, &b);
3369
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003370 shiftby = PyLong_AsLong((PyObject *)b);
3371 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003372 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003373 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003374 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003375 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003376 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003377 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003378 PyErr_SetString(PyExc_ValueError,
3379 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003380 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003381 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003382 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3383 wordshift = (int)shiftby / PyLong_SHIFT;
3384 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003385
3386 oldsize = ABS(a->ob_size);
3387 newsize = oldsize + wordshift;
3388 if (remshift)
3389 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003390 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003391 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003392 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003393 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003394 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003395 for (i = 0; i < wordshift; i++)
3396 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003397 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003398 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003399 accum |= (twodigits)a->ob_digit[j] << remshift;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003400 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3401 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003402 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003403 if (remshift)
3404 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003405 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003406 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003407 z = long_normalize(z);
3408lshift_error:
3409 Py_DECREF(a);
3410 Py_DECREF(b);
3411 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003412}
3413
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003414
3415/* Bitwise and/xor/or operations */
3416
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003417static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003418long_bitwise(PyLongObject *a,
3419 int op, /* '&', '|', '^' */
3420 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003421{
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003422 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003423 int negz;
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00003424 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003425 PyLongObject *z;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003426 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003427 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003428
Christian Heimese93237d2007-12-19 02:37:44 +00003429 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003430 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003431 if (a == NULL)
3432 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003433 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003434 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003435 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003436 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003437 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003438 }
Christian Heimese93237d2007-12-19 02:37:44 +00003439 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003440 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003441 if (b == NULL) {
3442 Py_DECREF(a);
3443 return NULL;
3444 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003445 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003446 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003447 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003448 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003449 maskb = 0;
3450 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003451
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003452 negz = 0;
3453 switch (op) {
3454 case '^':
3455 if (maska != maskb) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003456 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003457 negz = -1;
3458 }
3459 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003460 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003461 if (maska && maskb) {
3462 op = '|';
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003463 maska ^= PyLong_MASK;
3464 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003465 negz = -1;
3466 }
3467 break;
3468 case '|':
3469 if (maska || maskb) {
3470 op = '&';
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003471 maska ^= PyLong_MASK;
3472 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003473 negz = -1;
3474 }
3475 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003476 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003477
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003478 /* JRH: The original logic here was to allocate the result value (z)
3479 as the longer of the two operands. However, there are some cases
3480 where the result is guaranteed to be shorter than that: AND of two
3481 positives, OR of two negatives: use the shorter number. AND with
3482 mixed signs: use the positive number. OR with mixed signs: use the
3483 negative number. After the transformations above, op will be '&'
3484 iff one of these cases applies, and mask will be non-0 for operands
3485 whose length should be ignored.
3486 */
3487
Christian Heimese93237d2007-12-19 02:37:44 +00003488 size_a = Py_SIZE(a);
3489 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003490 size_z = op == '&'
3491 ? (maska
3492 ? size_b
3493 : (maskb ? size_a : MIN(size_a, size_b)))
3494 : MAX(size_a, size_b);
3495 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003496 if (z == NULL) {
Neal Norwitzef02b9e2006-07-16 02:00:32 +00003497 Py_DECREF(a);
3498 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003499 return NULL;
3500 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003501
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003502 for (i = 0; i < size_z; ++i) {
3503 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3504 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3505 switch (op) {
3506 case '&': z->ob_digit[i] = diga & digb; break;
3507 case '|': z->ob_digit[i] = diga | digb; break;
3508 case '^': z->ob_digit[i] = diga ^ digb; break;
3509 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003510 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003511
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003512 Py_DECREF(a);
3513 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003514 z = long_normalize(z);
3515 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003516 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003517 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003518 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003519 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003520}
3521
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003522static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003523long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003524{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003525 PyLongObject *a, *b;
3526 PyObject *c;
3527 CONVERT_BINOP(v, w, &a, &b);
3528 c = long_bitwise(a, '&', b);
3529 Py_DECREF(a);
3530 Py_DECREF(b);
3531 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003532}
3533
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003534static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003535long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003536{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003537 PyLongObject *a, *b;
3538 PyObject *c;
3539 CONVERT_BINOP(v, w, &a, &b);
3540 c = long_bitwise(a, '^', b);
3541 Py_DECREF(a);
3542 Py_DECREF(b);
3543 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003544}
3545
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003546static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003547long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003548{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003549 PyLongObject *a, *b;
3550 PyObject *c;
3551 CONVERT_BINOP(v, w, &a, &b);
3552 c = long_bitwise(a, '|', b);
3553 Py_DECREF(a);
3554 Py_DECREF(b);
3555 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003556}
3557
Guido van Rossum234f9421993-06-17 12:35:49 +00003558static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003559long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003560{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003561 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003562 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Georg Brandlc02e1312007-04-11 17:16:24 +00003563 if (*pw == NULL)
3564 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003565 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003566 return 0;
3567 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003568 else if (PyLong_Check(*pw)) {
3569 Py_INCREF(*pv);
3570 Py_INCREF(*pw);
3571 return 0;
3572 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003573 return 1; /* Can't do it */
3574}
3575
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003576static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003577long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003578{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003579 if (PyLong_CheckExact(v))
3580 Py_INCREF(v);
3581 else
3582 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003583 return v;
3584}
3585
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003586static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003587long_int(PyObject *v)
3588{
3589 long x;
3590 x = PyLong_AsLong(v);
3591 if (PyErr_Occurred()) {
3592 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3593 PyErr_Clear();
3594 if (PyLong_CheckExact(v)) {
3595 Py_INCREF(v);
3596 return v;
3597 }
3598 else
3599 return _PyLong_Copy((PyLongObject *)v);
3600 }
3601 else
3602 return NULL;
3603 }
3604 return PyInt_FromLong(x);
3605}
3606
3607static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003608long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003609{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003610 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003611 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003612 if (result == -1.0 && PyErr_Occurred())
3613 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003614 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003615}
3616
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003617static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003618long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003619{
Eric Smith5e527eb2008-02-10 01:36:53 +00003620 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003621}
3622
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003623static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003624long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003625{
Eric Smith5e527eb2008-02-10 01:36:53 +00003626 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003627}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003628
3629static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003630long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003631
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632static PyObject *
3633long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3634{
3635 PyObject *x = NULL;
3636 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003637 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638
Guido van Rossumbef14172001-08-29 15:47:46 +00003639 if (type != &PyLong_Type)
3640 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003641 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3642 &x, &base))
3643 return NULL;
3644 if (x == NULL)
3645 return PyLong_FromLong(0L);
3646 if (base == -909)
3647 return PyNumber_Long(x);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003648 else if (PyString_Check(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003649 /* Since PyLong_FromString doesn't have a length parameter,
3650 * check here for possible NULs in the string. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003651 char *string = PyString_AS_STRING(x);
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003652 if (strlen(string) != (size_t)PyString_Size(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003653 /* create a repr() of the input string,
3654 * just like PyLong_FromString does. */
3655 PyObject *srepr;
3656 srepr = PyObject_Repr(x);
3657 if (srepr == NULL)
3658 return NULL;
3659 PyErr_Format(PyExc_ValueError,
3660 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003661 base, PyString_AS_STRING(srepr));
Georg Brandl00cd8182007-03-06 18:41:12 +00003662 Py_DECREF(srepr);
3663 return NULL;
3664 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003665 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Georg Brandl00cd8182007-03-06 18:41:12 +00003666 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003667#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003668 else if (PyUnicode_Check(x))
3669 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3670 PyUnicode_GET_SIZE(x),
3671 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003672#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673 else {
3674 PyErr_SetString(PyExc_TypeError,
3675 "long() can't convert non-string with explicit base");
3676 return NULL;
3677 }
3678}
3679
Guido van Rossumbef14172001-08-29 15:47:46 +00003680/* Wimpy, slow approach to tp_new calls for subtypes of long:
3681 first create a regular long from whatever arguments we got,
3682 then allocate a subtype instance and initialize it from
3683 the regular long. The regular long is then thrown away.
3684*/
3685static PyObject *
3686long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3687{
Anthony Baxter377be112006-04-11 06:54:30 +00003688 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003689 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003690
3691 assert(PyType_IsSubtype(type, &PyLong_Type));
3692 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3693 if (tmp == NULL)
3694 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003695 assert(PyLong_CheckExact(tmp));
Christian Heimese93237d2007-12-19 02:37:44 +00003696 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003697 if (n < 0)
3698 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00003699 newobj = (PyLongObject *)type->tp_alloc(type, n);
3700 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003701 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003702 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003703 }
Anthony Baxter377be112006-04-11 06:54:30 +00003704 assert(PyLong_Check(newobj));
Christian Heimese93237d2007-12-19 02:37:44 +00003705 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003706 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00003707 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003708 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00003709 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003710}
3711
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003712static PyObject *
3713long_getnewargs(PyLongObject *v)
3714{
3715 return Py_BuildValue("(N)", _PyLong_Copy(v));
3716}
3717
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003718static PyObject *
Mark Dickinsond4b5c982009-05-02 17:55:01 +00003719long_get0(PyLongObject *v, void *context) {
3720 return PyLong_FromLong(0L);
3721}
3722
3723static PyObject *
3724long_get1(PyLongObject *v, void *context) {
3725 return PyLong_FromLong(1L);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003726}
3727
Eric Smitha9f7d622008-02-17 19:46:49 +00003728static PyObject *
3729long__format__(PyObject *self, PyObject *args)
3730{
3731 PyObject *format_spec;
3732
3733 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3734 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00003735 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00003736 return _PyLong_FormatAdvanced(self,
3737 PyBytes_AS_STRING(format_spec),
3738 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003739 if (PyUnicode_Check(format_spec)) {
3740 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00003741 PyObject *result;
3742 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003743
Eric Smithdc13b792008-05-30 18:10:04 +00003744 if (str_spec == NULL)
3745 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00003746
Eric Smithdc13b792008-05-30 18:10:04 +00003747 result = _PyLong_FormatAdvanced(self,
3748 PyBytes_AS_STRING(str_spec),
3749 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003750
Eric Smithdc13b792008-05-30 18:10:04 +00003751 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003752 return result;
3753 }
3754 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
3755 return NULL;
3756}
3757
Robert Schuppenies51df0642008-06-01 16:16:17 +00003758static PyObject *
3759long_sizeof(PyLongObject *v)
3760{
3761 Py_ssize_t res;
3762
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003763 res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
Robert Schuppenies51df0642008-06-01 16:16:17 +00003764 return PyInt_FromSsize_t(res);
3765}
3766
Mark Dickinson1a707982008-12-17 16:14:37 +00003767static PyObject *
3768long_bit_length(PyLongObject *v)
3769{
3770 PyLongObject *result, *x, *y;
3771 Py_ssize_t ndigits, msd_bits = 0;
3772 digit msd;
3773
3774 assert(v != NULL);
3775 assert(PyLong_Check(v));
3776
3777 ndigits = ABS(Py_SIZE(v));
3778 if (ndigits == 0)
3779 return PyInt_FromLong(0);
3780
3781 msd = v->ob_digit[ndigits-1];
3782 while (msd >= 32) {
3783 msd_bits += 6;
3784 msd >>= 6;
3785 }
3786 msd_bits += (long)(BitLengthTable[msd]);
3787
3788 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3789 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3790
3791 /* expression above may overflow; use Python integers instead */
3792 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3793 if (result == NULL)
3794 return NULL;
3795 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3796 if (x == NULL)
3797 goto error;
3798 y = (PyLongObject *)long_mul(result, x);
3799 Py_DECREF(x);
3800 if (y == NULL)
3801 goto error;
3802 Py_DECREF(result);
3803 result = y;
3804
3805 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3806 if (x == NULL)
3807 goto error;
3808 y = (PyLongObject *)long_add(result, x);
3809 Py_DECREF(x);
3810 if (y == NULL)
3811 goto error;
3812 Py_DECREF(result);
3813 result = y;
3814
3815 return (PyObject *)result;
3816
3817error:
3818 Py_DECREF(result);
3819 return NULL;
3820}
3821
3822PyDoc_STRVAR(long_bit_length_doc,
3823"long.bit_length() -> int or long\n\
3824\n\
3825Number of bits necessary to represent self in binary.\n\
3826>>> bin(37L)\n\
3827'0b100101'\n\
3828>>> (37L).bit_length()\n\
38296");
3830
Christian Heimes6f341092008-04-18 23:13:07 +00003831#if 0
3832static PyObject *
3833long_is_finite(PyObject *v)
3834{
3835 Py_RETURN_TRUE;
3836}
3837#endif
3838
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003839static PyMethodDef long_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003840 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3841 "Returns self, the complex conjugate of any long."},
Mark Dickinson1a707982008-12-17 16:14:37 +00003842 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3843 long_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00003844#if 0
3845 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3846 "Returns always True."},
3847#endif
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003848 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3849 "Truncating an Integral returns itself."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003850 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smitha9f7d622008-02-17 19:46:49 +00003851 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Robert Schuppenies51df0642008-06-01 16:16:17 +00003852 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00003853 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003854 {NULL, NULL} /* sentinel */
3855};
3856
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003857static PyGetSetDef long_getset[] = {
Mark Dickinsond4b5c982009-05-02 17:55:01 +00003858 {"real",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003859 (getter)long_long, (setter)NULL,
3860 "the real part of a complex number",
3861 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00003862 {"imag",
3863 (getter)long_get0, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003864 "the imaginary part of a complex number",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00003865 NULL},
3866 {"numerator",
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003867 (getter)long_long, (setter)NULL,
3868 "the numerator of a rational number in lowest terms",
3869 NULL},
Mark Dickinsond4b5c982009-05-02 17:55:01 +00003870 {"denominator",
3871 (getter)long_get1, (setter)NULL,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003872 "the denominator of a rational number in lowest terms",
Mark Dickinsond4b5c982009-05-02 17:55:01 +00003873 NULL},
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003874 {NULL} /* Sentinel */
3875};
3876
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003877PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003878"long(x[, base]) -> integer\n\
3879\n\
3880Convert a string or number to a long integer, if possible. A floating\n\
3881point argument will be truncated towards zero (this does not include a\n\
3882string representation of a floating point number!) When converting a\n\
3883string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003884converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003886static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003887 (binaryfunc) long_add, /*nb_add*/
3888 (binaryfunc) long_sub, /*nb_subtract*/
3889 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00003890 long_classic_div, /*nb_divide*/
3891 long_mod, /*nb_remainder*/
3892 long_divmod, /*nb_divmod*/
3893 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003894 (unaryfunc) long_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003895 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003896 (unaryfunc) long_abs, /*tp_absolute*/
3897 (inquiry) long_nonzero, /*tp_nonzero*/
3898 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00003899 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003900 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00003901 long_and, /*nb_and*/
3902 long_xor, /*nb_xor*/
3903 long_or, /*nb_or*/
3904 long_coerce, /*nb_coerce*/
3905 long_int, /*nb_int*/
3906 long_long, /*nb_long*/
3907 long_float, /*nb_float*/
3908 long_oct, /*nb_oct*/
3909 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003910 0, /* nb_inplace_add */
3911 0, /* nb_inplace_subtract */
3912 0, /* nb_inplace_multiply */
3913 0, /* nb_inplace_divide */
3914 0, /* nb_inplace_remainder */
3915 0, /* nb_inplace_power */
3916 0, /* nb_inplace_lshift */
3917 0, /* nb_inplace_rshift */
3918 0, /* nb_inplace_and */
3919 0, /* nb_inplace_xor */
3920 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00003921 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003922 long_true_divide, /* nb_true_divide */
3923 0, /* nb_inplace_floor_divide */
3924 0, /* nb_inplace_true_divide */
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003925 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003926};
3927
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003928PyTypeObject PyLong_Type = {
3929 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003930 0, /* ob_size */
3931 "long", /* tp_name */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003932 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003933 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003934 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003935 0, /* tp_print */
3936 0, /* tp_getattr */
3937 0, /* tp_setattr */
3938 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003939 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003940 &long_as_number, /* tp_as_number */
3941 0, /* tp_as_sequence */
3942 0, /* tp_as_mapping */
3943 (hashfunc)long_hash, /* tp_hash */
3944 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003945 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003946 PyObject_GenericGetAttr, /* tp_getattro */
3947 0, /* tp_setattro */
3948 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003949 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003950 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003951 long_doc, /* tp_doc */
3952 0, /* tp_traverse */
3953 0, /* tp_clear */
3954 0, /* tp_richcompare */
3955 0, /* tp_weaklistoffset */
3956 0, /* tp_iter */
3957 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003958 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003959 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003960 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003961 0, /* tp_base */
3962 0, /* tp_dict */
3963 0, /* tp_descr_get */
3964 0, /* tp_descr_set */
3965 0, /* tp_dictoffset */
3966 0, /* tp_init */
3967 0, /* tp_alloc */
3968 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003969 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003970};
Mark Dickinsonefc82f72009-03-20 15:51:55 +00003971
3972static PyTypeObject Long_InfoType;
3973
3974PyDoc_STRVAR(long_info__doc__,
3975"sys.long_info\n\
3976\n\
3977A struct sequence that holds information about Python's\n\
3978internal representation of integers. The attributes are read only.");
3979
3980static PyStructSequence_Field long_info_fields[] = {
3981 {"bits_per_digit", "size of a digit in bits"},
3982 {"sizeof_digit", "size in bytes of the C type used to "
3983 "represent a digit"},
3984 {NULL, NULL}
3985};
3986
3987static PyStructSequence_Desc long_info_desc = {
3988 "sys.long_info", /* name */
3989 long_info__doc__, /* doc */
3990 long_info_fields, /* fields */
3991 2 /* number of fields */
3992};
3993
3994PyObject *
3995PyLong_GetInfo(void)
3996{
3997 PyObject* long_info;
3998 int field = 0;
3999 long_info = PyStructSequence_New(&Long_InfoType);
4000 if (long_info == NULL)
4001 return NULL;
Mark Dickinson48e3fd22009-04-02 18:39:37 +00004002 PyStructSequence_SET_ITEM(long_info, field++,
4003 PyInt_FromLong(PyLong_SHIFT));
4004 PyStructSequence_SET_ITEM(long_info, field++,
4005 PyInt_FromLong(sizeof(digit)));
Mark Dickinsonefc82f72009-03-20 15:51:55 +00004006 if (PyErr_Occurred()) {
4007 Py_CLEAR(long_info);
4008 return NULL;
4009 }
4010 return long_info;
4011}
4012
4013int
4014_PyLong_Init(void)
4015{
4016 /* initialize long_info */
4017 if (Long_InfoType.tp_name == 0)
4018 PyStructSequence_InitType(&Long_InfoType, &long_info_desc);
4019 return 1;
4020}