blob: b46ce4eb479eb7403dc71ac5be7a9190c6783943 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Mark Dickinsonbd792642009-03-18 20:06:12 +00007#include "structseq.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Mark Dickinsonc6300392009-04-20 21:38:00 +00009#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000011#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000012
Guido van Rossumddefaf32007-01-14 03:31:43 +000013#ifndef NSMALLPOSINTS
14#define NSMALLPOSINTS 257
15#endif
16#ifndef NSMALLNEGINTS
17#define NSMALLNEGINTS 5
18#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000019
Mark Dickinsone4416742009-02-15 15:14:57 +000020/* convert a PyLong of size 1, 0 or -1 to an sdigit */
21#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
22 (Py_SIZE(x) == 0 ? (sdigit)0 : \
23 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024#define ABS(x) ((x) < 0 ? -(x) : (x))
25
Guido van Rossumddefaf32007-01-14 03:31:43 +000026#if NSMALLNEGINTS + NSMALLPOSINTS > 0
27/* Small integers are preallocated in this array so that they
28 can be shared.
29 The integers that are preallocated are those in the range
30 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
31*/
32static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
33#ifdef COUNT_ALLOCS
34int quick_int_allocs, quick_neg_int_allocs;
35#endif
36
Guido van Rossum7eaf8222007-06-18 17:58:50 +000037static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000038get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000039{
40 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
41 Py_INCREF(v);
42#ifdef COUNT_ALLOCS
43 if (ival >= 0)
44 quick_int_allocs++;
45 else
46 quick_neg_int_allocs++;
47#endif
48 return v;
49}
50#define CHECK_SMALL_INT(ival) \
51 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
Mark Dickinson0d4785b2009-02-15 17:27:41 +000052 return get_small_int((sdigit)ival); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000053 } while(0)
54
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055static PyLongObject *
56maybe_small_long(PyLongObject *v)
57{
58 if (v && ABS(Py_SIZE(v)) <= 1) {
Mark Dickinsone4416742009-02-15 15:14:57 +000059 sdigit ival = MEDIUM_VALUE(v);
Facundo Batista6e6f59b2008-07-24 18:57:11 +000060 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
61 Py_DECREF(v);
62 return (PyLongObject *)get_small_int(ival);
63 }
64 }
65 return v;
66}
Guido van Rossumddefaf32007-01-14 03:31:43 +000067#else
68#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000070#endif
71
Guido van Rossumddefaf32007-01-14 03:31:43 +000072/* If a freshly-allocated long is already shared, it must
73 be a small integer, so negating it must go to PyLong_FromLong */
74#define NEGATE(x) \
Christian Heimes90aa7642007-12-19 02:45:37 +000075 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
Christian Heimes217cfd12007-12-02 14:31:20 +000076 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000077 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
78 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000079/* For long multiplication, use the O(N**2) school algorithm unless
80 * both operands contain more than KARATSUBA_CUTOFF digits (this
81 * being an internal Python long digit, in base BASE).
82 */
Tim Peters0973b992004-08-29 22:16:50 +000083#define KARATSUBA_CUTOFF 70
84#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000085
Tim Peters47e52ee2004-08-30 02:44:38 +000086/* For exponentiation, use the binary left-to-right algorithm
87 * unless the exponent contains more than FIVEARY_CUTOFF digits.
88 * In that case, do 5 bits at a time. The potential drawback is that
89 * a table of 2**5 intermediate results is computed.
90 */
91#define FIVEARY_CUTOFF 8
92
Tim Peters5af4e6c2002-08-12 02:31:19 +000093#undef MIN
94#undef MAX
95#define MAX(x, y) ((x) < (y) ? (y) : (x))
96#define MIN(x, y) ((x) > (y) ? (y) : (x))
97
Guido van Rossumc0b618a1997-05-02 03:12:38 +000098#define SIGCHECK(PyTryBlock) \
Antoine Pitrou074e5ed2009-11-10 19:50:40 +000099 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000100
Mark Dickinsonc6300392009-04-20 21:38:00 +0000101/* forward declaration */
102static int bits_in_digit(digit d);
103
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000104/* Normalize (remove leading zeros from) a long int object.
105 Doesn't attempt to free the storage--in most cases, due to the nature
106 of the algorithms used, this could save at most be one word anyway. */
107
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000109long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000110{
Christian Heimes90aa7642007-12-19 02:45:37 +0000111 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000112 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000113
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000114 while (i > 0 && v->ob_digit[i-1] == 0)
115 --i;
116 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000117 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000118 return v;
119}
120
121/* Allocate a new long int object with size digits.
122 Return NULL and set exception if we run out of memory. */
123
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124#define MAX_LONG_DIGITS \
125 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
126
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000128_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000129{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000130 PyLongObject *result;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000131 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
132 sizeof(digit)*size. Previous incarnations of this code used
133 sizeof(PyVarObject) instead of the offsetof, but this risks being
134 incorrect in the presence of padding between the PyVarObject header
135 and the digits. */
Mark Dickinsone4416742009-02-15 15:14:57 +0000136 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000137 PyErr_SetString(PyExc_OverflowError,
138 "too many digits in integer");
139 return NULL;
140 }
141 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
Guido van Rossumddefaf32007-01-14 03:31:43 +0000142 size*sizeof(digit));
143 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000144 PyErr_NoMemory();
145 return NULL;
146 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000147 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000148}
149
Tim Peters64b5ce32001-09-10 20:52:51 +0000150PyObject *
151_PyLong_Copy(PyLongObject *src)
152{
153 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000154 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000155
156 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000157 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000158 if (i < 0)
159 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000160 if (i < 2) {
Mark Dickinsone4416742009-02-15 15:14:57 +0000161 sdigit ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000162 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000163 ival = -ival;
164 CHECK_SMALL_INT(ival);
165 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000166 result = _PyLong_New(i);
167 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000168 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000169 while (--i >= 0)
170 result->ob_digit[i] = src->ob_digit[i];
171 }
172 return (PyObject *)result;
173}
174
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000175/* Create a new long int object from a C long int */
176
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000177PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000178PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000179{
Tim Petersce9de2f2001-06-14 04:56:19 +0000180 PyLongObject *v;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000181 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000182 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
183 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000184 int sign = 1;
185
186 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000187
188 if (ival < 0) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000189 /* negate: can't write this as abs_ival = -ival since that
190 invokes undefined behaviour when ival is LONG_MIN */
191 abs_ival = 0U-(unsigned long)ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000192 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000193 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000194 else {
195 abs_ival = (unsigned long)ival;
196 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000197
Mark Dickinsond4624c32009-01-24 15:02:35 +0000198 /* Fast path for single-digit ints */
199 if (!(abs_ival >> PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000200 v = _PyLong_New(1);
201 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000202 Py_SIZE(v) = sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000203 v->ob_digit[0] = Py_SAFE_DOWNCAST(
204 abs_ival, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000205 }
206 return (PyObject*)v;
207 }
208
Mark Dickinson249b8982009-04-27 19:41:00 +0000209#if PyLong_SHIFT==15
Guido van Rossumddefaf32007-01-14 03:31:43 +0000210 /* 2 digits */
Mark Dickinsond4624c32009-01-24 15:02:35 +0000211 if (!(abs_ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000212 v = _PyLong_New(2);
213 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000214 Py_SIZE(v) = 2*sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000215 v->ob_digit[0] = Py_SAFE_DOWNCAST(
216 abs_ival & PyLong_MASK, unsigned long, digit);
217 v->ob_digit[1] = Py_SAFE_DOWNCAST(
218 abs_ival >> PyLong_SHIFT, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000219 }
220 return (PyObject*)v;
221 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000222#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000223
224 /* Larger numbers: loop to determine number of digits */
Christian Heimesdae2a892008-04-19 00:55:37 +0000225 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000226 while (t) {
227 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000228 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000229 }
230 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000231 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000232 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000233 Py_SIZE(v) = ndigits*sign;
Christian Heimesdae2a892008-04-19 00:55:37 +0000234 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000235 while (t) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000236 *p++ = Py_SAFE_DOWNCAST(
237 t & PyLong_MASK, unsigned long, digit);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000238 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000239 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000240 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000241 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000242}
243
Guido van Rossum53756b11997-01-03 17:14:46 +0000244/* Create a new long int object from a C unsigned long int */
245
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000247PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000248{
Tim Petersce9de2f2001-06-14 04:56:19 +0000249 PyLongObject *v;
250 unsigned long t;
251 int ndigits = 0;
252
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000253 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000254 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000255 /* Count the number of Python digits. */
256 t = (unsigned long)ival;
257 while (t) {
258 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000259 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000260 }
261 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000262 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000263 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000264 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000265 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000266 *p++ = (digit)(ival & PyLong_MASK);
267 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000268 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000269 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000270 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000271}
272
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000273/* Create a new long int object from a C double */
274
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000275PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000276PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000277{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000278 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000279 double frac;
280 int i, ndig, expo, neg;
281 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000282 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000283 PyErr_SetString(PyExc_OverflowError,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000284 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000285 return NULL;
286 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000287 if (Py_IS_NAN(dval)) {
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000288 PyErr_SetString(PyExc_ValueError,
289 "cannot convert float NaN to integer");
Christian Heimes386cd1e2008-01-15 02:01:20 +0000290 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000291 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000292 if (dval < 0.0) {
293 neg = 1;
294 dval = -dval;
295 }
296 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
297 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000298 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000299 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000300 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000301 if (v == NULL)
302 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000303 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000304 for (i = ndig; --i >= 0; ) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000305 digit bits = (digit)frac;
306 v->ob_digit[i] = bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000307 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000308 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000309 }
310 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000311 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000313}
314
Thomas Wouters89f507f2006-12-13 04:49:30 +0000315/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
316 * anything about what happens when a signed integer operation overflows,
317 * and some compilers think they're doing you a favor by being "clever"
318 * then. The bit pattern for the largest postive signed long is
319 * (unsigned long)LONG_MAX, and for the smallest negative signed long
320 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
321 * However, some other compilers warn about applying unary minus to an
322 * unsigned operand. Hence the weird "0-".
323 */
324#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
325#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
326
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000327/* Get a C long int from a long int object.
328 Returns -1 and sets an error condition if overflow occurs. */
329
330long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000331PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000332{
Guido van Rossumf7531811998-05-26 14:33:37 +0000333 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000334 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000335 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000336 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000337 Py_ssize_t i;
338 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000339 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000340
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000341 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000342 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000344 return -1;
345 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000346
347 if (!PyLong_Check(vv)) {
348 PyNumberMethods *nb;
349 if ((nb = vv->ob_type->tp_as_number) == NULL ||
350 nb->nb_int == NULL) {
351 PyErr_SetString(PyExc_TypeError, "an integer is required");
352 return -1;
353 }
354 vv = (*nb->nb_int) (vv);
355 if (vv == NULL)
356 return -1;
357 do_decref = 1;
358 if (!PyLong_Check(vv)) {
359 Py_DECREF(vv);
360 PyErr_SetString(PyExc_TypeError,
361 "nb_int should return int object");
362 return -1;
363 }
364 }
365
Georg Brandl61c31b02007-02-26 14:46:30 +0000366 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000368 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000369
Georg Brandl61c31b02007-02-26 14:46:30 +0000370 switch (i) {
371 case -1:
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000372 res = -(sdigit)v->ob_digit[0];
Georg Brandl61c31b02007-02-26 14:46:30 +0000373 break;
374 case 0:
375 res = 0;
376 break;
377 case 1:
378 res = v->ob_digit[0];
379 break;
380 default:
381 sign = 1;
382 x = 0;
383 if (i < 0) {
384 sign = -1;
385 i = -(i);
386 }
387 while (--i >= 0) {
388 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000389 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000390 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000391 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000392 goto exit;
393 }
394 }
395 /* Haven't lost any bits, but casting to long requires extra care
396 * (see comment above).
397 */
398 if (x <= (unsigned long)LONG_MAX) {
399 res = (long)x * sign;
400 }
401 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
402 res = LONG_MIN;
403 }
404 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000405 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000406 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000407 }
408 }
409 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000410 if (do_decref) {
411 Py_DECREF(vv);
412 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000413 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000414}
415
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000416long
417PyLong_AsLong(PyObject *obj)
418{
419 int overflow;
420 long result = PyLong_AsLongAndOverflow(obj, &overflow);
421 if (overflow) {
422 /* XXX: could be cute and give a different
423 message for overflow == -1 */
424 PyErr_SetString(PyExc_OverflowError,
425 "Python int too large to convert to C long");
426 }
427 return result;
428}
429
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000430/* Get a Py_ssize_t from a long int object.
431 Returns -1 and sets an error condition if overflow occurs. */
432
433Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000434PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000435 register PyLongObject *v;
436 size_t x, prev;
437 Py_ssize_t i;
438 int sign;
439
440 if (vv == NULL || !PyLong_Check(vv)) {
441 PyErr_BadInternalCall();
442 return -1;
443 }
444 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000445 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000446 switch (i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000447 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +0000448 case 0: return 0;
449 case 1: return v->ob_digit[0];
450 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000451 sign = 1;
452 x = 0;
453 if (i < 0) {
454 sign = -1;
455 i = -(i);
456 }
457 while (--i >= 0) {
458 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000459 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000460 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000461 goto overflow;
462 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463 /* Haven't lost any bits, but casting to a signed type requires
464 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000465 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466 if (x <= (size_t)PY_SSIZE_T_MAX) {
467 return (Py_ssize_t)x * sign;
468 }
469 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
470 return PY_SSIZE_T_MIN;
471 }
472 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000473
474 overflow:
475 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000476 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000477 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000478}
479
Guido van Rossumd8c80482002-08-13 00:24:58 +0000480/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000481 Returns -1 and sets an error condition if overflow occurs. */
482
483unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000484PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000485{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000487 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000488 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000489
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 if (vv == NULL || !PyLong_Check(vv)) {
491 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000492 return (unsigned long) -1;
493 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000494 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000495 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000496 x = 0;
497 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000498 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000499 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000500 return (unsigned long) -1;
501 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000502 switch (i) {
503 case 0: return 0;
504 case 1: return v->ob_digit[0];
505 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000506 while (--i >= 0) {
507 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000508 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000509 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000510 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000511 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000512 return (unsigned long) -1;
513 }
514 }
515 return x;
516}
517
518/* Get a C unsigned long int from a long int object.
519 Returns -1 and sets an error condition if overflow occurs. */
520
521size_t
522PyLong_AsSize_t(PyObject *vv)
523{
524 register PyLongObject *v;
525 size_t x, prev;
526 Py_ssize_t i;
527
528 if (vv == NULL || !PyLong_Check(vv)) {
529 PyErr_BadInternalCall();
530 return (unsigned long) -1;
531 }
532 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000533 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000534 x = 0;
535 if (i < 0) {
536 PyErr_SetString(PyExc_OverflowError,
537 "can't convert negative value to size_t");
538 return (size_t) -1;
539 }
540 switch (i) {
541 case 0: return 0;
542 case 1: return v->ob_digit[0];
543 }
544 while (--i >= 0) {
545 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000546 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000547 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000548 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000549 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000550 return (unsigned long) -1;
551 }
552 }
553 return x;
554}
555
Thomas Hellera4ea6032003-04-17 18:55:45 +0000556/* Get a C unsigned long int from a long int object, ignoring the high bits.
557 Returns -1 and sets an error condition if an error occurs. */
558
Guido van Rossumddefaf32007-01-14 03:31:43 +0000559static unsigned long
560_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000561{
562 register PyLongObject *v;
563 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000564 Py_ssize_t i;
565 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000566
567 if (vv == NULL || !PyLong_Check(vv)) {
568 PyErr_BadInternalCall();
569 return (unsigned long) -1;
570 }
571 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000572 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000573 switch (i) {
574 case 0: return 0;
575 case 1: return v->ob_digit[0];
576 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000577 sign = 1;
578 x = 0;
579 if (i < 0) {
580 sign = -1;
581 i = -i;
582 }
583 while (--i >= 0) {
Mark Dickinson24f57852009-09-28 17:54:52 +0000584 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000585 }
586 return x * sign;
587}
588
Guido van Rossumddefaf32007-01-14 03:31:43 +0000589unsigned long
590PyLong_AsUnsignedLongMask(register PyObject *op)
591{
592 PyNumberMethods *nb;
593 PyLongObject *lo;
594 unsigned long val;
595
596 if (op && PyLong_Check(op))
597 return _PyLong_AsUnsignedLongMask(op);
598
599 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
600 nb->nb_int == NULL) {
601 PyErr_SetString(PyExc_TypeError, "an integer is required");
602 return (unsigned long)-1;
603 }
604
605 lo = (PyLongObject*) (*nb->nb_int) (op);
606 if (lo == NULL)
607 return (unsigned long)-1;
608 if (PyLong_Check(lo)) {
609 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
610 Py_DECREF(lo);
611 if (PyErr_Occurred())
612 return (unsigned long)-1;
613 return val;
614 }
615 else
616 {
617 Py_DECREF(lo);
618 PyErr_SetString(PyExc_TypeError,
619 "nb_int should return int object");
620 return (unsigned long)-1;
621 }
622}
623
Tim Peters5b8132f2003-01-31 15:52:05 +0000624int
625_PyLong_Sign(PyObject *vv)
626{
627 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000628
629 assert(v != NULL);
630 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000631
Christian Heimes90aa7642007-12-19 02:45:37 +0000632 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000633}
634
Tim Petersbaefd9e2003-01-28 20:37:45 +0000635size_t
636_PyLong_NumBits(PyObject *vv)
637{
638 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000639 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000640 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000641
642 assert(v != NULL);
643 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000644 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000645 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
646 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000647 digit msd = v->ob_digit[ndigits - 1];
648
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000649 result = (ndigits - 1) * PyLong_SHIFT;
650 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000651 goto Overflow;
652 do {
653 ++result;
654 if (result == 0)
655 goto Overflow;
656 msd >>= 1;
657 } while (msd);
658 }
659 return result;
660
661Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000662 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000663 "to express in a platform size_t");
664 return (size_t)-1;
665}
666
Tim Peters2a9b3672001-06-11 21:23:58 +0000667PyObject *
668_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
669 int little_endian, int is_signed)
670{
671 const unsigned char* pstartbyte;/* LSB of bytes */
672 int incr; /* direction to move pstartbyte */
673 const unsigned char* pendbyte; /* MSB of bytes */
674 size_t numsignificantbytes; /* number of bytes that matter */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000675 Py_ssize_t ndigits; /* number of Python long digits */
Tim Peters2a9b3672001-06-11 21:23:58 +0000676 PyLongObject* v; /* result */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000677 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000678
679 if (n == 0)
680 return PyLong_FromLong(0L);
681
682 if (little_endian) {
683 pstartbyte = bytes;
684 pendbyte = bytes + n - 1;
685 incr = 1;
686 }
687 else {
688 pstartbyte = bytes + n - 1;
689 pendbyte = bytes;
690 incr = -1;
691 }
692
693 if (is_signed)
694 is_signed = *pendbyte >= 0x80;
695
696 /* Compute numsignificantbytes. This consists of finding the most
697 significant byte. Leading 0 bytes are insignficant if the number
698 is positive, and leading 0xff bytes if negative. */
699 {
700 size_t i;
701 const unsigned char* p = pendbyte;
702 const int pincr = -incr; /* search MSB to LSB */
703 const unsigned char insignficant = is_signed ? 0xff : 0x00;
704
705 for (i = 0; i < n; ++i, p += pincr) {
706 if (*p != insignficant)
707 break;
708 }
709 numsignificantbytes = n - i;
710 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
711 actually has 2 significant bytes. OTOH, 0xff0001 ==
712 -0x00ffff, so we wouldn't *need* to bump it there; but we
713 do for 0xffff = -0x0001. To be safe without bothering to
714 check every case, bump it regardless. */
715 if (is_signed && numsignificantbytes < n)
716 ++numsignificantbytes;
717 }
718
719 /* How many Python long digits do we need? We have
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000720 8*numsignificantbytes bits, and each Python long digit has
721 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
722 /* catch overflow before it happens */
723 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
724 PyErr_SetString(PyExc_OverflowError,
725 "byte array too long to convert to int");
726 return NULL;
727 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000728 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000729 v = _PyLong_New(ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000730 if (v == NULL)
731 return NULL;
732
733 /* Copy the bits over. The tricky parts are computing 2's-comp on
734 the fly for signed numbers, and dealing with the mismatch between
735 8-bit bytes and (probably) 15-bit Python digits.*/
736 {
737 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000738 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000739 twodigits accum = 0; /* sliding register */
740 unsigned int accumbits = 0; /* number of bits in accum */
741 const unsigned char* p = pstartbyte;
742
743 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000744 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000745 /* Compute correction for 2's comp, if needed. */
746 if (is_signed) {
747 thisbyte = (0xff ^ thisbyte) + carry;
748 carry = thisbyte >> 8;
749 thisbyte &= 0xff;
750 }
751 /* Because we're going LSB to MSB, thisbyte is
752 more significant than what's already in accum,
753 so needs to be prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000754 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000755 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000756 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000757 /* There's enough to fill a Python digit. */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000758 assert(idigit < ndigits);
759 v->ob_digit[idigit] = (digit)(accum &
760 PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000761 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000762 accum >>= PyLong_SHIFT;
763 accumbits -= PyLong_SHIFT;
764 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000765 }
766 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000767 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000768 if (accumbits) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000769 assert(idigit < ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000770 v->ob_digit[idigit] = (digit)accum;
771 ++idigit;
772 }
773 }
774
Christian Heimes90aa7642007-12-19 02:45:37 +0000775 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000776 return (PyObject *)long_normalize(v);
777}
778
779int
780_PyLong_AsByteArray(PyLongObject* v,
781 unsigned char* bytes, size_t n,
782 int little_endian, int is_signed)
783{
Mark Dickinson17e55872009-01-24 15:56:57 +0000784 Py_ssize_t i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000785 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000786 twodigits accum; /* sliding register */
787 unsigned int accumbits; /* # bits in accum */
788 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
Mark Dickinson1e2d8702009-01-25 22:25:06 +0000789 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000790 size_t j; /* # bytes filled */
791 unsigned char* p; /* pointer to next byte in bytes */
792 int pincr; /* direction to move p */
793
794 assert(v != NULL && PyLong_Check(v));
795
Christian Heimes90aa7642007-12-19 02:45:37 +0000796 if (Py_SIZE(v) < 0) {
797 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000798 if (!is_signed) {
Mark Dickinson21776072009-02-10 16:13:25 +0000799 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000800 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000801 return -1;
802 }
803 do_twos_comp = 1;
804 }
805 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000806 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000807 do_twos_comp = 0;
808 }
809
810 if (little_endian) {
811 p = bytes;
812 pincr = 1;
813 }
814 else {
815 p = bytes + n - 1;
816 pincr = -1;
817 }
818
Tim Peters898cf852001-06-13 20:50:08 +0000819 /* Copy over all the Python digits.
820 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000821 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000822 normalized. */
823 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000824 j = 0;
825 accum = 0;
826 accumbits = 0;
827 carry = do_twos_comp ? 1 : 0;
828 for (i = 0; i < ndigits; ++i) {
Mark Dickinson17e55872009-01-24 15:56:57 +0000829 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000830 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000831 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
832 carry = thisdigit >> PyLong_SHIFT;
833 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000834 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000835 /* Because we're going LSB to MSB, thisdigit is more
836 significant than what's already in accum, so needs to be
837 prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000838 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000839
Tim Petersede05092001-06-14 08:53:38 +0000840 /* The most-significant digit may be (probably is) at least
841 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000842 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000843 /* Count # of sign bits -- they needn't be stored,
844 * although for signed conversion we need later to
Mark Dickinson17e55872009-01-24 15:56:57 +0000845 * make sure at least one sign bit gets stored. */
846 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
847 thisdigit;
848 while (s != 0) {
849 s >>= 1;
850 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000851 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000852 }
Mark Dickinson17e55872009-01-24 15:56:57 +0000853 else
854 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000855
Tim Peters2a9b3672001-06-11 21:23:58 +0000856 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000857 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000858 if (j >= n)
859 goto Overflow;
860 ++j;
861 *p = (unsigned char)(accum & 0xff);
862 p += pincr;
863 accumbits -= 8;
864 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000865 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000866 }
867
868 /* Store the straggler (if any). */
869 assert(accumbits < 8);
870 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000871 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000872 if (j >= n)
873 goto Overflow;
874 ++j;
875 if (do_twos_comp) {
876 /* Fill leading bits of the byte with sign bits
877 (appropriately pretending that the long had an
878 infinite supply of sign bits). */
879 accum |= (~(twodigits)0) << accumbits;
880 }
881 *p = (unsigned char)(accum & 0xff);
882 p += pincr;
883 }
Tim Peters05607ad2001-06-13 21:01:27 +0000884 else if (j == n && n > 0 && is_signed) {
885 /* The main loop filled the byte array exactly, so the code
886 just above didn't get to ensure there's a sign bit, and the
887 loop below wouldn't add one either. Make sure a sign bit
888 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000889 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000890 int sign_bit_set = msb >= 0x80;
891 assert(accumbits == 0);
892 if (sign_bit_set == do_twos_comp)
893 return 0;
894 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000895 goto Overflow;
896 }
Tim Peters05607ad2001-06-13 21:01:27 +0000897
898 /* Fill remaining bytes with copies of the sign bit. */
899 {
900 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
901 for ( ; j < n; ++j, p += pincr)
902 *p = signbyte;
903 }
904
Tim Peters2a9b3672001-06-11 21:23:58 +0000905 return 0;
906
907Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000908 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000909 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000910
Tim Peters2a9b3672001-06-11 21:23:58 +0000911}
912
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000913double
914_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
915{
916/* NBITS_WANTED should be > the number of bits in a double's precision,
917 but small enough so that 2**NBITS_WANTED is within the normal double
918 range. nbitsneeded is set to 1 less than that because the most-significant
919 Python digit contains at least 1 significant bit, but we don't want to
920 bother counting them (catering to the worst case cheaply).
921
922 57 is one more than VAX-D double precision; I (Tim) don't know of a double
923 format with more precision than that; it's 1 larger so that we add in at
924 least one round bit to stand in for the ignored least-significant bits.
925*/
926#define NBITS_WANTED 57
927 PyLongObject *v;
928 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000929 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000930 Py_ssize_t i;
931 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000932 int nbitsneeded;
933
934 if (vv == NULL || !PyLong_Check(vv)) {
935 PyErr_BadInternalCall();
936 return -1;
937 }
938 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000939 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000940 sign = 1;
941 if (i < 0) {
942 sign = -1;
943 i = -(i);
944 }
945 else if (i == 0) {
946 *exponent = 0;
947 return 0.0;
948 }
949 --i;
950 x = (double)v->ob_digit[i];
951 nbitsneeded = NBITS_WANTED - 1;
952 /* Invariant: i Python digits remain unaccounted for. */
953 while (i > 0 && nbitsneeded > 0) {
954 --i;
955 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000956 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000957 }
958 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000959 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000960 *exponent = i;
961 assert(x > 0.0);
962 return x * sign;
963#undef NBITS_WANTED
964}
965
Mark Dickinsonc6300392009-04-20 21:38:00 +0000966/* Get a C double from a long int object. Rounds to the nearest double,
967 using the round-half-to-even rule in the case of a tie. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000968
969double
Tim Peters9f688bf2000-07-07 15:53:28 +0000970PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000971{
Mark Dickinsonc6300392009-04-20 21:38:00 +0000972 PyLongObject *v = (PyLongObject *)vv;
973 Py_ssize_t rnd_digit, rnd_bit, m, n;
974 digit lsb, *d;
975 int round_up = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000976 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000977
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000978 if (vv == NULL || !PyLong_Check(vv)) {
979 PyErr_BadInternalCall();
Tim Peters9fffa3e2001-09-04 05:14:19 +0000980 return -1.0;
Mark Dickinsonc6300392009-04-20 21:38:00 +0000981 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000982
Mark Dickinsonc6300392009-04-20 21:38:00 +0000983 /* Notes on the method: for simplicity, assume v is positive and >=
984 2**DBL_MANT_DIG. (For negative v we just ignore the sign until the
985 end; for small v no rounding is necessary.) Write n for the number
986 of bits in v, so that 2**(n-1) <= v < 2**n, and n > DBL_MANT_DIG.
987
988 Some terminology: the *rounding bit* of v is the 1st bit of v that
989 will be rounded away (bit n - DBL_MANT_DIG - 1); the *parity bit*
990 is the bit immediately above. The round-half-to-even rule says
991 that we round up if the rounding bit is set, unless v is exactly
992 halfway between two floats and the parity bit is zero.
993
994 Write d[0] ... d[m] for the digits of v, least to most significant.
995 Let rnd_bit be the index of the rounding bit, and rnd_digit the
996 index of the PyLong digit containing the rounding bit. Then the
997 bits of the digit d[rnd_digit] look something like:
998
999 rounding bit
1000 |
1001 v
1002 msb -> sssssrttttttttt <- lsb
1003 ^
1004 |
1005 parity bit
1006
1007 where 's' represents a 'significant bit' that will be included in
1008 the mantissa of the result, 'r' is the rounding bit, and 't'
1009 represents a 'trailing bit' following the rounding bit. Note that
1010 if the rounding bit is at the top of d[rnd_digit] then the parity
1011 bit will be the lsb of d[rnd_digit+1]. If we set
1012
1013 lsb = 1 << (rnd_bit % PyLong_SHIFT)
1014
1015 then d[rnd_digit] & (PyLong_BASE - 2*lsb) selects just the
1016 significant bits of d[rnd_digit], d[rnd_digit] & (lsb-1) gets the
1017 trailing bits, and d[rnd_digit] & lsb gives the rounding bit.
1018
1019 We initialize the double x to the integer given by digits
1020 d[rnd_digit:m-1], but with the rounding bit and trailing bits of
1021 d[rnd_digit] masked out. So the value of x comes from the top
1022 DBL_MANT_DIG bits of v, multiplied by 2*lsb. Note that in the loop
1023 that produces x, all floating-point operations are exact (assuming
1024 that FLT_RADIX==2). Now if we're rounding down, the value we want
1025 to return is simply
1026
1027 x * 2**(PyLong_SHIFT * rnd_digit).
1028
1029 and if we're rounding up, it's
1030
1031 (x + 2*lsb) * 2**(PyLong_SHIFT * rnd_digit).
1032
1033 Under the round-half-to-even rule, we round up if, and only
1034 if, the rounding bit is set *and* at least one of the
1035 following three conditions is satisfied:
1036
1037 (1) the parity bit is set, or
1038 (2) at least one of the trailing bits of d[rnd_digit] is set, or
1039 (3) at least one of the digits d[i], 0 <= i < rnd_digit
1040 is nonzero.
1041
1042 Finally, we have to worry about overflow. If v >= 2**DBL_MAX_EXP,
1043 or equivalently n > DBL_MAX_EXP, then overflow occurs. If v <
1044 2**DBL_MAX_EXP then we're usually safe, but there's a corner case
1045 to consider: if v is very close to 2**DBL_MAX_EXP then it's
1046 possible that v is rounded up to exactly 2**DBL_MAX_EXP, and then
1047 again overflow occurs.
1048 */
1049
1050 if (Py_SIZE(v) == 0)
1051 return 0.0;
1052 m = ABS(Py_SIZE(v)) - 1;
1053 d = v->ob_digit;
1054 assert(d[m]); /* v should be normalized */
1055
1056 /* fast path for case where 0 < abs(v) < 2**DBL_MANT_DIG */
1057 if (m < DBL_MANT_DIG / PyLong_SHIFT ||
1058 (m == DBL_MANT_DIG / PyLong_SHIFT &&
1059 d[m] < (digit)1 << DBL_MANT_DIG%PyLong_SHIFT)) {
1060 x = d[m];
1061 while (--m >= 0)
1062 x = x*PyLong_BASE + d[m];
1063 return Py_SIZE(v) < 0 ? -x : x;
1064 }
1065
1066 /* if m is huge then overflow immediately; otherwise, compute the
1067 number of bits n in v. The condition below implies n (= #bits) >=
1068 m * PyLong_SHIFT + 1 > DBL_MAX_EXP, hence v >= 2**DBL_MAX_EXP. */
1069 if (m > (DBL_MAX_EXP-1)/PyLong_SHIFT)
1070 goto overflow;
1071 n = m * PyLong_SHIFT + bits_in_digit(d[m]);
1072 if (n > DBL_MAX_EXP)
1073 goto overflow;
1074
1075 /* find location of rounding bit */
1076 assert(n > DBL_MANT_DIG); /* dealt with |v| < 2**DBL_MANT_DIG above */
1077 rnd_bit = n - DBL_MANT_DIG - 1;
1078 rnd_digit = rnd_bit/PyLong_SHIFT;
1079 lsb = (digit)1 << (rnd_bit%PyLong_SHIFT);
1080
1081 /* Get top DBL_MANT_DIG bits of v. Assumes PyLong_SHIFT <
1082 DBL_MANT_DIG, so we'll need bits from at least 2 digits of v. */
1083 x = d[m];
1084 assert(m > rnd_digit);
1085 while (--m > rnd_digit)
1086 x = x*PyLong_BASE + d[m];
1087 x = x*PyLong_BASE + (d[m] & (PyLong_BASE-2*lsb));
1088
1089 /* decide whether to round up, using round-half-to-even */
1090 assert(m == rnd_digit);
1091 if (d[m] & lsb) { /* if (rounding bit is set) */
1092 digit parity_bit;
1093 if (lsb == PyLong_BASE/2)
1094 parity_bit = d[m+1] & 1;
1095 else
1096 parity_bit = d[m] & 2*lsb;
1097 if (parity_bit)
1098 round_up = 1;
1099 else if (d[m] & (lsb-1))
1100 round_up = 1;
1101 else {
1102 while (--m >= 0) {
1103 if (d[m]) {
1104 round_up = 1;
1105 break;
1106 }
1107 }
1108 }
1109 }
1110
1111 /* and round up if necessary */
1112 if (round_up) {
1113 x += 2*lsb;
1114 if (n == DBL_MAX_EXP &&
1115 x == ldexp((double)(2*lsb), DBL_MANT_DIG)) {
1116 /* overflow corner case */
1117 goto overflow;
1118 }
1119 }
1120
1121 /* shift, adjust for sign, and return */
1122 x = ldexp(x, rnd_digit*PyLong_SHIFT);
1123 return Py_SIZE(v) < 0 ? -x : x;
1124
1125 overflow:
Tim Peters9fffa3e2001-09-04 05:14:19 +00001126 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +00001127 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +00001128 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001129}
1130
Guido van Rossum78694d91998-09-18 14:14:13 +00001131/* Create a new long (or int) object from a C pointer */
1132
1133PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001134PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001135{
Tim Peters70128a12001-06-16 08:48:40 +00001136#ifndef HAVE_LONG_LONG
1137# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1138#endif
1139#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001140# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001141#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +00001142 /* special-case null pointer */
1143 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +00001144 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001145 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +00001146
Guido van Rossum78694d91998-09-18 14:14:13 +00001147}
1148
1149/* Get a C pointer from a long object (or an int object in some cases) */
1150
1151void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001152PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001153{
1154 /* This function will allow int or long objects. If vv is neither,
1155 then the PyLong_AsLong*() functions will raise the exception:
1156 PyExc_SystemError, "bad argument to internal function"
1157 */
Tim Peters70128a12001-06-16 08:48:40 +00001158#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001159 long x;
1160
Guido van Rossumddefaf32007-01-14 03:31:43 +00001161 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001162 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001163 else
1164 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001165#else
Tim Peters70128a12001-06-16 08:48:40 +00001166
1167#ifndef HAVE_LONG_LONG
1168# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1169#endif
1170#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001171# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001172#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001173 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001174
Guido van Rossumddefaf32007-01-14 03:31:43 +00001175 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001176 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001177 else
1178 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001179
1180#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001181
1182 if (x == -1 && PyErr_Occurred())
1183 return NULL;
1184 return (void *)x;
1185}
1186
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001187#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001188
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001189/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001190 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001191 */
1192
Tim Peterscf37dfc2001-06-14 18:42:50 +00001193#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001194
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001195/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001196
1197PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001198PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001199{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001200 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +00001201 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001202 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1203 int ndigits = 0;
1204 int negative = 0;
1205
Guido van Rossumddefaf32007-01-14 03:31:43 +00001206 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001207 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +00001208 /* avoid signed overflow on negation; see comments
1209 in PyLong_FromLong above. */
1210 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001211 negative = 1;
1212 }
Christian Heimesdae2a892008-04-19 00:55:37 +00001213 else {
1214 abs_ival = (unsigned PY_LONG_LONG)ival;
1215 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001216
1217 /* Count the number of Python digits.
1218 We used to pick 5 ("big enough for anything"), but that's a
1219 waste of time and space given that 5*15 = 75 bits are rarely
1220 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001221 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001222 while (t) {
1223 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001224 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001225 }
1226 v = _PyLong_New(ndigits);
1227 if (v != NULL) {
1228 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001229 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001230 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001231 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001232 *p++ = (digit)(t & PyLong_MASK);
1233 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001234 }
1235 }
1236 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001237}
1238
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001239/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001240
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001241PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001242PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001243{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001244 PyLongObject *v;
1245 unsigned PY_LONG_LONG t;
1246 int ndigits = 0;
1247
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001248 if (ival < PyLong_BASE)
Mark Dickinson50b2b6e2008-12-05 17:14:29 +00001249 return PyLong_FromLong((long)ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001250 /* Count the number of Python digits. */
1251 t = (unsigned PY_LONG_LONG)ival;
1252 while (t) {
1253 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001254 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001255 }
1256 v = _PyLong_New(ndigits);
1257 if (v != NULL) {
1258 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001259 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001260 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001261 *p++ = (digit)(ival & PyLong_MASK);
1262 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001263 }
1264 }
1265 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001266}
1267
Martin v. Löwis18e16552006-02-15 17:27:45 +00001268/* Create a new long int object from a C Py_ssize_t. */
1269
1270PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001271PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001272{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001273 PyLongObject *v;
1274 size_t abs_ival;
1275 size_t t; /* unsigned so >> doesn't propagate sign bit */
1276 int ndigits = 0;
1277 int negative = 0;
1278
1279 CHECK_SMALL_INT(ival);
1280 if (ival < 0) {
1281 /* avoid signed overflow when ival = SIZE_T_MIN */
1282 abs_ival = (size_t)(-1-ival)+1;
1283 negative = 1;
1284 }
1285 else {
1286 abs_ival = (size_t)ival;
1287 }
1288
1289 /* Count the number of Python digits. */
1290 t = abs_ival;
1291 while (t) {
1292 ++ndigits;
1293 t >>= PyLong_SHIFT;
1294 }
1295 v = _PyLong_New(ndigits);
1296 if (v != NULL) {
1297 digit *p = v->ob_digit;
1298 Py_SIZE(v) = negative ? -ndigits : ndigits;
1299 t = abs_ival;
1300 while (t) {
1301 *p++ = (digit)(t & PyLong_MASK);
1302 t >>= PyLong_SHIFT;
1303 }
1304 }
1305 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001306}
1307
1308/* Create a new long int object from a C size_t. */
1309
1310PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001311PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001312{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001313 PyLongObject *v;
1314 size_t t;
1315 int ndigits = 0;
1316
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001317 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001318 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001319 /* Count the number of Python digits. */
1320 t = ival;
1321 while (t) {
1322 ++ndigits;
1323 t >>= PyLong_SHIFT;
1324 }
1325 v = _PyLong_New(ndigits);
1326 if (v != NULL) {
1327 digit *p = v->ob_digit;
1328 Py_SIZE(v) = ndigits;
1329 while (ival) {
1330 *p++ = (digit)(ival & PyLong_MASK);
1331 ival >>= PyLong_SHIFT;
1332 }
1333 }
1334 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001335}
1336
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001337/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001338 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001339
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001340PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001341PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001342{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001343 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001344 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001345 int one = 1;
1346 int res;
1347
Tim Petersd38b1c72001-09-30 05:09:37 +00001348 if (vv == NULL) {
1349 PyErr_BadInternalCall();
1350 return -1;
1351 }
1352 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001353 PyNumberMethods *nb;
1354 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001355 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1356 nb->nb_int == NULL) {
1357 PyErr_SetString(PyExc_TypeError, "an integer is required");
1358 return -1;
1359 }
1360 io = (*nb->nb_int) (vv);
1361 if (io == NULL)
1362 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001363 if (PyLong_Check(io)) {
1364 bytes = PyLong_AsLongLong(io);
1365 Py_DECREF(io);
1366 return bytes;
1367 }
1368 Py_DECREF(io);
1369 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001370 return -1;
1371 }
1372
Guido van Rossumddefaf32007-01-14 03:31:43 +00001373 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001374 switch(Py_SIZE(v)) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00001375 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00001376 case 0: return 0;
1377 case 1: return v->ob_digit[0];
1378 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001379 res = _PyLong_AsByteArray(
1380 (PyLongObject *)vv, (unsigned char *)&bytes,
1381 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001382
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001383 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001384 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001385 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001386 else
1387 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001388}
1389
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001390/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001391 Return -1 and set an error if overflow occurs. */
1392
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001393unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001394PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001395{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001396 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001397 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001398 int one = 1;
1399 int res;
1400
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001401 if (vv == NULL || !PyLong_Check(vv)) {
1402 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001403 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001404 }
1405
Guido van Rossumddefaf32007-01-14 03:31:43 +00001406 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001407 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001408 case 0: return 0;
1409 case 1: return v->ob_digit[0];
1410 }
1411
Tim Petersd1a7da62001-06-13 00:35:57 +00001412 res = _PyLong_AsByteArray(
1413 (PyLongObject *)vv, (unsigned char *)&bytes,
1414 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001415
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001416 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001417 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001418 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001419 else
1420 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001421}
Tim Petersd1a7da62001-06-13 00:35:57 +00001422
Thomas Hellera4ea6032003-04-17 18:55:45 +00001423/* Get a C unsigned long int from a long int object, ignoring the high bits.
1424 Returns -1 and sets an error condition if an error occurs. */
1425
Guido van Rossumddefaf32007-01-14 03:31:43 +00001426static unsigned PY_LONG_LONG
1427_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001428{
1429 register PyLongObject *v;
1430 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001431 Py_ssize_t i;
1432 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001433
1434 if (vv == NULL || !PyLong_Check(vv)) {
1435 PyErr_BadInternalCall();
1436 return (unsigned long) -1;
1437 }
1438 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001439 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001440 case 0: return 0;
1441 case 1: return v->ob_digit[0];
1442 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001443 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001444 sign = 1;
1445 x = 0;
1446 if (i < 0) {
1447 sign = -1;
1448 i = -i;
1449 }
1450 while (--i >= 0) {
Mark Dickinson24f57852009-09-28 17:54:52 +00001451 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001452 }
1453 return x * sign;
1454}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001455
1456unsigned PY_LONG_LONG
1457PyLong_AsUnsignedLongLongMask(register PyObject *op)
1458{
1459 PyNumberMethods *nb;
1460 PyLongObject *lo;
1461 unsigned PY_LONG_LONG val;
1462
1463 if (op && PyLong_Check(op))
1464 return _PyLong_AsUnsignedLongLongMask(op);
1465
1466 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1467 nb->nb_int == NULL) {
1468 PyErr_SetString(PyExc_TypeError, "an integer is required");
1469 return (unsigned PY_LONG_LONG)-1;
1470 }
1471
1472 lo = (PyLongObject*) (*nb->nb_int) (op);
1473 if (lo == NULL)
1474 return (unsigned PY_LONG_LONG)-1;
1475 if (PyLong_Check(lo)) {
1476 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1477 Py_DECREF(lo);
1478 if (PyErr_Occurred())
1479 return (unsigned PY_LONG_LONG)-1;
1480 return val;
1481 }
1482 else
1483 {
1484 Py_DECREF(lo);
1485 PyErr_SetString(PyExc_TypeError,
1486 "nb_int should return int object");
1487 return (unsigned PY_LONG_LONG)-1;
1488 }
1489}
Tim Petersd1a7da62001-06-13 00:35:57 +00001490#undef IS_LITTLE_ENDIAN
1491
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001492#endif /* HAVE_LONG_LONG */
1493
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001494#define CHECK_BINOP(v,w) \
1495 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001496 Py_INCREF(Py_NotImplemented); \
1497 return Py_NotImplemented; \
1498 }
1499
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001500/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1501 2**k if d is nonzero, else 0. */
1502
1503static const unsigned char BitLengthTable[32] = {
1504 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1505 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1506};
1507
1508static int
1509bits_in_digit(digit d)
1510{
1511 int d_bits = 0;
1512 while (d >= 32) {
1513 d_bits += 6;
1514 d >>= 6;
1515 }
1516 d_bits += (int)BitLengthTable[d];
1517 return d_bits;
1518}
1519
Tim Peters877a2122002-08-12 05:09:36 +00001520/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1521 * is modified in place, by adding y to it. Carries are propagated as far as
1522 * x[m-1], and the remaining carry (0 or 1) is returned.
1523 */
1524static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001525v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001526{
Mark Dickinson17e55872009-01-24 15:56:57 +00001527 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001528 digit carry = 0;
1529
1530 assert(m >= n);
1531 for (i = 0; i < n; ++i) {
1532 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001533 x[i] = carry & PyLong_MASK;
1534 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001535 assert((carry & 1) == carry);
1536 }
1537 for (; carry && i < m; ++i) {
1538 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001539 x[i] = carry & PyLong_MASK;
1540 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001541 assert((carry & 1) == carry);
1542 }
1543 return carry;
1544}
1545
1546/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1547 * is modified in place, by subtracting y from it. Borrows are propagated as
1548 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1549 */
1550static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001551v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001552{
Mark Dickinson17e55872009-01-24 15:56:57 +00001553 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001554 digit borrow = 0;
1555
1556 assert(m >= n);
1557 for (i = 0; i < n; ++i) {
1558 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001559 x[i] = borrow & PyLong_MASK;
1560 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001561 borrow &= 1; /* keep only 1 sign bit */
1562 }
1563 for (; borrow && i < m; ++i) {
1564 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001565 x[i] = borrow & PyLong_MASK;
1566 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001567 borrow &= 1;
1568 }
1569 return borrow;
1570}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001571
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001572/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1573 * result in z[0:m], and return the d bits shifted out of the top.
1574 */
1575static digit
1576v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001577{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001578 Py_ssize_t i;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001579 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001580
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001581 assert(0 <= d && d < PyLong_SHIFT);
1582 for (i=0; i < m; i++) {
1583 twodigits acc = (twodigits)a[i] << d | carry;
1584 z[i] = (digit)acc & PyLong_MASK;
1585 carry = (digit)(acc >> PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001586 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001587 return carry;
1588}
1589
1590/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1591 * result in z[0:m], and return the d bits shifted out of the bottom.
1592 */
1593static digit
1594v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1595{
1596 Py_ssize_t i;
1597 digit carry = 0;
1598 digit mask = ((digit)1 << d) - 1U;
1599
1600 assert(0 <= d && d < PyLong_SHIFT);
1601 for (i=m; i-- > 0;) {
1602 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1603 carry = (digit)acc & mask;
1604 z[i] = (digit)(acc >> d);
1605 }
1606 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001607}
1608
Tim Peters212e6142001-07-14 12:23:19 +00001609/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1610 in pout, and returning the remainder. pin and pout point at the LSD.
1611 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001612 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001613 immutable. */
1614
1615static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001616inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001617{
1618 twodigits rem = 0;
1619
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001620 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001621 pin += size;
1622 pout += size;
1623 while (--size >= 0) {
1624 digit hi;
Mark Dickinson24f57852009-09-28 17:54:52 +00001625 rem = (rem << PyLong_SHIFT) | *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001626 *--pout = hi = (digit)(rem / n);
Mark Dickinson17e55872009-01-24 15:56:57 +00001627 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001628 }
1629 return (digit)rem;
1630}
1631
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001632/* Divide a long integer by a digit, returning both the quotient
1633 (as function result) and the remainder (through *prem).
1634 The sign of a is ignored; n should not be zero. */
1635
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001636static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001637divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001638{
Christian Heimes90aa7642007-12-19 02:45:37 +00001639 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001640 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001641
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001642 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001643 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001644 if (z == NULL)
1645 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001646 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001647 return long_normalize(z);
1648}
1649
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001650/* Convert a long integer to a base 10 string. Returns a new non-shared
1651 string. (Return value is non-shared so that callers can modify the
1652 returned value if necessary.) */
1653
1654static PyObject *
1655long_to_decimal_string(PyObject *aa)
1656{
1657 PyLongObject *scratch, *a;
1658 PyObject *str;
1659 Py_ssize_t size, strlen, size_a, i, j;
1660 digit *pout, *pin, rem, tenpow;
1661 Py_UNICODE *p;
1662 int negative;
1663
1664 a = (PyLongObject *)aa;
1665 if (a == NULL || !PyLong_Check(a)) {
1666 PyErr_BadInternalCall();
1667 return NULL;
1668 }
1669 size_a = ABS(Py_SIZE(a));
1670 negative = Py_SIZE(a) < 0;
1671
1672 /* quick and dirty upper bound for the number of digits
1673 required to express a in base _PyLong_DECIMAL_BASE:
1674
1675 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1676
1677 But log2(a) < size_a * PyLong_SHIFT, and
1678 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1679 > 3 * _PyLong_DECIMAL_SHIFT
1680 */
1681 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1682 PyErr_SetString(PyExc_OverflowError,
1683 "long is too large to format");
1684 return NULL;
1685 }
1686 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1687 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1688 scratch = _PyLong_New(size);
1689 if (scratch == NULL)
1690 return NULL;
1691
1692 /* convert array of base _PyLong_BASE digits in pin to an array of
1693 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1694 Volume 2 (3rd edn), section 4.4, Method 1b). */
1695 pin = a->ob_digit;
1696 pout = scratch->ob_digit;
1697 size = 0;
1698 for (i = size_a; --i >= 0; ) {
1699 digit hi = pin[i];
1700 for (j = 0; j < size; j++) {
1701 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
Mark Dickinson741984d2009-09-21 16:18:27 +00001702 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1703 pout[j] = (digit)(z - (twodigits)hi *
1704 _PyLong_DECIMAL_BASE);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001705 }
1706 while (hi) {
1707 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1708 hi /= _PyLong_DECIMAL_BASE;
1709 }
1710 /* check for keyboard interrupt */
1711 SIGCHECK({
1712 Py_DECREF(scratch);
1713 return NULL;
1714 })
1715 }
1716 /* pout should have at least one digit, so that the case when a = 0
1717 works correctly */
1718 if (size == 0)
1719 pout[size++] = 0;
1720
1721 /* calculate exact length of output string, and allocate */
1722 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1723 tenpow = 10;
1724 rem = pout[size-1];
1725 while (rem >= tenpow) {
1726 tenpow *= 10;
1727 strlen++;
1728 }
1729 str = PyUnicode_FromUnicode(NULL, strlen);
1730 if (str == NULL) {
1731 Py_DECREF(scratch);
1732 return NULL;
1733 }
1734
1735 /* fill the string right-to-left */
1736 p = PyUnicode_AS_UNICODE(str) + strlen;
1737 *p = '\0';
1738 /* pout[0] through pout[size-2] contribute exactly
1739 _PyLong_DECIMAL_SHIFT digits each */
1740 for (i=0; i < size - 1; i++) {
1741 rem = pout[i];
1742 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1743 *--p = '0' + rem % 10;
1744 rem /= 10;
1745 }
1746 }
1747 /* pout[size-1]: always produce at least one decimal digit */
1748 rem = pout[i];
1749 do {
1750 *--p = '0' + rem % 10;
1751 rem /= 10;
1752 } while (rem != 0);
1753
1754 /* and sign */
1755 if (negative)
1756 *--p = '-';
1757
1758 /* check we've counted correctly */
1759 assert(p == PyUnicode_AS_UNICODE(str));
1760 Py_DECREF(scratch);
1761 return (PyObject *)str;
1762}
1763
Mark Dickinsoncd068122009-09-18 14:53:08 +00001764/* Convert a long int object to a string, using a given conversion base,
1765 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001766 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001767
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001768PyObject *
1769_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001770{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001771 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001772 PyObject *str;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001773 Py_ssize_t i, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001774 Py_ssize_t size_a;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001775 Py_UNICODE *p, sign = '\0';
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001776 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001777
Mark Dickinsoncd068122009-09-18 14:53:08 +00001778 assert(base == 2 || base == 8 || base == 10 || base == 16);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001779 if (base == 10)
1780 return long_to_decimal_string((PyObject *)a);
1781
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001782 if (a == NULL || !PyLong_Check(a)) {
1783 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001784 return NULL;
1785 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001786 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001787
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001788 /* Compute a rough upper bound for the length of the string */
Mark Dickinsoncd068122009-09-18 14:53:08 +00001789 switch (base) {
1790 case 16:
1791 bits = 4;
1792 break;
1793 case 8:
1794 bits = 3;
1795 break;
1796 case 2:
1797 bits = 1;
1798 break;
1799 default:
1800 assert(0); /* shouldn't ever get here */
1801 bits = 0; /* to silence gcc warning */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001802 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001803 /* compute length of output string: allow 2 characters for prefix and
1804 1 for possible '-' sign. */
1805 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001806 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001807 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001808 return NULL;
1809 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001810 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1811 is safe from overflow */
1812 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001813 assert(sz >= 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001814 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001815 if (str == NULL)
1816 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001817 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001818 *p = '\0';
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001819 if (Py_SIZE(a) < 0)
1820 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001821
Christian Heimes90aa7642007-12-19 02:45:37 +00001822 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001823 *--p = '0';
1824 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001825 else {
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001826 /* JRH: special case for power-of-2 bases */
1827 twodigits accum = 0;
1828 int accumbits = 0; /* # of bits in accum */
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001829 for (i = 0; i < size_a; ++i) {
1830 accum |= (twodigits)a->ob_digit[i] << accumbits;
1831 accumbits += PyLong_SHIFT;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001832 assert(accumbits >= bits);
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001833 do {
Mark Dickinson1f7e18c2009-09-24 18:31:17 +00001834 Py_UNICODE cdigit;
1835 cdigit = (Py_UNICODE)(accum & (base - 1));
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001836 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1837 assert(p > PyUnicode_AS_UNICODE(str));
1838 *--p = cdigit;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001839 accumbits -= bits;
1840 accum >>= bits;
1841 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001842 }
1843 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001844
Mark Dickinsoncd068122009-09-18 14:53:08 +00001845 if (base == 16)
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001846 *--p = 'x';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001847 else if (base == 8)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001848 *--p = 'o';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001849 else /* (base == 2) */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001850 *--p = 'b';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001851 *--p = '0';
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001852 if (sign)
1853 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001854 if (p != PyUnicode_AS_UNICODE(str)) {
1855 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001856 assert(p > q);
1857 do {
1858 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001859 q--;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001860 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1861 PyUnicode_AS_UNICODE(str)))) {
Walter Dörwald1ab83302007-05-18 17:15:44 +00001862 Py_DECREF(str);
1863 return NULL;
1864 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001865 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001866 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001867}
1868
Thomas Wouters477c8d52006-05-27 19:21:47 +00001869/* Table of digit values for 8-bit string -> integer conversion.
1870 * '0' maps to 0, ..., '9' maps to 9.
1871 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1872 * All other indices map to 37.
1873 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001874 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001875 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001876unsigned char _PyLong_DigitValue[256] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001877 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1878 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1879 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1880 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1881 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1882 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1883 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1884 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1885 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1886 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1887 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1888 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1889 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1890 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1891 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1892 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1893};
1894
1895/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001896 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1897 * non-digit (which may be *str!). A normalized long is returned.
1898 * The point to this routine is that it takes time linear in the number of
1899 * string characters.
1900 */
1901static PyLongObject *
1902long_from_binary_base(char **str, int base)
1903{
1904 char *p = *str;
1905 char *start = p;
1906 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001907 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001908 PyLongObject *z;
1909 twodigits accum;
1910 int bits_in_accum;
1911 digit *pdigit;
1912
1913 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1914 n = base;
1915 for (bits_per_char = -1; n; ++bits_per_char)
1916 n >>= 1;
1917 /* n <- total # of bits needed, while setting p to end-of-string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001918 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001919 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001920 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001921 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1922 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001923 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001924 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001925 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001926 return NULL;
1927 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001928 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001929 z = _PyLong_New(n);
1930 if (z == NULL)
1931 return NULL;
1932 /* Read string from right, and fill in long from left; i.e.,
1933 * from least to most significant in both.
1934 */
1935 accum = 0;
1936 bits_in_accum = 0;
1937 pdigit = z->ob_digit;
1938 while (--p >= start) {
Raymond Hettinger35631532009-01-09 03:58:09 +00001939 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001940 assert(k >= 0 && k < base);
Mark Dickinson17e55872009-01-24 15:56:57 +00001941 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001942 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001943 if (bits_in_accum >= PyLong_SHIFT) {
1944 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinson17e55872009-01-24 15:56:57 +00001945 assert(pdigit - z->ob_digit <= n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001946 accum >>= PyLong_SHIFT;
1947 bits_in_accum -= PyLong_SHIFT;
1948 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001949 }
1950 }
1951 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001952 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001953 *pdigit++ = (digit)accum;
Mark Dickinson17e55872009-01-24 15:56:57 +00001954 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001955 }
1956 while (pdigit - z->ob_digit < n)
1957 *pdigit++ = 0;
1958 return long_normalize(z);
1959}
1960
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001961PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001962PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001963{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001964 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001965 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001966 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001967 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001968 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001969
Guido van Rossum472c04f1996-12-05 21:57:21 +00001970 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001971 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001972 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001973 return NULL;
1974 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001975 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001976 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001977 if (*str == '+')
1978 ++str;
1979 else if (*str == '-') {
1980 ++str;
1981 sign = -1;
1982 }
1983 if (base == 0) {
1984 if (str[0] != '0')
1985 base = 10;
1986 else if (str[1] == 'x' || str[1] == 'X')
1987 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001988 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001989 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001990 else if (str[1] == 'b' || str[1] == 'B')
1991 base = 2;
1992 else {
1993 /* "old" (C-style) octal literal, now invalid.
1994 it might still be zero though */
1995 error_if_nonzero = 1;
1996 base = 10;
1997 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001998 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001999 if (str[0] == '0' &&
2000 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2001 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2002 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002003 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002004
Guido van Rossume6762971998-06-22 03:54:46 +00002005 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00002006 if ((base & (base - 1)) == 0)
2007 z = long_from_binary_base(&str, base);
2008 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002009/***
2010Binary bases can be converted in time linear in the number of digits, because
2011Python's representation base is binary. Other bases (including decimal!) use
2012the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002013
Thomas Wouters477c8d52006-05-27 19:21:47 +00002014First some math: the largest integer that can be expressed in N base-B digits
2015is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2016case number of Python digits needed to hold it is the smallest integer n s.t.
2017
2018 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2019 BASE**n >= B**N [taking logs to base BASE]
2020 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2021
2022The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2023this quickly. A Python long with that much space is reserved near the start,
2024and the result is computed into it.
2025
2026The input string is actually treated as being in base base**i (i.e., i digits
2027are processed at a time), where two more static arrays hold:
2028
2029 convwidth_base[base] = the largest integer i such that base**i <= BASE
2030 convmultmax_base[base] = base ** convwidth_base[base]
2031
2032The first of these is the largest i such that i consecutive input digits
2033must fit in a single Python digit. The second is effectively the input
2034base we're really using.
2035
2036Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2037convmultmax_base[base], the result is "simply"
2038
2039 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2040
2041where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002042
2043Error analysis: as above, the number of Python digits `n` needed is worst-
2044case
2045
2046 n >= N * log(B)/log(BASE)
2047
2048where `N` is the number of input digits in base `B`. This is computed via
2049
2050 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2051
2052below. Two numeric concerns are how much space this can waste, and whether
2053the computed result can be too small. To be concrete, assume BASE = 2**15,
2054which is the default (and it's unlikely anyone changes that).
2055
2056Waste isn't a problem: provided the first input digit isn't 0, the difference
2057between the worst-case input with N digits and the smallest input with N
2058digits is about a factor of B, but B is small compared to BASE so at most
2059one allocated Python digit can remain unused on that count. If
2060N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2061and adding 1 returns a result 1 larger than necessary. However, that can't
2062happen: whenever B is a power of 2, long_from_binary_base() is called
2063instead, and it's impossible for B**i to be an integer power of 2**15 when
2064B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2065an exact integer when B is not a power of 2, since B**i has a prime factor
2066other than 2 in that case, but (2**15)**j's only prime factor is 2).
2067
2068The computed result can be too small if the true value of N*log(B)/log(BASE)
2069is a little bit larger than an exact integer, but due to roundoff errors (in
2070computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2071yields a numeric result a little less than that integer. Unfortunately, "how
2072close can a transcendental function get to an integer over some range?"
2073questions are generally theoretically intractable. Computer analysis via
2074continued fractions is practical: expand log(B)/log(BASE) via continued
2075fractions, giving a sequence i/j of "the best" rational approximations. Then
2076j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2077we can get very close to being in trouble, but very rarely. For example,
207876573 is a denominator in one of the continued-fraction approximations to
2079log(10)/log(2**15), and indeed:
2080
2081 >>> log(10)/log(2**15)*76573
2082 16958.000000654003
2083
2084is very close to an integer. If we were working with IEEE single-precision,
2085rounding errors could kill us. Finding worst cases in IEEE double-precision
2086requires better-than-double-precision log() functions, and Tim didn't bother.
2087Instead the code checks to see whether the allocated space is enough as each
2088new Python digit is added, and copies the whole thing to a larger long if not.
2089This should happen extremely rarely, and in fact I don't have a test case
2090that triggers it(!). Instead the code was tested by artificially allocating
2091just 1 digit at the start, so that the copying code was exercised for every
2092digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002093***/
2094 register twodigits c; /* current input character */
2095 Py_ssize_t size_z;
2096 int i;
2097 int convwidth;
2098 twodigits convmultmax, convmult;
2099 digit *pz, *pzstop;
2100 char* scan;
2101
2102 static double log_base_BASE[37] = {0.0e0,};
2103 static int convwidth_base[37] = {0,};
2104 static twodigits convmultmax_base[37] = {0,};
2105
2106 if (log_base_BASE[base] == 0.0) {
2107 twodigits convmax = base;
2108 int i = 1;
2109
2110 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002111 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002112 for (;;) {
2113 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002114 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002115 break;
2116 convmax = next;
2117 ++i;
2118 }
2119 convmultmax_base[base] = convmax;
2120 assert(i > 0);
2121 convwidth_base[base] = i;
2122 }
2123
2124 /* Find length of the string of numeric characters. */
2125 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00002126 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002127 ++scan;
2128
2129 /* Create a long object that can contain the largest possible
2130 * integer with this base and length. Note that there's no
2131 * need to initialize z->ob_digit -- no slot is read up before
2132 * being stored into.
2133 */
2134 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002135 /* Uncomment next line to test exceedingly rare copy code */
2136 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002137 assert(size_z > 0);
2138 z = _PyLong_New(size_z);
2139 if (z == NULL)
2140 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002141 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002142
2143 /* `convwidth` consecutive input digits are treated as a single
2144 * digit in base `convmultmax`.
2145 */
2146 convwidth = convwidth_base[base];
2147 convmultmax = convmultmax_base[base];
2148
2149 /* Work ;-) */
2150 while (str < scan) {
2151 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00002152 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002153 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2154 c = (twodigits)(c * base +
Raymond Hettinger35631532009-01-09 03:58:09 +00002155 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002156 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002157 }
2158
2159 convmult = convmultmax;
2160 /* Calculate the shift only if we couldn't get
2161 * convwidth digits.
2162 */
2163 if (i != convwidth) {
2164 convmult = base;
2165 for ( ; i > 1; --i)
2166 convmult *= base;
2167 }
2168
2169 /* Multiply z by convmult, and add c. */
2170 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00002171 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002172 for (; pz < pzstop; ++pz) {
2173 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002174 *pz = (digit)(c & PyLong_MASK);
2175 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002176 }
2177 /* carry off the current end? */
2178 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002179 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00002180 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002181 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00002182 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002183 }
2184 else {
2185 PyLongObject *tmp;
2186 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002187 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002188 tmp = _PyLong_New(size_z + 1);
2189 if (tmp == NULL) {
2190 Py_DECREF(z);
2191 return NULL;
2192 }
2193 memcpy(tmp->ob_digit,
2194 z->ob_digit,
2195 sizeof(digit) * size_z);
2196 Py_DECREF(z);
2197 z = tmp;
2198 z->ob_digit[size_z] = (digit)c;
2199 ++size_z;
2200 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002201 }
Tim Petersbf2674b2003-02-02 07:51:32 +00002202 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002203 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00002204 if (z == NULL)
2205 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002206 if (error_if_nonzero) {
2207 /* reset the base to 0, else the exception message
2208 doesn't make too much sense */
2209 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00002210 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002211 goto onError;
2212 /* there might still be other problems, therefore base
2213 remains zero here for the same reason */
2214 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00002215 if (str == start)
2216 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002217 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00002218 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00002219 while (*str && isspace(Py_CHARMASK(*str)))
2220 str++;
2221 if (*str != '\0')
2222 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002223 if (pend)
2224 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00002225 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002226 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002227
2228 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002229 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002230 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002231 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002232 if (strobj == NULL)
2233 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002234 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002235 "invalid literal for int() with base %d: %R",
2236 base, strobj);
2237 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002238 return NULL;
2239}
2240
2241PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002242PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002243{
Walter Dörwald07e14762002-11-06 16:15:14 +00002244 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002245 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002246
Walter Dörwald07e14762002-11-06 16:15:14 +00002247 if (buffer == NULL)
2248 return NULL;
2249
2250 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2251 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002252 return NULL;
2253 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002254 result = PyLong_FromString(buffer, NULL, base);
2255 PyMem_FREE(buffer);
2256 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002257}
2258
Tim Peters9f688bf2000-07-07 15:53:28 +00002259/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002260static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002261 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002262static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002263
2264/* Long division with remainder, top-level routine */
2265
Guido van Rossume32e0141992-01-19 16:31:05 +00002266static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002267long_divrem(PyLongObject *a, PyLongObject *b,
2268 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002269{
Christian Heimes90aa7642007-12-19 02:45:37 +00002270 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002271 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002272
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002273 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002274 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002275 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002276 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002277 }
2278 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002279 (size_a == size_b &&
2280 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002281 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002282 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002283 if (*pdiv == NULL)
2284 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002285 Py_INCREF(a);
2286 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002287 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002288 }
2289 if (size_b == 1) {
2290 digit rem = 0;
2291 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002292 if (z == NULL)
2293 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002294 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002295 if (*prem == NULL) {
2296 Py_DECREF(z);
2297 return -1;
2298 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002299 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002300 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002301 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002302 if (z == NULL)
2303 return -1;
2304 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002305 /* Set the signs.
2306 The quotient z has the sign of a*b;
2307 the remainder r has the sign of a,
2308 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002309 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002310 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002311 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002312 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002313 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002314 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002315}
2316
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002317/* Unsigned long division with remainder -- the algorithm. The arguments v1
2318 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002319
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002320static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002321x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002322{
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002323 PyLongObject *v, *w, *a;
2324 Py_ssize_t i, k, size_v, size_w;
2325 int d;
2326 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2327 twodigits vv;
2328 sdigit zhi;
2329 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002330
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002331 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2332 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2333 handle the special case when the initial estimate q for a quotient
2334 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2335 that won't overflow a digit. */
2336
2337 /* allocate space; w will also be used to hold the final remainder */
2338 size_v = ABS(Py_SIZE(v1));
2339 size_w = ABS(Py_SIZE(w1));
2340 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2341 v = _PyLong_New(size_v+1);
2342 if (v == NULL) {
2343 *prem = NULL;
2344 return NULL;
2345 }
2346 w = _PyLong_New(size_w);
2347 if (w == NULL) {
2348 Py_DECREF(v);
2349 *prem = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002350 return NULL;
2351 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002352
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002353 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2354 shift v1 left by the same amount. Results go into w and v. */
2355 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2356 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2357 assert(carry == 0);
2358 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2359 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2360 v->ob_digit[size_v] = carry;
2361 size_v++;
2362 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002363
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002364 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2365 at most (and usually exactly) k = size_v - size_w digits. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002366 k = size_v - size_w;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002367 assert(k >= 0);
2368 a = _PyLong_New(k);
2369 if (a == NULL) {
2370 Py_DECREF(w);
2371 Py_DECREF(v);
2372 *prem = NULL;
2373 return NULL;
2374 }
2375 v0 = v->ob_digit;
2376 w0 = w->ob_digit;
2377 wm1 = w0[size_w-1];
2378 wm2 = w0[size_w-2];
2379 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2380 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2381 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002382
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002383 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002384 Py_DECREF(a);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002385 Py_DECREF(w);
2386 Py_DECREF(v);
2387 *prem = NULL;
2388 return NULL;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002389 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002390
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002391 /* estimate quotient digit q; may overestimate by 1 (rare) */
2392 vtop = vk[size_w];
2393 assert(vtop <= wm1);
2394 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2395 q = (digit)(vv / wm1);
2396 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2397 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2398 | vk[size_w-2])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002399 --q;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002400 r += wm1;
2401 if (r >= PyLong_BASE)
2402 break;
2403 }
2404 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002405
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002406 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2407 zhi = 0;
2408 for (i = 0; i < size_w; ++i) {
2409 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2410 -PyLong_BASE * q <= z < PyLong_BASE */
2411 z = (sdigit)vk[i] + zhi -
2412 (stwodigits)q * (stwodigits)w0[i];
2413 vk[i] = (digit)z & PyLong_MASK;
2414 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2415 z, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002416 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002417
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002418 /* add w back if q was too large (this branch taken rarely) */
2419 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2420 if ((sdigit)vtop + zhi < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002421 carry = 0;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002422 for (i = 0; i < size_w; ++i) {
2423 carry += vk[i] + w0[i];
2424 vk[i] = carry & PyLong_MASK;
2425 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002426 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002427 --q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002428 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002429
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002430 /* store quotient digit */
2431 assert(q < PyLong_BASE);
2432 *--ak = q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002433 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002434
2435 /* unshift remainder; we reuse w to store the result */
2436 carry = v_rshift(w0, v0, size_w, d);
2437 assert(carry==0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002438 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002439
2440 *prem = long_normalize(w);
2441 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002442}
2443
2444/* Methods */
2445
2446static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002447long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002448{
Christian Heimes90aa7642007-12-19 02:45:37 +00002449 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002450}
2451
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002452static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002453long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002454{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002455 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002456
Christian Heimes90aa7642007-12-19 02:45:37 +00002457 if (Py_SIZE(a) != Py_SIZE(b)) {
2458 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002459 sign = 0;
2460 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002461 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002462 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002463 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002464 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002465 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2466 ;
2467 if (i < 0)
2468 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002469 else {
Mark Dickinsone4416742009-02-15 15:14:57 +00002470 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002471 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002472 sign = -sign;
2473 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002474 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002475 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002476}
2477
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002478#define TEST_COND(cond) \
2479 ((cond) ? Py_True : Py_False)
2480
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002481static PyObject *
2482long_richcompare(PyObject *self, PyObject *other, int op)
2483{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002484 int result;
2485 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002486 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002487 if (self == other)
2488 result = 0;
2489 else
2490 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2491 /* Convert the return value to a Boolean */
2492 switch (op) {
2493 case Py_EQ:
2494 v = TEST_COND(result == 0);
2495 break;
2496 case Py_NE:
2497 v = TEST_COND(result != 0);
2498 break;
2499 case Py_LE:
2500 v = TEST_COND(result <= 0);
2501 break;
2502 case Py_GE:
2503 v = TEST_COND(result >= 0);
2504 break;
2505 case Py_LT:
2506 v = TEST_COND(result == -1);
2507 break;
2508 case Py_GT:
2509 v = TEST_COND(result == 1);
2510 break;
2511 default:
2512 PyErr_BadArgument();
2513 return NULL;
2514 }
2515 Py_INCREF(v);
2516 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002517}
2518
Guido van Rossum9bfef441993-03-29 10:43:31 +00002519static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002520long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002521{
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002522 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002523 Py_ssize_t i;
2524 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002525
2526 /* This is designed so that Python ints and longs with the
2527 same value hash to the same value, otherwise comparisons
2528 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002529 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002530 switch(i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00002531 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00002532 case 0: return 0;
2533 case 1: return v->ob_digit[0];
2534 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002535 sign = 1;
2536 x = 0;
2537 if (i < 0) {
2538 sign = -1;
2539 i = -(i);
2540 }
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002541 /* The following loop produces a C unsigned long x such that x is
2542 congruent to the absolute value of v modulo ULONG_MAX. The
Thomas Woutersce272b62007-09-19 21:19:28 +00002543 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002544 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002545 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002546 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002547 x += v->ob_digit[i];
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002548 /* If the addition above overflowed we compensate by
2549 incrementing. This preserves the value modulo
2550 ULONG_MAX. */
2551 if (x < v->ob_digit[i])
Thomas Woutersce272b62007-09-19 21:19:28 +00002552 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002553 }
2554 x = x * sign;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002555 if (x == (unsigned long)-1)
2556 x = (unsigned long)-2;
2557 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002558}
2559
2560
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002561/* Add the absolute values of two long integers. */
2562
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002563static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002564x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002565{
Christian Heimes90aa7642007-12-19 02:45:37 +00002566 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002567 PyLongObject *z;
Mark Dickinson17e55872009-01-24 15:56:57 +00002568 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002569 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002570
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002571 /* Ensure a is the larger of the two: */
2572 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002573 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002574 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002575 size_a = size_b;
2576 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002577 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002578 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002579 if (z == NULL)
2580 return NULL;
2581 for (i = 0; i < size_b; ++i) {
2582 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002583 z->ob_digit[i] = carry & PyLong_MASK;
2584 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002585 }
2586 for (; i < size_a; ++i) {
2587 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002588 z->ob_digit[i] = carry & PyLong_MASK;
2589 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002590 }
2591 z->ob_digit[i] = carry;
2592 return long_normalize(z);
2593}
2594
2595/* Subtract the absolute values of two integers. */
2596
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002597static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002598x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002599{
Christian Heimes90aa7642007-12-19 02:45:37 +00002600 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002601 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002602 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002603 int sign = 1;
2604 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002605
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002606 /* Ensure a is the larger of the two: */
2607 if (size_a < size_b) {
2608 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002609 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002610 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002611 size_a = size_b;
2612 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002613 }
2614 else if (size_a == size_b) {
2615 /* Find highest digit where a and b differ: */
2616 i = size_a;
2617 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2618 ;
2619 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002620 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002621 if (a->ob_digit[i] < b->ob_digit[i]) {
2622 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002623 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002624 }
2625 size_a = size_b = i+1;
2626 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002627 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002628 if (z == NULL)
2629 return NULL;
2630 for (i = 0; i < size_b; ++i) {
2631 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002632 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002633 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002634 z->ob_digit[i] = borrow & PyLong_MASK;
2635 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002636 borrow &= 1; /* Keep only one sign bit */
2637 }
2638 for (; i < size_a; ++i) {
2639 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002640 z->ob_digit[i] = borrow & PyLong_MASK;
2641 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002642 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002643 }
2644 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002645 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002646 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002647 return long_normalize(z);
2648}
2649
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002650static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002651long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002652{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002653 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002654
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002655 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002656
Christian Heimes90aa7642007-12-19 02:45:37 +00002657 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002658 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002659 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002660 return result;
2661 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002662 if (Py_SIZE(a) < 0) {
2663 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002664 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002665 if (z != NULL && Py_SIZE(z) != 0)
2666 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002667 }
2668 else
2669 z = x_sub(b, a);
2670 }
2671 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002672 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002673 z = x_sub(a, b);
2674 else
2675 z = x_add(a, b);
2676 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002677 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002678}
2679
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002680static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002681long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002682{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002683 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002684
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002685 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002686
Christian Heimes90aa7642007-12-19 02:45:37 +00002687 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002688 PyObject* r;
2689 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002690 return r;
2691 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002692 if (Py_SIZE(a) < 0) {
2693 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002694 z = x_sub(a, b);
2695 else
2696 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002697 if (z != NULL && Py_SIZE(z) != 0)
2698 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002699 }
2700 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002701 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002702 z = x_add(a, b);
2703 else
2704 z = x_sub(a, b);
2705 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002706 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002707}
2708
Tim Peters5af4e6c2002-08-12 02:31:19 +00002709/* Grade school multiplication, ignoring the signs.
2710 * Returns the absolute value of the product, or NULL if error.
2711 */
2712static PyLongObject *
2713x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002714{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002715 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002716 Py_ssize_t size_a = ABS(Py_SIZE(a));
2717 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002718 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002719
Tim Peters5af4e6c2002-08-12 02:31:19 +00002720 z = _PyLong_New(size_a + size_b);
2721 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002722 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002723
Christian Heimes90aa7642007-12-19 02:45:37 +00002724 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002725 if (a == b) {
2726 /* Efficient squaring per HAC, Algorithm 14.16:
2727 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2728 * Gives slightly less than a 2x speedup when a == b,
2729 * via exploiting that each entry in the multiplication
2730 * pyramid appears twice (except for the size_a squares).
2731 */
2732 for (i = 0; i < size_a; ++i) {
2733 twodigits carry;
2734 twodigits f = a->ob_digit[i];
2735 digit *pz = z->ob_digit + (i << 1);
2736 digit *pa = a->ob_digit + i + 1;
2737 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002738
Tim Peters0973b992004-08-29 22:16:50 +00002739 SIGCHECK({
2740 Py_DECREF(z);
2741 return NULL;
2742 })
2743
2744 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002745 *pz++ = (digit)(carry & PyLong_MASK);
2746 carry >>= PyLong_SHIFT;
2747 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002748
2749 /* Now f is added in twice in each column of the
2750 * pyramid it appears. Same as adding f<<1 once.
2751 */
2752 f <<= 1;
2753 while (pa < paend) {
2754 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002755 *pz++ = (digit)(carry & PyLong_MASK);
2756 carry >>= PyLong_SHIFT;
2757 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002758 }
2759 if (carry) {
2760 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002761 *pz++ = (digit)(carry & PyLong_MASK);
2762 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002763 }
2764 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002765 *pz += (digit)(carry & PyLong_MASK);
2766 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002767 }
Tim Peters0973b992004-08-29 22:16:50 +00002768 }
2769 else { /* a is not the same as b -- gradeschool long mult */
2770 for (i = 0; i < size_a; ++i) {
2771 twodigits carry = 0;
2772 twodigits f = a->ob_digit[i];
2773 digit *pz = z->ob_digit + i;
2774 digit *pb = b->ob_digit;
2775 digit *pbend = b->ob_digit + size_b;
2776
2777 SIGCHECK({
2778 Py_DECREF(z);
2779 return NULL;
2780 })
2781
2782 while (pb < pbend) {
2783 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002784 *pz++ = (digit)(carry & PyLong_MASK);
2785 carry >>= PyLong_SHIFT;
2786 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002787 }
2788 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002789 *pz += (digit)(carry & PyLong_MASK);
2790 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002791 }
2792 }
Tim Peters44121a62002-08-12 06:17:58 +00002793 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002794}
2795
2796/* A helper for Karatsuba multiplication (k_mul).
2797 Takes a long "n" and an integer "size" representing the place to
2798 split, and sets low and high such that abs(n) == (high << size) + low,
2799 viewing the shift as being by digits. The sign bit is ignored, and
2800 the return values are >= 0.
2801 Returns 0 on success, -1 on failure.
2802*/
2803static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002804kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002805{
2806 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002807 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002808 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002809
2810 size_lo = MIN(size_n, size);
2811 size_hi = size_n - size_lo;
2812
2813 if ((hi = _PyLong_New(size_hi)) == NULL)
2814 return -1;
2815 if ((lo = _PyLong_New(size_lo)) == NULL) {
2816 Py_DECREF(hi);
2817 return -1;
2818 }
2819
2820 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2821 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2822
2823 *high = long_normalize(hi);
2824 *low = long_normalize(lo);
2825 return 0;
2826}
2827
Tim Peters60004642002-08-12 22:01:34 +00002828static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2829
Tim Peters5af4e6c2002-08-12 02:31:19 +00002830/* Karatsuba multiplication. Ignores the input signs, and returns the
2831 * absolute value of the product (or NULL if error).
2832 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2833 */
2834static PyLongObject *
2835k_mul(PyLongObject *a, PyLongObject *b)
2836{
Christian Heimes90aa7642007-12-19 02:45:37 +00002837 Py_ssize_t asize = ABS(Py_SIZE(a));
2838 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002839 PyLongObject *ah = NULL;
2840 PyLongObject *al = NULL;
2841 PyLongObject *bh = NULL;
2842 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002843 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002844 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002845 Py_ssize_t shift; /* the number of digits we split off */
2846 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002847
Tim Peters5af4e6c2002-08-12 02:31:19 +00002848 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2849 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2850 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002851 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002852 * By picking X to be a power of 2, "*X" is just shifting, and it's
2853 * been reduced to 3 multiplies on numbers half the size.
2854 */
2855
Tim Petersfc07e562002-08-12 02:54:10 +00002856 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002857 * is largest.
2858 */
Tim Peters738eda72002-08-12 15:08:20 +00002859 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002860 t1 = a;
2861 a = b;
2862 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002863
2864 i = asize;
2865 asize = bsize;
2866 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002867 }
2868
2869 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002870 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2871 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002872 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002873 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002874 else
2875 return x_mul(a, b);
2876 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002877
Tim Peters60004642002-08-12 22:01:34 +00002878 /* If a is small compared to b, splitting on b gives a degenerate
2879 * case with ah==0, and Karatsuba may be (even much) less efficient
2880 * than "grade school" then. However, we can still win, by viewing
2881 * b as a string of "big digits", each of width a->ob_size. That
2882 * leads to a sequence of balanced calls to k_mul.
2883 */
2884 if (2 * asize <= bsize)
2885 return k_lopsided_mul(a, b);
2886
Tim Petersd6974a52002-08-13 20:37:51 +00002887 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002888 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002889 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002890 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002891
Tim Peters0973b992004-08-29 22:16:50 +00002892 if (a == b) {
2893 bh = ah;
2894 bl = al;
2895 Py_INCREF(bh);
2896 Py_INCREF(bl);
2897 }
2898 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002899
Tim Petersd64c1de2002-08-12 17:36:03 +00002900 /* The plan:
2901 * 1. Allocate result space (asize + bsize digits: that's always
2902 * enough).
2903 * 2. Compute ah*bh, and copy into result at 2*shift.
2904 * 3. Compute al*bl, and copy into result at 0. Note that this
2905 * can't overlap with #2.
2906 * 4. Subtract al*bl from the result, starting at shift. This may
2907 * underflow (borrow out of the high digit), but we don't care:
2908 * we're effectively doing unsigned arithmetic mod
2909 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2910 * borrows and carries out of the high digit can be ignored.
2911 * 5. Subtract ah*bh from the result, starting at shift.
2912 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2913 * at shift.
2914 */
2915
2916 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002917 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002918 if (ret == NULL) goto fail;
2919#ifdef Py_DEBUG
2920 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002921 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002922#endif
Tim Peters44121a62002-08-12 06:17:58 +00002923
Tim Petersd64c1de2002-08-12 17:36:03 +00002924 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002925 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002926 assert(Py_SIZE(t1) >= 0);
2927 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002928 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002929 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002930
2931 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002932 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002933 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002934 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002935 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002936
Tim Petersd64c1de2002-08-12 17:36:03 +00002937 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002938 if ((t2 = k_mul(al, bl)) == NULL) {
2939 Py_DECREF(t1);
2940 goto fail;
2941 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002942 assert(Py_SIZE(t2) >= 0);
2943 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2944 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002945
2946 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002947 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002948 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002949 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002950
Tim Petersd64c1de2002-08-12 17:36:03 +00002951 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2952 * because it's fresher in cache.
2953 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002954 i = Py_SIZE(ret) - shift; /* # digits after shift */
2955 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002956 Py_DECREF(t2);
2957
Christian Heimes90aa7642007-12-19 02:45:37 +00002958 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002959 Py_DECREF(t1);
2960
Tim Petersd64c1de2002-08-12 17:36:03 +00002961 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002962 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2963 Py_DECREF(ah);
2964 Py_DECREF(al);
2965 ah = al = NULL;
2966
Tim Peters0973b992004-08-29 22:16:50 +00002967 if (a == b) {
2968 t2 = t1;
2969 Py_INCREF(t2);
2970 }
2971 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002972 Py_DECREF(t1);
2973 goto fail;
2974 }
2975 Py_DECREF(bh);
2976 Py_DECREF(bl);
2977 bh = bl = NULL;
2978
Tim Peters738eda72002-08-12 15:08:20 +00002979 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002980 Py_DECREF(t1);
2981 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002982 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002983 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002984
Tim Petersd6974a52002-08-13 20:37:51 +00002985 /* Add t3. It's not obvious why we can't run out of room here.
2986 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002987 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002988 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002989 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002990
Tim Peters5af4e6c2002-08-12 02:31:19 +00002991 return long_normalize(ret);
2992
2993 fail:
2994 Py_XDECREF(ret);
2995 Py_XDECREF(ah);
2996 Py_XDECREF(al);
2997 Py_XDECREF(bh);
2998 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002999 return NULL;
3000}
3001
Tim Petersd6974a52002-08-13 20:37:51 +00003002/* (*) Why adding t3 can't "run out of room" above.
3003
Tim Petersab86c2b2002-08-15 20:06:00 +00003004Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3005to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003006
Tim Petersab86c2b2002-08-15 20:06:00 +000030071. For any integer i, i = c(i/2) + f(i/2). In particular,
3008 bsize = c(bsize/2) + f(bsize/2).
30092. shift = f(bsize/2)
30103. asize <= bsize
30114. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3012 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003013
Tim Petersab86c2b2002-08-15 20:06:00 +00003014We allocated asize + bsize result digits, and add t3 into them at an offset
3015of shift. This leaves asize+bsize-shift allocated digit positions for t3
3016to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3017asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003018
Tim Petersab86c2b2002-08-15 20:06:00 +00003019bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3020at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003021
Tim Petersab86c2b2002-08-15 20:06:00 +00003022If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3023digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3024most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003025
Tim Petersab86c2b2002-08-15 20:06:00 +00003026The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003027
Tim Petersab86c2b2002-08-15 20:06:00 +00003028 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003029
Tim Petersab86c2b2002-08-15 20:06:00 +00003030and we have asize + c(bsize/2) available digit positions. We need to show
3031this is always enough. An instance of c(bsize/2) cancels out in both, so
3032the question reduces to whether asize digits is enough to hold
3033(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3034then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3035asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003036digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003037asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003038c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3039is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3040bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003041
Tim Peters48d52c02002-08-14 17:07:32 +00003042Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3043clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3044ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003045*/
3046
Tim Peters60004642002-08-12 22:01:34 +00003047/* b has at least twice the digits of a, and a is big enough that Karatsuba
3048 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3049 * of slices, each with a->ob_size digits, and multiply the slices by a,
3050 * one at a time. This gives k_mul balanced inputs to work with, and is
3051 * also cache-friendly (we compute one double-width slice of the result
3052 * at a time, then move on, never bactracking except for the helpful
3053 * single-width slice overlap between successive partial sums).
3054 */
3055static PyLongObject *
3056k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3057{
Christian Heimes90aa7642007-12-19 02:45:37 +00003058 const Py_ssize_t asize = ABS(Py_SIZE(a));
3059 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00003060 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00003061 PyLongObject *ret;
3062 PyLongObject *bslice = NULL;
3063
3064 assert(asize > KARATSUBA_CUTOFF);
3065 assert(2 * asize <= bsize);
3066
3067 /* Allocate result space, and zero it out. */
3068 ret = _PyLong_New(asize + bsize);
3069 if (ret == NULL)
3070 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003071 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003072
3073 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00003074 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00003075 if (bslice == NULL)
3076 goto fail;
3077
3078 nbdone = 0;
3079 while (bsize > 0) {
3080 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003081 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003082
3083 /* Multiply the next slice of b by a. */
3084 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3085 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00003086 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00003087 product = k_mul(a, bslice);
3088 if (product == NULL)
3089 goto fail;
3090
3091 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003092 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3093 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00003094 Py_DECREF(product);
3095
3096 bsize -= nbtouse;
3097 nbdone += nbtouse;
3098 }
3099
3100 Py_DECREF(bslice);
3101 return long_normalize(ret);
3102
3103 fail:
3104 Py_DECREF(ret);
3105 Py_XDECREF(bslice);
3106 return NULL;
3107}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003108
3109static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003110long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003111{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003112 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003113
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003114 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003115
Mark Dickinsonbd792642009-03-18 20:06:12 +00003116 /* fast path for single-digit multiplication */
Christian Heimes90aa7642007-12-19 02:45:37 +00003117 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonbd792642009-03-18 20:06:12 +00003118 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
3119#ifdef HAVE_LONG_LONG
3120 return PyLong_FromLongLong((PY_LONG_LONG)v);
3121#else
3122 /* if we don't have long long then we're almost certainly
3123 using 15-bit digits, so v will fit in a long. In the
3124 unlikely event that we're using 30-bit digits on a platform
3125 without long long, a large v will just cause us to fall
3126 through to the general multiplication code below. */
3127 if (v >= LONG_MIN && v <= LONG_MAX)
3128 return PyLong_FromLong((long)v);
3129#endif
Martin v. Löwis14b6d922007-02-06 21:05:30 +00003130 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003131
Tim Petersd64c1de2002-08-12 17:36:03 +00003132 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00003133 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003134 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003135 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00003136 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003137}
3138
Guido van Rossume32e0141992-01-19 16:31:05 +00003139/* The / and % operators are now defined in terms of divmod().
3140 The expression a mod b has the value a - b*floor(a/b).
3141 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003142 |a| by |b|, with the sign of a. This is also expressed
3143 as a - b*trunc(a/b), if trunc truncates towards zero.
3144 Some examples:
3145 a b a rem b a mod b
3146 13 10 3 3
3147 -13 10 -3 7
3148 13 -10 3 -7
3149 -13 -10 -3 -3
3150 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003151 have different signs. We then subtract one from the 'div'
3152 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003153
Tim Peters47e52ee2004-08-30 02:44:38 +00003154/* Compute
3155 * *pdiv, *pmod = divmod(v, w)
3156 * NULL can be passed for pdiv or pmod, in which case that part of
3157 * the result is simply thrown away. The caller owns a reference to
3158 * each of these it requests (does not pass NULL for).
3159 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003160static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003161l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00003162 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003163{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003164 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003165
Guido van Rossume32e0141992-01-19 16:31:05 +00003166 if (long_divrem(v, w, &div, &mod) < 0)
3167 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00003168 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3169 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003170 PyLongObject *temp;
3171 PyLongObject *one;
3172 temp = (PyLongObject *) long_add(mod, w);
3173 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00003174 mod = temp;
3175 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003176 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003177 return -1;
3178 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003179 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00003180 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003181 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3182 Py_DECREF(mod);
3183 Py_DECREF(div);
3184 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00003185 return -1;
3186 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003187 Py_DECREF(one);
3188 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003189 div = temp;
3190 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003191 if (pdiv != NULL)
3192 *pdiv = div;
3193 else
3194 Py_DECREF(div);
3195
3196 if (pmod != NULL)
3197 *pmod = mod;
3198 else
3199 Py_DECREF(mod);
3200
Guido van Rossume32e0141992-01-19 16:31:05 +00003201 return 0;
3202}
3203
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003204static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003205long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003206{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003207 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003208
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003209 CHECK_BINOP(a, b);
3210 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003211 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003212 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003213}
3214
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003215static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003216long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00003217{
Tim Peterse2a60002001-09-04 06:17:36 +00003218 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00003219 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00003220
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003221 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00003222 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
3223 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00003224 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00003225 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00003226 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00003227 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
3228 but should really be set correctly after sucessful calls to
3229 _PyLong_AsScaledDouble() */
3230 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00003231
3232 if (bd == 0.0) {
3233 PyErr_SetString(PyExc_ZeroDivisionError,
Mark Dickinson0b9293f2009-12-07 19:34:59 +00003234 "integer division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00003235 return NULL;
3236 }
3237
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003238 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00003239 ad /= bd; /* overflow/underflow impossible here */
3240 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003241 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00003242 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003243 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00003244 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003245 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003246 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00003247 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003248 goto overflow;
3249 return PyFloat_FromDouble(ad);
3250
3251overflow:
3252 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003253 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00003254 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003255
Tim Peters20dab9f2001-09-04 05:31:47 +00003256}
3257
3258static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003259long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003260{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003261 PyLongObject *mod;
3262
3263 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003264
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003265 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003266 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003267 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003268}
3269
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003270static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003271long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003272{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003273 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003274 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003275
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003276 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003277
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003278 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003279 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003280 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003281 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003282 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003283 PyTuple_SetItem(z, 0, (PyObject *) div);
3284 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003285 }
3286 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003287 Py_DECREF(div);
3288 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003289 }
3290 return z;
3291}
3292
Tim Peters47e52ee2004-08-30 02:44:38 +00003293/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003294static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003295long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003296{
Tim Peters47e52ee2004-08-30 02:44:38 +00003297 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3298 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003299
Tim Peters47e52ee2004-08-30 02:44:38 +00003300 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003301 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003302 PyLongObject *temp = NULL;
3303
3304 /* 5-ary values. If the exponent is large enough, table is
3305 * precomputed so that table[i] == a**i % c for i in range(32).
3306 */
3307 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3308 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3309
3310 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003311 CHECK_BINOP(v, w);
3312 a = (PyLongObject*)v; Py_INCREF(a);
3313 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003314 if (PyLong_Check(x)) {
3315 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003316 Py_INCREF(x);
3317 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003318 else if (x == Py_None)
3319 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003320 else {
3321 Py_DECREF(a);
3322 Py_DECREF(b);
3323 Py_INCREF(Py_NotImplemented);
3324 return Py_NotImplemented;
3325 }
Tim Peters4c483c42001-09-05 06:24:58 +00003326
Christian Heimes90aa7642007-12-19 02:45:37 +00003327 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003328 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003329 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003330 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003331 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003332 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003333 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003334 /* else return a float. This works because we know
3335 that this calls float_pow() which converts its
3336 arguments to double. */
3337 Py_DECREF(a);
3338 Py_DECREF(b);
3339 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003340 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003341 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003342
3343 if (c) {
3344 /* if modulus == 0:
3345 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003346 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003347 PyErr_SetString(PyExc_ValueError,
3348 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003349 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003350 }
3351
3352 /* if modulus < 0:
3353 negativeOutput = True
3354 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003355 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003356 negativeOutput = 1;
3357 temp = (PyLongObject *)_PyLong_Copy(c);
3358 if (temp == NULL)
3359 goto Error;
3360 Py_DECREF(c);
3361 c = temp;
3362 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003363 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003364 }
3365
3366 /* if modulus == 1:
3367 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003368 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003369 z = (PyLongObject *)PyLong_FromLong(0L);
3370 goto Done;
3371 }
3372
3373 /* if base < 0:
3374 base = base % modulus
3375 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003376 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003377 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003378 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003379 Py_DECREF(a);
3380 a = temp;
3381 temp = NULL;
3382 }
3383 }
3384
3385 /* At this point a, b, and c are guaranteed non-negative UNLESS
3386 c is NULL, in which case a may be negative. */
3387
3388 z = (PyLongObject *)PyLong_FromLong(1L);
3389 if (z == NULL)
3390 goto Error;
3391
3392 /* Perform a modular reduction, X = X % c, but leave X alone if c
3393 * is NULL.
3394 */
3395#define REDUCE(X) \
3396 if (c != NULL) { \
3397 if (l_divmod(X, c, NULL, &temp) < 0) \
3398 goto Error; \
3399 Py_XDECREF(X); \
3400 X = temp; \
3401 temp = NULL; \
3402 }
3403
3404 /* Multiply two values, then reduce the result:
3405 result = X*Y % c. If c is NULL, skip the mod. */
3406#define MULT(X, Y, result) \
3407{ \
3408 temp = (PyLongObject *)long_mul(X, Y); \
3409 if (temp == NULL) \
3410 goto Error; \
3411 Py_XDECREF(result); \
3412 result = temp; \
3413 temp = NULL; \
3414 REDUCE(result) \
3415}
3416
Christian Heimes90aa7642007-12-19 02:45:37 +00003417 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003418 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3419 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003420 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003421 digit bi = b->ob_digit[i];
3422
Mark Dickinsone4416742009-02-15 15:14:57 +00003423 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003424 MULT(z, z, z)
3425 if (bi & j)
3426 MULT(z, a, z)
3427 }
3428 }
3429 }
3430 else {
3431 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3432 Py_INCREF(z); /* still holds 1L */
3433 table[0] = z;
3434 for (i = 1; i < 32; ++i)
3435 MULT(table[i-1], a, table[i])
3436
Christian Heimes90aa7642007-12-19 02:45:37 +00003437 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003438 const digit bi = b->ob_digit[i];
3439
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003440 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003441 const int index = (bi >> j) & 0x1f;
3442 for (k = 0; k < 5; ++k)
3443 MULT(z, z, z)
3444 if (index)
3445 MULT(z, table[index], z)
3446 }
3447 }
3448 }
3449
Christian Heimes90aa7642007-12-19 02:45:37 +00003450 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003451 temp = (PyLongObject *)long_sub(z, c);
3452 if (temp == NULL)
3453 goto Error;
3454 Py_DECREF(z);
3455 z = temp;
3456 temp = NULL;
3457 }
3458 goto Done;
3459
3460 Error:
3461 if (z != NULL) {
3462 Py_DECREF(z);
3463 z = NULL;
3464 }
3465 /* fall through */
3466 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003467 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003468 for (i = 0; i < 32; ++i)
3469 Py_XDECREF(table[i]);
3470 }
Tim Petersde7990b2005-07-17 23:45:23 +00003471 Py_DECREF(a);
3472 Py_DECREF(b);
3473 Py_XDECREF(c);
3474 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003475 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003476}
3477
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003478static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003479long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003480{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003481 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003482 PyLongObject *x;
3483 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003484 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003485 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003486 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003487 if (w == NULL)
3488 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003489 x = (PyLongObject *) long_add(v, w);
3490 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003491 if (x == NULL)
3492 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003493 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003494 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003495}
3496
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003497static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003498long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003499{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003500 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003501 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003502 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003503 z = (PyLongObject *)_PyLong_Copy(v);
3504 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003505 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003506 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003507}
3508
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003509static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003510long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003511{
Christian Heimes90aa7642007-12-19 02:45:37 +00003512 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003513 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003514 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003515 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003516}
3517
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003518static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003519long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003520{
Christian Heimes90aa7642007-12-19 02:45:37 +00003521 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003522}
3523
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003524static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003525long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003526{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003527 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003528 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003529 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003530 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003531
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003532 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003533
Christian Heimes90aa7642007-12-19 02:45:37 +00003534 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003535 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003536 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003537 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003538 if (a1 == NULL)
3539 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003540 a2 = (PyLongObject *) long_rshift(a1, b);
3541 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003542 if (a2 == NULL)
3543 goto rshift_error;
3544 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003545 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003546 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003547 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003548
Neil Schemenauerba872e22001-01-04 01:46:03 +00003549 shiftby = PyLong_AsLong((PyObject *)b);
3550 if (shiftby == -1L && PyErr_Occurred())
3551 goto rshift_error;
3552 if (shiftby < 0) {
3553 PyErr_SetString(PyExc_ValueError,
3554 "negative shift count");
3555 goto rshift_error;
3556 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003557 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003558 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003559 if (newsize <= 0)
3560 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003561 loshift = shiftby % PyLong_SHIFT;
3562 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003563 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003564 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003565 z = _PyLong_New(newsize);
3566 if (z == NULL)
3567 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003568 if (Py_SIZE(a) < 0)
3569 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003570 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3571 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3572 if (i+1 < newsize)
3573 z->ob_digit[i] |=
3574 (a->ob_digit[j+1] << hishift) & himask;
3575 }
3576 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003577 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003578rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003579 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003580
Guido van Rossumc6913e71991-11-19 20:26:46 +00003581}
3582
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003583static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003584long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003585{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003586 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003587 PyLongObject *a = (PyLongObject*)v;
3588 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003589 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003590 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003591 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003592 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003593
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003594 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003595
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003596 shiftby = PyLong_AsLong((PyObject *)b);
3597 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003598 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003599 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003600 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003601 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003602 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003603 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003604 PyErr_SetString(PyExc_ValueError,
3605 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003606 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003607 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003608 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3609 wordshift = (int)shiftby / PyLong_SHIFT;
3610 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003611
Christian Heimes90aa7642007-12-19 02:45:37 +00003612 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003613 newsize = oldsize + wordshift;
3614 if (remshift)
3615 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003616 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003617 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003618 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003619 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003620 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003621 for (i = 0; i < wordshift; i++)
3622 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003623 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003624 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003625 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003626 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3627 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003628 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003629 if (remshift)
3630 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003631 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003632 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003633 z = long_normalize(z);
3634lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003635 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003636}
3637
Mark Dickinson27a87a22009-10-25 20:43:34 +00003638/* Compute two's complement of digit vector a[0:m], writing result to
3639 z[0:m]. The digit vector a need not be normalized, but should not
3640 be entirely zero. a and z may point to the same digit vector. */
3641
3642static void
3643v_complement(digit *z, digit *a, Py_ssize_t m)
3644{
3645 Py_ssize_t i;
3646 digit carry = 1;
3647 for (i = 0; i < m; ++i) {
3648 carry += a[i] ^ PyLong_MASK;
3649 z[i] = carry & PyLong_MASK;
3650 carry >>= PyLong_SHIFT;
3651 }
3652 assert(carry == 0);
3653}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003654
3655/* Bitwise and/xor/or operations */
3656
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003657static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003658long_bitwise(PyLongObject *a,
3659 int op, /* '&', '|', '^' */
3660 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003661{
Mark Dickinson27a87a22009-10-25 20:43:34 +00003662 int nega, negb, negz;
Mark Dickinsone4416742009-02-15 15:14:57 +00003663 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003664 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003665
Mark Dickinson27a87a22009-10-25 20:43:34 +00003666 /* Bitwise operations for negative numbers operate as though
3667 on a two's complement representation. So convert arguments
3668 from sign-magnitude to two's complement, and convert the
3669 result back to sign-magnitude at the end. */
3670
3671 /* If a is negative, replace it by its two's complement. */
3672 size_a = ABS(Py_SIZE(a));
3673 nega = Py_SIZE(a) < 0;
3674 if (nega) {
3675 z = _PyLong_New(size_a);
3676 if (z == NULL)
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003677 return NULL;
Mark Dickinson27a87a22009-10-25 20:43:34 +00003678 v_complement(z->ob_digit, a->ob_digit, size_a);
3679 a = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003680 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003681 else
3682 /* Keep reference count consistent. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003683 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003684
3685 /* Same for b. */
3686 size_b = ABS(Py_SIZE(b));
3687 negb = Py_SIZE(b) < 0;
3688 if (negb) {
3689 z = _PyLong_New(size_b);
3690 if (z == NULL) {
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003691 Py_DECREF(a);
3692 return NULL;
3693 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003694 v_complement(z->ob_digit, b->ob_digit, size_b);
3695 b = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003696 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003697 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003698 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003699
Mark Dickinson27a87a22009-10-25 20:43:34 +00003700 /* Swap a and b if necessary to ensure size_a >= size_b. */
3701 if (size_a < size_b) {
3702 z = a; a = b; b = z;
3703 size_z = size_a; size_a = size_b; size_b = size_z;
3704 negz = nega; nega = negb; negb = negz;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003705 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003706
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003707 /* JRH: The original logic here was to allocate the result value (z)
3708 as the longer of the two operands. However, there are some cases
3709 where the result is guaranteed to be shorter than that: AND of two
3710 positives, OR of two negatives: use the shorter number. AND with
3711 mixed signs: use the positive number. OR with mixed signs: use the
Mark Dickinson27a87a22009-10-25 20:43:34 +00003712 negative number.
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003713 */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003714 switch (op) {
3715 case '^':
3716 negz = nega ^ negb;
3717 size_z = size_a;
3718 break;
3719 case '&':
3720 negz = nega & negb;
3721 size_z = negb ? size_a : size_b;
3722 break;
3723 case '|':
3724 negz = nega | negb;
3725 size_z = negb ? size_b : size_a;
3726 break;
3727 default:
3728 PyErr_BadArgument();
3729 return NULL;
3730 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003731
Mark Dickinson27a87a22009-10-25 20:43:34 +00003732 /* We allow an extra digit if z is negative, to make sure that
3733 the final two's complement of z doesn't overflow. */
3734 z = _PyLong_New(size_z + negz);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003735 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003736 Py_DECREF(a);
3737 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003738 return NULL;
3739 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003740
Mark Dickinson27a87a22009-10-25 20:43:34 +00003741 /* Compute digits for overlap of a and b. */
3742 switch(op) {
3743 case '&':
3744 for (i = 0; i < size_b; ++i)
3745 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3746 break;
3747 case '|':
3748 for (i = 0; i < size_b; ++i)
3749 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3750 break;
3751 case '^':
3752 for (i = 0; i < size_b; ++i)
3753 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3754 break;
3755 default:
3756 PyErr_BadArgument();
3757 return NULL;
3758 }
3759
3760 /* Copy any remaining digits of a, inverting if necessary. */
3761 if (op == '^' && negb)
3762 for (; i < size_z; ++i)
3763 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
3764 else if (i < size_z)
3765 memcpy(&z->ob_digit[i], &a->ob_digit[i],
3766 (size_z-i)*sizeof(digit));
3767
3768 /* Complement result if negative. */
3769 if (negz) {
3770 Py_SIZE(z) = -(Py_SIZE(z));
3771 z->ob_digit[size_z] = PyLong_MASK;
3772 v_complement(z->ob_digit, z->ob_digit, size_z+1);
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003773 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003774
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003775 Py_DECREF(a);
3776 Py_DECREF(b);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003777 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00003778}
3779
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003780static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003781long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003782{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003783 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003784 CHECK_BINOP(a, b);
3785 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003786 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003787}
3788
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003789static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003790long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003791{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003792 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003793 CHECK_BINOP(a, b);
3794 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003795 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003796}
3797
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003798static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003799long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003800{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003801 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003802 CHECK_BINOP(a, b);
3803 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003804 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003805}
3806
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003807static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003808long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003809{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003810 if (PyLong_CheckExact(v))
3811 Py_INCREF(v);
3812 else
3813 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003814 return v;
3815}
3816
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003817static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003818long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003819{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003820 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003821 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003822 if (result == -1.0 && PyErr_Occurred())
3823 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003824 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003825}
3826
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003827static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003828long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003829
Tim Peters6d6c1a32001-08-02 04:15:00 +00003830static PyObject *
3831long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3832{
3833 PyObject *x = NULL;
3834 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003835 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003836
Guido van Rossumbef14172001-08-29 15:47:46 +00003837 if (type != &PyLong_Type)
3838 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003839 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003840 &x, &base))
3841 return NULL;
3842 if (x == NULL)
3843 return PyLong_FromLong(0L);
3844 if (base == -909)
3845 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003846 else if (PyUnicode_Check(x))
3847 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3848 PyUnicode_GET_SIZE(x),
3849 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003850 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003851 /* Since PyLong_FromString doesn't have a length parameter,
3852 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003853 char *string;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003854 Py_ssize_t size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003855 if (PyByteArray_Check(x))
3856 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003857 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003858 string = PyBytes_AS_STRING(x);
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003859 if (strlen(string) != (size_t)size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003860 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003861 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003862 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003863 "invalid literal for int() with base %d: %R",
3864 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003865 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003866 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003867 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003868 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003869 else {
3870 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003871 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003872 return NULL;
3873 }
3874}
3875
Guido van Rossumbef14172001-08-29 15:47:46 +00003876/* Wimpy, slow approach to tp_new calls for subtypes of long:
3877 first create a regular long from whatever arguments we got,
3878 then allocate a subtype instance and initialize it from
3879 the regular long. The regular long is then thrown away.
3880*/
3881static PyObject *
3882long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3883{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003884 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003885 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003886
3887 assert(PyType_IsSubtype(type, &PyLong_Type));
3888 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3889 if (tmp == NULL)
3890 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003891 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003892 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003893 if (n < 0)
3894 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003895 newobj = (PyLongObject *)type->tp_alloc(type, n);
3896 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003897 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003898 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003899 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003900 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003901 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003902 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003903 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003904 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003905 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003906}
3907
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003908static PyObject *
3909long_getnewargs(PyLongObject *v)
3910{
3911 return Py_BuildValue("(N)", _PyLong_Copy(v));
3912}
3913
Guido van Rossumb43daf72007-08-01 18:08:08 +00003914static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00003915long_get0(PyLongObject *v, void *context) {
3916 return PyLong_FromLong(0L);
3917}
3918
3919static PyObject *
3920long_get1(PyLongObject *v, void *context) {
3921 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003922}
3923
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003924static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003925long__format__(PyObject *self, PyObject *args)
3926{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003927 PyObject *format_spec;
3928
3929 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3930 return NULL;
3931 return _PyLong_FormatAdvanced(self,
3932 PyUnicode_AS_UNICODE(format_spec),
3933 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003934}
3935
Eric Smith8c663262007-08-25 02:26:07 +00003936static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003937long_round(PyObject *self, PyObject *args)
3938{
Mark Dickinson1124e712009-01-28 21:25:58 +00003939 PyObject *o_ndigits=NULL, *temp;
3940 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
3941 int errcode;
3942 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003943
Mark Dickinson1124e712009-01-28 21:25:58 +00003944 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
3945 the straightforward method is:
3946
3947 (1) divide by 10**n
3948 (2) round to nearest integer (round to even in case of tie)
3949 (3) multiply result by 10**n.
3950
3951 But the rounding step involves examining the fractional part of the
3952 quotient to see whether it's greater than 0.5 or not. Since we
3953 want to do the whole calculation in integer arithmetic, it's
3954 simpler to do:
3955
3956 (1) divide by (10**n)/2
3957 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
3958 (3) multiply result by (10**n)/2.
3959
3960 Then all we need to know about the fractional part of the quotient
3961 arising in step (2) is whether it's zero or not.
3962
3963 Doing both a multiplication and division is wasteful, and is easily
3964 avoided if we just figure out how much to adjust the original input
3965 by to do the rounding.
3966
3967 Here's the whole algorithm expressed in Python.
3968
3969 def round(self, ndigits = None):
3970 """round(int, int) -> int"""
3971 if ndigits is None or ndigits >= 0:
3972 return self
3973 pow = 10**-ndigits >> 1
3974 q, r = divmod(self, pow)
3975 self -= r
3976 if (q & 1 != 0):
3977 if (q & 2 == r == 0):
3978 self -= pow
3979 else:
3980 self += pow
3981 return self
3982
3983 */
3984 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
3985 return NULL;
3986 if (o_ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003987 return long_long(self);
3988
Mark Dickinson1124e712009-01-28 21:25:58 +00003989 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
3990 if (ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003991 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00003992
3993 if (Py_SIZE(ndigits) >= 0) {
3994 Py_DECREF(ndigits);
3995 return long_long(self);
3996 }
3997
3998 Py_INCREF(self); /* to keep refcounting simple */
3999 /* we now own references to self, ndigits */
4000
4001 /* pow = 10 ** -ndigits >> 1 */
4002 pow = (PyLongObject *)PyLong_FromLong(10L);
4003 if (pow == NULL)
4004 goto error;
4005 temp = long_neg(ndigits);
4006 Py_DECREF(ndigits);
4007 ndigits = (PyLongObject *)temp;
4008 if (ndigits == NULL)
4009 goto error;
4010 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
4011 Py_DECREF(pow);
4012 pow = (PyLongObject *)temp;
4013 if (pow == NULL)
4014 goto error;
4015 assert(PyLong_Check(pow)); /* check long_pow returned a long */
4016 one = (PyLongObject *)PyLong_FromLong(1L);
4017 if (one == NULL)
4018 goto error;
4019 temp = long_rshift(pow, one);
4020 Py_DECREF(one);
4021 Py_DECREF(pow);
4022 pow = (PyLongObject *)temp;
4023 if (pow == NULL)
4024 goto error;
4025
4026 /* q, r = divmod(self, pow) */
4027 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
4028 if (errcode == -1)
4029 goto error;
4030
4031 /* self -= r */
4032 temp = long_sub((PyLongObject *)self, r);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004033 Py_DECREF(self);
Mark Dickinson1124e712009-01-28 21:25:58 +00004034 self = temp;
4035 if (self == NULL)
4036 goto error;
4037
4038 /* get value of quotient modulo 4 */
4039 if (Py_SIZE(q) == 0)
4040 q_mod_4 = 0;
4041 else if (Py_SIZE(q) > 0)
4042 q_mod_4 = q->ob_digit[0] & 3;
4043 else
4044 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
4045
4046 if ((q_mod_4 & 1) == 1) {
4047 /* q is odd; round self up or down by adding or subtracting pow */
4048 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
4049 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
4050 else
4051 temp = (PyObject *)long_add((PyLongObject *)self, pow);
4052 Py_DECREF(self);
4053 self = temp;
4054 if (self == NULL)
4055 goto error;
4056 }
4057 Py_DECREF(q);
4058 Py_DECREF(r);
4059 Py_DECREF(pow);
4060 Py_DECREF(ndigits);
4061 return self;
4062
4063 error:
4064 Py_XDECREF(q);
4065 Py_XDECREF(r);
4066 Py_XDECREF(pow);
4067 Py_XDECREF(self);
4068 Py_XDECREF(ndigits);
4069 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004070}
4071
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004072static PyObject *
4073long_sizeof(PyLongObject *v)
4074{
4075 Py_ssize_t res;
4076
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004077 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004078 return PyLong_FromSsize_t(res);
4079}
4080
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004081static PyObject *
4082long_bit_length(PyLongObject *v)
4083{
4084 PyLongObject *result, *x, *y;
4085 Py_ssize_t ndigits, msd_bits = 0;
4086 digit msd;
4087
4088 assert(v != NULL);
4089 assert(PyLong_Check(v));
4090
4091 ndigits = ABS(Py_SIZE(v));
4092 if (ndigits == 0)
4093 return PyLong_FromLong(0);
4094
4095 msd = v->ob_digit[ndigits-1];
4096 while (msd >= 32) {
4097 msd_bits += 6;
4098 msd >>= 6;
4099 }
4100 msd_bits += (long)(BitLengthTable[msd]);
4101
4102 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4103 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
4104
4105 /* expression above may overflow; use Python integers instead */
4106 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4107 if (result == NULL)
4108 return NULL;
4109 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4110 if (x == NULL)
4111 goto error;
4112 y = (PyLongObject *)long_mul(result, x);
4113 Py_DECREF(x);
4114 if (y == NULL)
4115 goto error;
4116 Py_DECREF(result);
4117 result = y;
4118
4119 x = (PyLongObject *)PyLong_FromLong(msd_bits);
4120 if (x == NULL)
4121 goto error;
4122 y = (PyLongObject *)long_add(result, x);
4123 Py_DECREF(x);
4124 if (y == NULL)
4125 goto error;
4126 Py_DECREF(result);
4127 result = y;
4128
4129 return (PyObject *)result;
4130
4131error:
4132 Py_DECREF(result);
4133 return NULL;
4134}
4135
4136PyDoc_STRVAR(long_bit_length_doc,
4137"int.bit_length() -> int\n\
4138\n\
4139Number of bits necessary to represent self in binary.\n\
4140>>> bin(37)\n\
4141'0b100101'\n\
4142>>> (37).bit_length()\n\
41436");
4144
Christian Heimes53876d92008-04-19 00:31:39 +00004145#if 0
4146static PyObject *
4147long_is_finite(PyObject *v)
4148{
4149 Py_RETURN_TRUE;
4150}
4151#endif
4152
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004153static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00004154 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4155 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004156 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4157 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004158#if 0
4159 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4160 "Returns always True."},
4161#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004162 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4163 "Truncating an Integral returns itself."},
4164 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4165 "Flooring an Integral returns itself."},
4166 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4167 "Ceiling of an Integral returns itself."},
4168 {"__round__", (PyCFunction)long_round, METH_VARARGS,
Mark Dickinson1124e712009-01-28 21:25:58 +00004169 "Rounding an Integral returns itself.\n"
4170 "Rounding with an ndigits argument also returns an integer."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004171 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00004172 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004173 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4174 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004175 {NULL, NULL} /* sentinel */
4176};
4177
Guido van Rossumb43daf72007-08-01 18:08:08 +00004178static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004179 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004180 (getter)long_long, (setter)NULL,
4181 "the real part of a complex number",
4182 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004183 {"imag",
4184 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004185 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004186 NULL},
4187 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004188 (getter)long_long, (setter)NULL,
4189 "the numerator of a rational number in lowest terms",
4190 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004191 {"denominator",
4192 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004193 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004194 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004195 {NULL} /* Sentinel */
4196};
4197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004198PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004199"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004200\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004201Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004202point argument will be truncated towards zero (this does not include a\n\
4203string representation of a floating point number!) When converting a\n\
4204string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004205converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004207static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00004208 (binaryfunc) long_add, /*nb_add*/
4209 (binaryfunc) long_sub, /*nb_subtract*/
4210 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004211 long_mod, /*nb_remainder*/
4212 long_divmod, /*nb_divmod*/
4213 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004214 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004215 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004216 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00004217 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004218 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004219 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004220 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004221 long_and, /*nb_and*/
4222 long_xor, /*nb_xor*/
4223 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004224 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00004225 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004226 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00004227 0, /* nb_inplace_add */
4228 0, /* nb_inplace_subtract */
4229 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00004230 0, /* nb_inplace_remainder */
4231 0, /* nb_inplace_power */
4232 0, /* nb_inplace_lshift */
4233 0, /* nb_inplace_rshift */
4234 0, /* nb_inplace_and */
4235 0, /* nb_inplace_xor */
4236 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004237 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00004238 long_true_divide, /* nb_true_divide */
4239 0, /* nb_inplace_floor_divide */
4240 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004241 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004242};
4243
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004244PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004245 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00004246 "int", /* tp_name */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004247 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004248 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004249 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004250 0, /* tp_print */
4251 0, /* tp_getattr */
4252 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00004253 0, /* tp_reserved */
Mark Dickinson2031d132009-09-17 00:17:48 +00004254 long_to_decimal_string, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004255 &long_as_number, /* tp_as_number */
4256 0, /* tp_as_sequence */
4257 0, /* tp_as_mapping */
4258 (hashfunc)long_hash, /* tp_hash */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004259 0, /* tp_call */
Mark Dickinson2031d132009-09-17 00:17:48 +00004260 long_to_decimal_string, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004261 PyObject_GenericGetAttr, /* tp_getattro */
4262 0, /* tp_setattro */
4263 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00004264 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4265 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004266 long_doc, /* tp_doc */
4267 0, /* tp_traverse */
4268 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00004269 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004270 0, /* tp_weaklistoffset */
4271 0, /* tp_iter */
4272 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004273 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004274 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00004275 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004276 0, /* tp_base */
4277 0, /* tp_dict */
4278 0, /* tp_descr_get */
4279 0, /* tp_descr_set */
4280 0, /* tp_dictoffset */
4281 0, /* tp_init */
4282 0, /* tp_alloc */
4283 long_new, /* tp_new */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004284 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004285};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004286
Mark Dickinsonbd792642009-03-18 20:06:12 +00004287static PyTypeObject Int_InfoType;
4288
4289PyDoc_STRVAR(int_info__doc__,
4290"sys.int_info\n\
4291\n\
4292A struct sequence that holds information about Python's\n\
4293internal representation of integers. The attributes are read only.");
4294
4295static PyStructSequence_Field int_info_fields[] = {
4296 {"bits_per_digit", "size of a digit in bits"},
4297 {"sizeof_digit", "size in bytes of the C type used to "
4298 "represent a digit"},
4299 {NULL, NULL}
4300};
4301
4302static PyStructSequence_Desc int_info_desc = {
4303 "sys.int_info", /* name */
4304 int_info__doc__, /* doc */
4305 int_info_fields, /* fields */
4306 2 /* number of fields */
4307};
4308
4309PyObject *
4310PyLong_GetInfo(void)
4311{
4312 PyObject* int_info;
4313 int field = 0;
4314 int_info = PyStructSequence_New(&Int_InfoType);
4315 if (int_info == NULL)
4316 return NULL;
Mark Dickinson0bdab682009-04-02 18:41:40 +00004317 PyStructSequence_SET_ITEM(int_info, field++,
4318 PyLong_FromLong(PyLong_SHIFT));
4319 PyStructSequence_SET_ITEM(int_info, field++,
4320 PyLong_FromLong(sizeof(digit)));
Mark Dickinsonbd792642009-03-18 20:06:12 +00004321 if (PyErr_Occurred()) {
4322 Py_CLEAR(int_info);
4323 return NULL;
4324 }
4325 return int_info;
4326}
4327
Guido van Rossumddefaf32007-01-14 03:31:43 +00004328int
4329_PyLong_Init(void)
4330{
4331#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004332 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004333 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004334
4335 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4336 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4337 if (Py_TYPE(v) == &PyLong_Type) {
4338 /* The element is already initialized, most likely
4339 * the Python interpreter was initialized before.
4340 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00004341 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004342 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004343
Christian Heimes48aa4b12008-02-01 16:56:30 +00004344 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4345 _Py_NewReference(op);
4346 /* _Py_NewReference sets the ref count to 1 but
4347 * the ref count might be larger. Set the refcnt
4348 * to the original refcnt + 1 */
4349 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004350 assert(Py_SIZE(op) == size);
4351 assert(v->ob_digit[0] == abs(ival));
4352 }
4353 else {
4354 PyObject_INIT(v, &PyLong_Type);
4355 }
4356 Py_SIZE(v) = size;
4357 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004358 }
4359#endif
Mark Dickinsonbd792642009-03-18 20:06:12 +00004360 /* initialize int_info */
4361 if (Int_InfoType.tp_name == 0)
4362 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
4363
Guido van Rossumddefaf32007-01-14 03:31:43 +00004364 return 1;
4365}
4366
4367void
4368PyLong_Fini(void)
4369{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004370 /* Integers are currently statically allocated. Py_DECREF is not
4371 needed, but Python must forget about the reference or multiple
4372 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004373#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004374 int i;
4375 PyLongObject *v = small_ints;
4376 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4377 _Py_DEC_REFTOTAL;
4378 _Py_ForgetReference((PyObject*)v);
4379 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004380#endif
4381}