blob: 8e4093c79d50f3a0161c47d5f5f101928783b9e2 [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;
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000349 nb = vv->ob_type->tp_as_number;
350 if (nb == NULL || nb->nb_int == NULL) {
351 PyErr_SetString(PyExc_TypeError,
352 "an integer is required");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000353 return -1;
354 }
355 vv = (*nb->nb_int) (vv);
356 if (vv == NULL)
357 return -1;
358 do_decref = 1;
359 if (!PyLong_Check(vv)) {
360 Py_DECREF(vv);
361 PyErr_SetString(PyExc_TypeError,
362 "nb_int should return int object");
363 return -1;
364 }
365 }
366
Georg Brandl61c31b02007-02-26 14:46:30 +0000367 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000368 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000369 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000370
Georg Brandl61c31b02007-02-26 14:46:30 +0000371 switch (i) {
372 case -1:
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000373 res = -(sdigit)v->ob_digit[0];
Georg Brandl61c31b02007-02-26 14:46:30 +0000374 break;
375 case 0:
376 res = 0;
377 break;
378 case 1:
379 res = v->ob_digit[0];
380 break;
381 default:
382 sign = 1;
383 x = 0;
384 if (i < 0) {
385 sign = -1;
386 i = -(i);
387 }
388 while (--i >= 0) {
389 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000390 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000391 if ((x >> PyLong_SHIFT) != prev) {
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000392 *overflow = sign;
Georg Brandl61c31b02007-02-26 14:46:30 +0000393 goto exit;
394 }
395 }
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000396 /* Haven't lost any bits, but casting to long requires extra
397 * care (see comment above).
398 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000399 if (x <= (unsigned long)LONG_MAX) {
400 res = (long)x * sign;
401 }
402 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
403 res = LONG_MIN;
404 }
405 else {
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000406 *overflow = sign;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000407 /* res is already set to -1 */
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000408 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000409 }
410 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000411 if (do_decref) {
412 Py_DECREF(vv);
413 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000414 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000415}
416
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000417long
418PyLong_AsLong(PyObject *obj)
419{
420 int overflow;
421 long result = PyLong_AsLongAndOverflow(obj, &overflow);
422 if (overflow) {
423 /* XXX: could be cute and give a different
424 message for overflow == -1 */
425 PyErr_SetString(PyExc_OverflowError,
426 "Python int too large to convert to C long");
427 }
428 return result;
429}
430
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000431/* Get a Py_ssize_t from a long int object.
432 Returns -1 and sets an error condition if overflow occurs. */
433
434Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000435PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000436 register PyLongObject *v;
437 size_t x, prev;
438 Py_ssize_t i;
439 int sign;
440
441 if (vv == NULL || !PyLong_Check(vv)) {
442 PyErr_BadInternalCall();
443 return -1;
444 }
445 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000446 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000447 switch (i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000448 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +0000449 case 0: return 0;
450 case 1: return v->ob_digit[0];
451 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000452 sign = 1;
453 x = 0;
454 if (i < 0) {
455 sign = -1;
456 i = -(i);
457 }
458 while (--i >= 0) {
459 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000460 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000461 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000462 goto overflow;
463 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000464 /* Haven't lost any bits, but casting to a signed type requires
465 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000466 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000467 if (x <= (size_t)PY_SSIZE_T_MAX) {
468 return (Py_ssize_t)x * sign;
469 }
470 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
471 return PY_SSIZE_T_MIN;
472 }
473 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000474
475 overflow:
476 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000477 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000478 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000479}
480
Guido van Rossumd8c80482002-08-13 00:24:58 +0000481/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000482 Returns -1 and sets an error condition if overflow occurs. */
483
484unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000485PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000486{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000488 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000489 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000490
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000491 if (vv == NULL || !PyLong_Check(vv)) {
492 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000493 return (unsigned long) -1;
494 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000495 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000496 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000497 x = 0;
498 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000500 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000501 return (unsigned long) -1;
502 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000503 switch (i) {
504 case 0: return 0;
505 case 1: return v->ob_digit[0];
506 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000507 while (--i >= 0) {
508 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000509 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000510 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000511 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000512 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000513 return (unsigned long) -1;
514 }
515 }
516 return x;
517}
518
519/* Get a C unsigned long int from a long int object.
520 Returns -1 and sets an error condition if overflow occurs. */
521
522size_t
523PyLong_AsSize_t(PyObject *vv)
524{
525 register PyLongObject *v;
526 size_t x, prev;
527 Py_ssize_t i;
528
529 if (vv == NULL || !PyLong_Check(vv)) {
530 PyErr_BadInternalCall();
531 return (unsigned long) -1;
532 }
533 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000534 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000535 x = 0;
536 if (i < 0) {
537 PyErr_SetString(PyExc_OverflowError,
538 "can't convert negative value to size_t");
539 return (size_t) -1;
540 }
541 switch (i) {
542 case 0: return 0;
543 case 1: return v->ob_digit[0];
544 }
545 while (--i >= 0) {
546 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000547 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000548 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000549 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000550 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000551 return (unsigned long) -1;
552 }
553 }
554 return x;
555}
556
Thomas Hellera4ea6032003-04-17 18:55:45 +0000557/* Get a C unsigned long int from a long int object, ignoring the high bits.
558 Returns -1 and sets an error condition if an error occurs. */
559
Guido van Rossumddefaf32007-01-14 03:31:43 +0000560static unsigned long
561_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000562{
563 register PyLongObject *v;
564 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000565 Py_ssize_t i;
566 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000567
568 if (vv == NULL || !PyLong_Check(vv)) {
569 PyErr_BadInternalCall();
570 return (unsigned long) -1;
571 }
572 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000573 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000574 switch (i) {
575 case 0: return 0;
576 case 1: return v->ob_digit[0];
577 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000578 sign = 1;
579 x = 0;
580 if (i < 0) {
581 sign = -1;
582 i = -i;
583 }
584 while (--i >= 0) {
Mark Dickinson24f57852009-09-28 17:54:52 +0000585 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000586 }
587 return x * sign;
588}
589
Guido van Rossumddefaf32007-01-14 03:31:43 +0000590unsigned long
591PyLong_AsUnsignedLongMask(register PyObject *op)
592{
593 PyNumberMethods *nb;
594 PyLongObject *lo;
595 unsigned long val;
596
597 if (op && PyLong_Check(op))
598 return _PyLong_AsUnsignedLongMask(op);
599
600 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
601 nb->nb_int == NULL) {
602 PyErr_SetString(PyExc_TypeError, "an integer is required");
603 return (unsigned long)-1;
604 }
605
606 lo = (PyLongObject*) (*nb->nb_int) (op);
607 if (lo == NULL)
608 return (unsigned long)-1;
609 if (PyLong_Check(lo)) {
610 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
611 Py_DECREF(lo);
612 if (PyErr_Occurred())
613 return (unsigned long)-1;
614 return val;
615 }
616 else
617 {
618 Py_DECREF(lo);
619 PyErr_SetString(PyExc_TypeError,
620 "nb_int should return int object");
621 return (unsigned long)-1;
622 }
623}
624
Tim Peters5b8132f2003-01-31 15:52:05 +0000625int
626_PyLong_Sign(PyObject *vv)
627{
628 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000629
630 assert(v != NULL);
631 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000632
Christian Heimes90aa7642007-12-19 02:45:37 +0000633 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000634}
635
Tim Petersbaefd9e2003-01-28 20:37:45 +0000636size_t
637_PyLong_NumBits(PyObject *vv)
638{
639 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000640 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000641 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000642
643 assert(v != NULL);
644 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000645 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000646 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
647 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000648 digit msd = v->ob_digit[ndigits - 1];
649
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000650 result = (ndigits - 1) * PyLong_SHIFT;
651 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000652 goto Overflow;
653 do {
654 ++result;
655 if (result == 0)
656 goto Overflow;
657 msd >>= 1;
658 } while (msd);
659 }
660 return result;
661
662Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000663 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000664 "to express in a platform size_t");
665 return (size_t)-1;
666}
667
Tim Peters2a9b3672001-06-11 21:23:58 +0000668PyObject *
669_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
670 int little_endian, int is_signed)
671{
672 const unsigned char* pstartbyte;/* LSB of bytes */
673 int incr; /* direction to move pstartbyte */
674 const unsigned char* pendbyte; /* MSB of bytes */
675 size_t numsignificantbytes; /* number of bytes that matter */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000676 Py_ssize_t ndigits; /* number of Python long digits */
Tim Peters2a9b3672001-06-11 21:23:58 +0000677 PyLongObject* v; /* result */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000678 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000679
680 if (n == 0)
681 return PyLong_FromLong(0L);
682
683 if (little_endian) {
684 pstartbyte = bytes;
685 pendbyte = bytes + n - 1;
686 incr = 1;
687 }
688 else {
689 pstartbyte = bytes + n - 1;
690 pendbyte = bytes;
691 incr = -1;
692 }
693
694 if (is_signed)
695 is_signed = *pendbyte >= 0x80;
696
697 /* Compute numsignificantbytes. This consists of finding the most
698 significant byte. Leading 0 bytes are insignficant if the number
699 is positive, and leading 0xff bytes if negative. */
700 {
701 size_t i;
702 const unsigned char* p = pendbyte;
703 const int pincr = -incr; /* search MSB to LSB */
704 const unsigned char insignficant = is_signed ? 0xff : 0x00;
705
706 for (i = 0; i < n; ++i, p += pincr) {
707 if (*p != insignficant)
708 break;
709 }
710 numsignificantbytes = n - i;
711 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
712 actually has 2 significant bytes. OTOH, 0xff0001 ==
713 -0x00ffff, so we wouldn't *need* to bump it there; but we
714 do for 0xffff = -0x0001. To be safe without bothering to
715 check every case, bump it regardless. */
716 if (is_signed && numsignificantbytes < n)
717 ++numsignificantbytes;
718 }
719
720 /* How many Python long digits do we need? We have
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000721 8*numsignificantbytes bits, and each Python long digit has
722 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
723 /* catch overflow before it happens */
724 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
725 PyErr_SetString(PyExc_OverflowError,
726 "byte array too long to convert to int");
727 return NULL;
728 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000729 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000730 v = _PyLong_New(ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000731 if (v == NULL)
732 return NULL;
733
734 /* Copy the bits over. The tricky parts are computing 2's-comp on
735 the fly for signed numbers, and dealing with the mismatch between
736 8-bit bytes and (probably) 15-bit Python digits.*/
737 {
738 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000739 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000740 twodigits accum = 0; /* sliding register */
741 unsigned int accumbits = 0; /* number of bits in accum */
742 const unsigned char* p = pstartbyte;
743
744 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000745 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000746 /* Compute correction for 2's comp, if needed. */
747 if (is_signed) {
748 thisbyte = (0xff ^ thisbyte) + carry;
749 carry = thisbyte >> 8;
750 thisbyte &= 0xff;
751 }
752 /* Because we're going LSB to MSB, thisbyte is
753 more significant than what's already in accum,
754 so needs to be prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000755 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000756 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000757 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000758 /* There's enough to fill a Python digit. */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000759 assert(idigit < ndigits);
760 v->ob_digit[idigit] = (digit)(accum &
761 PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000762 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000763 accum >>= PyLong_SHIFT;
764 accumbits -= PyLong_SHIFT;
765 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000766 }
767 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000768 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000769 if (accumbits) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000770 assert(idigit < ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000771 v->ob_digit[idigit] = (digit)accum;
772 ++idigit;
773 }
774 }
775
Christian Heimes90aa7642007-12-19 02:45:37 +0000776 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000777 return (PyObject *)long_normalize(v);
778}
779
780int
781_PyLong_AsByteArray(PyLongObject* v,
782 unsigned char* bytes, size_t n,
783 int little_endian, int is_signed)
784{
Mark Dickinson17e55872009-01-24 15:56:57 +0000785 Py_ssize_t i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000786 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000787 twodigits accum; /* sliding register */
788 unsigned int accumbits; /* # bits in accum */
789 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
Mark Dickinson1e2d8702009-01-25 22:25:06 +0000790 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000791 size_t j; /* # bytes filled */
792 unsigned char* p; /* pointer to next byte in bytes */
793 int pincr; /* direction to move p */
794
795 assert(v != NULL && PyLong_Check(v));
796
Christian Heimes90aa7642007-12-19 02:45:37 +0000797 if (Py_SIZE(v) < 0) {
798 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000799 if (!is_signed) {
Mark Dickinson21776072009-02-10 16:13:25 +0000800 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000801 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000802 return -1;
803 }
804 do_twos_comp = 1;
805 }
806 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000807 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000808 do_twos_comp = 0;
809 }
810
811 if (little_endian) {
812 p = bytes;
813 pincr = 1;
814 }
815 else {
816 p = bytes + n - 1;
817 pincr = -1;
818 }
819
Tim Peters898cf852001-06-13 20:50:08 +0000820 /* Copy over all the Python digits.
821 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000822 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000823 normalized. */
824 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000825 j = 0;
826 accum = 0;
827 accumbits = 0;
828 carry = do_twos_comp ? 1 : 0;
829 for (i = 0; i < ndigits; ++i) {
Mark Dickinson17e55872009-01-24 15:56:57 +0000830 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000831 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000832 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
833 carry = thisdigit >> PyLong_SHIFT;
834 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000835 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000836 /* Because we're going LSB to MSB, thisdigit is more
837 significant than what's already in accum, so needs to be
838 prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000839 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000840
Tim Petersede05092001-06-14 08:53:38 +0000841 /* The most-significant digit may be (probably is) at least
842 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000843 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000844 /* Count # of sign bits -- they needn't be stored,
845 * although for signed conversion we need later to
Mark Dickinson17e55872009-01-24 15:56:57 +0000846 * make sure at least one sign bit gets stored. */
847 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
848 thisdigit;
849 while (s != 0) {
850 s >>= 1;
851 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000852 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000853 }
Mark Dickinson17e55872009-01-24 15:56:57 +0000854 else
855 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000856
Tim Peters2a9b3672001-06-11 21:23:58 +0000857 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000858 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000859 if (j >= n)
860 goto Overflow;
861 ++j;
862 *p = (unsigned char)(accum & 0xff);
863 p += pincr;
864 accumbits -= 8;
865 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000866 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000867 }
868
869 /* Store the straggler (if any). */
870 assert(accumbits < 8);
871 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000872 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000873 if (j >= n)
874 goto Overflow;
875 ++j;
876 if (do_twos_comp) {
877 /* Fill leading bits of the byte with sign bits
878 (appropriately pretending that the long had an
879 infinite supply of sign bits). */
880 accum |= (~(twodigits)0) << accumbits;
881 }
882 *p = (unsigned char)(accum & 0xff);
883 p += pincr;
884 }
Tim Peters05607ad2001-06-13 21:01:27 +0000885 else if (j == n && n > 0 && is_signed) {
886 /* The main loop filled the byte array exactly, so the code
887 just above didn't get to ensure there's a sign bit, and the
888 loop below wouldn't add one either. Make sure a sign bit
889 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000890 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000891 int sign_bit_set = msb >= 0x80;
892 assert(accumbits == 0);
893 if (sign_bit_set == do_twos_comp)
894 return 0;
895 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000896 goto Overflow;
897 }
Tim Peters05607ad2001-06-13 21:01:27 +0000898
899 /* Fill remaining bytes with copies of the sign bit. */
900 {
901 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
902 for ( ; j < n; ++j, p += pincr)
903 *p = signbyte;
904 }
905
Tim Peters2a9b3672001-06-11 21:23:58 +0000906 return 0;
907
908Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000909 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000910 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000911
Tim Peters2a9b3672001-06-11 21:23:58 +0000912}
913
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000914double
915_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
916{
917/* NBITS_WANTED should be > the number of bits in a double's precision,
918 but small enough so that 2**NBITS_WANTED is within the normal double
919 range. nbitsneeded is set to 1 less than that because the most-significant
920 Python digit contains at least 1 significant bit, but we don't want to
921 bother counting them (catering to the worst case cheaply).
922
923 57 is one more than VAX-D double precision; I (Tim) don't know of a double
924 format with more precision than that; it's 1 larger so that we add in at
925 least one round bit to stand in for the ignored least-significant bits.
926*/
927#define NBITS_WANTED 57
928 PyLongObject *v;
929 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000930 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000931 Py_ssize_t i;
932 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000933 int nbitsneeded;
934
935 if (vv == NULL || !PyLong_Check(vv)) {
936 PyErr_BadInternalCall();
937 return -1;
938 }
939 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000940 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000941 sign = 1;
942 if (i < 0) {
943 sign = -1;
944 i = -(i);
945 }
946 else if (i == 0) {
947 *exponent = 0;
948 return 0.0;
949 }
950 --i;
951 x = (double)v->ob_digit[i];
952 nbitsneeded = NBITS_WANTED - 1;
953 /* Invariant: i Python digits remain unaccounted for. */
954 while (i > 0 && nbitsneeded > 0) {
955 --i;
956 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000957 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000958 }
959 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000960 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000961 *exponent = i;
962 assert(x > 0.0);
963 return x * sign;
964#undef NBITS_WANTED
965}
966
Mark Dickinsonc6300392009-04-20 21:38:00 +0000967/* Get a C double from a long int object. Rounds to the nearest double,
968 using the round-half-to-even rule in the case of a tie. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000969
970double
Tim Peters9f688bf2000-07-07 15:53:28 +0000971PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000972{
Mark Dickinsonc6300392009-04-20 21:38:00 +0000973 PyLongObject *v = (PyLongObject *)vv;
974 Py_ssize_t rnd_digit, rnd_bit, m, n;
975 digit lsb, *d;
976 int round_up = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000977 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000978
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000979 if (vv == NULL || !PyLong_Check(vv)) {
980 PyErr_BadInternalCall();
Tim Peters9fffa3e2001-09-04 05:14:19 +0000981 return -1.0;
Mark Dickinsonc6300392009-04-20 21:38:00 +0000982 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000983
Mark Dickinsonc6300392009-04-20 21:38:00 +0000984 /* Notes on the method: for simplicity, assume v is positive and >=
985 2**DBL_MANT_DIG. (For negative v we just ignore the sign until the
986 end; for small v no rounding is necessary.) Write n for the number
987 of bits in v, so that 2**(n-1) <= v < 2**n, and n > DBL_MANT_DIG.
988
989 Some terminology: the *rounding bit* of v is the 1st bit of v that
990 will be rounded away (bit n - DBL_MANT_DIG - 1); the *parity bit*
991 is the bit immediately above. The round-half-to-even rule says
992 that we round up if the rounding bit is set, unless v is exactly
993 halfway between two floats and the parity bit is zero.
994
995 Write d[0] ... d[m] for the digits of v, least to most significant.
996 Let rnd_bit be the index of the rounding bit, and rnd_digit the
997 index of the PyLong digit containing the rounding bit. Then the
998 bits of the digit d[rnd_digit] look something like:
999
1000 rounding bit
1001 |
1002 v
1003 msb -> sssssrttttttttt <- lsb
1004 ^
1005 |
1006 parity bit
1007
1008 where 's' represents a 'significant bit' that will be included in
1009 the mantissa of the result, 'r' is the rounding bit, and 't'
1010 represents a 'trailing bit' following the rounding bit. Note that
1011 if the rounding bit is at the top of d[rnd_digit] then the parity
1012 bit will be the lsb of d[rnd_digit+1]. If we set
1013
1014 lsb = 1 << (rnd_bit % PyLong_SHIFT)
1015
1016 then d[rnd_digit] & (PyLong_BASE - 2*lsb) selects just the
1017 significant bits of d[rnd_digit], d[rnd_digit] & (lsb-1) gets the
1018 trailing bits, and d[rnd_digit] & lsb gives the rounding bit.
1019
1020 We initialize the double x to the integer given by digits
1021 d[rnd_digit:m-1], but with the rounding bit and trailing bits of
1022 d[rnd_digit] masked out. So the value of x comes from the top
1023 DBL_MANT_DIG bits of v, multiplied by 2*lsb. Note that in the loop
1024 that produces x, all floating-point operations are exact (assuming
1025 that FLT_RADIX==2). Now if we're rounding down, the value we want
1026 to return is simply
1027
1028 x * 2**(PyLong_SHIFT * rnd_digit).
1029
1030 and if we're rounding up, it's
1031
1032 (x + 2*lsb) * 2**(PyLong_SHIFT * rnd_digit).
1033
1034 Under the round-half-to-even rule, we round up if, and only
1035 if, the rounding bit is set *and* at least one of the
1036 following three conditions is satisfied:
1037
1038 (1) the parity bit is set, or
1039 (2) at least one of the trailing bits of d[rnd_digit] is set, or
1040 (3) at least one of the digits d[i], 0 <= i < rnd_digit
1041 is nonzero.
1042
1043 Finally, we have to worry about overflow. If v >= 2**DBL_MAX_EXP,
1044 or equivalently n > DBL_MAX_EXP, then overflow occurs. If v <
1045 2**DBL_MAX_EXP then we're usually safe, but there's a corner case
1046 to consider: if v is very close to 2**DBL_MAX_EXP then it's
1047 possible that v is rounded up to exactly 2**DBL_MAX_EXP, and then
1048 again overflow occurs.
1049 */
1050
1051 if (Py_SIZE(v) == 0)
1052 return 0.0;
1053 m = ABS(Py_SIZE(v)) - 1;
1054 d = v->ob_digit;
1055 assert(d[m]); /* v should be normalized */
1056
1057 /* fast path for case where 0 < abs(v) < 2**DBL_MANT_DIG */
1058 if (m < DBL_MANT_DIG / PyLong_SHIFT ||
1059 (m == DBL_MANT_DIG / PyLong_SHIFT &&
1060 d[m] < (digit)1 << DBL_MANT_DIG%PyLong_SHIFT)) {
1061 x = d[m];
1062 while (--m >= 0)
1063 x = x*PyLong_BASE + d[m];
1064 return Py_SIZE(v) < 0 ? -x : x;
1065 }
1066
1067 /* if m is huge then overflow immediately; otherwise, compute the
1068 number of bits n in v. The condition below implies n (= #bits) >=
1069 m * PyLong_SHIFT + 1 > DBL_MAX_EXP, hence v >= 2**DBL_MAX_EXP. */
1070 if (m > (DBL_MAX_EXP-1)/PyLong_SHIFT)
1071 goto overflow;
1072 n = m * PyLong_SHIFT + bits_in_digit(d[m]);
1073 if (n > DBL_MAX_EXP)
1074 goto overflow;
1075
1076 /* find location of rounding bit */
1077 assert(n > DBL_MANT_DIG); /* dealt with |v| < 2**DBL_MANT_DIG above */
1078 rnd_bit = n - DBL_MANT_DIG - 1;
1079 rnd_digit = rnd_bit/PyLong_SHIFT;
1080 lsb = (digit)1 << (rnd_bit%PyLong_SHIFT);
1081
1082 /* Get top DBL_MANT_DIG bits of v. Assumes PyLong_SHIFT <
1083 DBL_MANT_DIG, so we'll need bits from at least 2 digits of v. */
1084 x = d[m];
1085 assert(m > rnd_digit);
1086 while (--m > rnd_digit)
1087 x = x*PyLong_BASE + d[m];
1088 x = x*PyLong_BASE + (d[m] & (PyLong_BASE-2*lsb));
1089
1090 /* decide whether to round up, using round-half-to-even */
1091 assert(m == rnd_digit);
1092 if (d[m] & lsb) { /* if (rounding bit is set) */
1093 digit parity_bit;
1094 if (lsb == PyLong_BASE/2)
1095 parity_bit = d[m+1] & 1;
1096 else
1097 parity_bit = d[m] & 2*lsb;
1098 if (parity_bit)
1099 round_up = 1;
1100 else if (d[m] & (lsb-1))
1101 round_up = 1;
1102 else {
1103 while (--m >= 0) {
1104 if (d[m]) {
1105 round_up = 1;
1106 break;
1107 }
1108 }
1109 }
1110 }
1111
1112 /* and round up if necessary */
1113 if (round_up) {
1114 x += 2*lsb;
1115 if (n == DBL_MAX_EXP &&
1116 x == ldexp((double)(2*lsb), DBL_MANT_DIG)) {
1117 /* overflow corner case */
1118 goto overflow;
1119 }
1120 }
1121
1122 /* shift, adjust for sign, and return */
1123 x = ldexp(x, rnd_digit*PyLong_SHIFT);
1124 return Py_SIZE(v) < 0 ? -x : x;
1125
1126 overflow:
Tim Peters9fffa3e2001-09-04 05:14:19 +00001127 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +00001128 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +00001129 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001130}
1131
Guido van Rossum78694d91998-09-18 14:14:13 +00001132/* Create a new long (or int) object from a C pointer */
1133
1134PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001135PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001136{
Tim Peters70128a12001-06-16 08:48:40 +00001137#ifndef HAVE_LONG_LONG
1138# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1139#endif
1140#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001141# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001142#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +00001143 /* special-case null pointer */
1144 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +00001145 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001146 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +00001147
Guido van Rossum78694d91998-09-18 14:14:13 +00001148}
1149
1150/* Get a C pointer from a long object (or an int object in some cases) */
1151
1152void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001153PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001154{
1155 /* This function will allow int or long objects. If vv is neither,
1156 then the PyLong_AsLong*() functions will raise the exception:
1157 PyExc_SystemError, "bad argument to internal function"
1158 */
Tim Peters70128a12001-06-16 08:48:40 +00001159#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001160 long x;
1161
Guido van Rossumddefaf32007-01-14 03:31:43 +00001162 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001163 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001164 else
1165 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001166#else
Tim Peters70128a12001-06-16 08:48:40 +00001167
1168#ifndef HAVE_LONG_LONG
1169# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1170#endif
1171#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001172# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001173#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001174 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001175
Guido van Rossumddefaf32007-01-14 03:31:43 +00001176 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001177 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001178 else
1179 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001180
1181#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001182
1183 if (x == -1 && PyErr_Occurred())
1184 return NULL;
1185 return (void *)x;
1186}
1187
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001188#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001189
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001190/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001191 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001192 */
1193
Tim Peterscf37dfc2001-06-14 18:42:50 +00001194#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001195
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001196/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001197
1198PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001199PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001200{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001201 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +00001202 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001203 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1204 int ndigits = 0;
1205 int negative = 0;
1206
Guido van Rossumddefaf32007-01-14 03:31:43 +00001207 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001208 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +00001209 /* avoid signed overflow on negation; see comments
1210 in PyLong_FromLong above. */
1211 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001212 negative = 1;
1213 }
Christian Heimesdae2a892008-04-19 00:55:37 +00001214 else {
1215 abs_ival = (unsigned PY_LONG_LONG)ival;
1216 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001217
1218 /* Count the number of Python digits.
1219 We used to pick 5 ("big enough for anything"), but that's a
1220 waste of time and space given that 5*15 = 75 bits are rarely
1221 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001222 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001223 while (t) {
1224 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001225 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001226 }
1227 v = _PyLong_New(ndigits);
1228 if (v != NULL) {
1229 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001230 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001231 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001232 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001233 *p++ = (digit)(t & PyLong_MASK);
1234 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001235 }
1236 }
1237 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001238}
1239
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001240/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001241
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001242PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001243PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001244{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001245 PyLongObject *v;
1246 unsigned PY_LONG_LONG t;
1247 int ndigits = 0;
1248
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001249 if (ival < PyLong_BASE)
Mark Dickinson50b2b6e2008-12-05 17:14:29 +00001250 return PyLong_FromLong((long)ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001251 /* Count the number of Python digits. */
1252 t = (unsigned PY_LONG_LONG)ival;
1253 while (t) {
1254 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001255 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001256 }
1257 v = _PyLong_New(ndigits);
1258 if (v != NULL) {
1259 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001260 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001261 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001262 *p++ = (digit)(ival & PyLong_MASK);
1263 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001264 }
1265 }
1266 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001267}
1268
Martin v. Löwis18e16552006-02-15 17:27:45 +00001269/* Create a new long int object from a C Py_ssize_t. */
1270
1271PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001272PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001273{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001274 PyLongObject *v;
1275 size_t abs_ival;
1276 size_t t; /* unsigned so >> doesn't propagate sign bit */
1277 int ndigits = 0;
1278 int negative = 0;
1279
1280 CHECK_SMALL_INT(ival);
1281 if (ival < 0) {
1282 /* avoid signed overflow when ival = SIZE_T_MIN */
1283 abs_ival = (size_t)(-1-ival)+1;
1284 negative = 1;
1285 }
1286 else {
1287 abs_ival = (size_t)ival;
1288 }
1289
1290 /* Count the number of Python digits. */
1291 t = abs_ival;
1292 while (t) {
1293 ++ndigits;
1294 t >>= PyLong_SHIFT;
1295 }
1296 v = _PyLong_New(ndigits);
1297 if (v != NULL) {
1298 digit *p = v->ob_digit;
1299 Py_SIZE(v) = negative ? -ndigits : ndigits;
1300 t = abs_ival;
1301 while (t) {
1302 *p++ = (digit)(t & PyLong_MASK);
1303 t >>= PyLong_SHIFT;
1304 }
1305 }
1306 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001307}
1308
1309/* Create a new long int object from a C size_t. */
1310
1311PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001312PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001313{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001314 PyLongObject *v;
1315 size_t t;
1316 int ndigits = 0;
1317
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001318 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001319 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001320 /* Count the number of Python digits. */
1321 t = ival;
1322 while (t) {
1323 ++ndigits;
1324 t >>= PyLong_SHIFT;
1325 }
1326 v = _PyLong_New(ndigits);
1327 if (v != NULL) {
1328 digit *p = v->ob_digit;
1329 Py_SIZE(v) = ndigits;
1330 while (ival) {
1331 *p++ = (digit)(ival & PyLong_MASK);
1332 ival >>= PyLong_SHIFT;
1333 }
1334 }
1335 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001336}
1337
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001338/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001339 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001340
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001341PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001342PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001343{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001344 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001345 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001346 int one = 1;
1347 int res;
1348
Tim Petersd38b1c72001-09-30 05:09:37 +00001349 if (vv == NULL) {
1350 PyErr_BadInternalCall();
1351 return -1;
1352 }
1353 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001354 PyNumberMethods *nb;
1355 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001356 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1357 nb->nb_int == NULL) {
1358 PyErr_SetString(PyExc_TypeError, "an integer is required");
1359 return -1;
1360 }
1361 io = (*nb->nb_int) (vv);
1362 if (io == NULL)
1363 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001364 if (PyLong_Check(io)) {
1365 bytes = PyLong_AsLongLong(io);
1366 Py_DECREF(io);
1367 return bytes;
1368 }
1369 Py_DECREF(io);
1370 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001371 return -1;
1372 }
1373
Guido van Rossumddefaf32007-01-14 03:31:43 +00001374 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001375 switch(Py_SIZE(v)) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00001376 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00001377 case 0: return 0;
1378 case 1: return v->ob_digit[0];
1379 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001380 res = _PyLong_AsByteArray(
1381 (PyLongObject *)vv, (unsigned char *)&bytes,
1382 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001383
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001384 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001385 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001386 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001387 else
1388 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001389}
1390
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001391/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001392 Return -1 and set an error if overflow occurs. */
1393
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001394unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001395PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001396{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001397 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001398 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001399 int one = 1;
1400 int res;
1401
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001402 if (vv == NULL || !PyLong_Check(vv)) {
1403 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001404 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001405 }
1406
Guido van Rossumddefaf32007-01-14 03:31:43 +00001407 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001408 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001409 case 0: return 0;
1410 case 1: return v->ob_digit[0];
1411 }
1412
Tim Petersd1a7da62001-06-13 00:35:57 +00001413 res = _PyLong_AsByteArray(
1414 (PyLongObject *)vv, (unsigned char *)&bytes,
1415 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001416
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001417 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001418 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001419 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001420 else
1421 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001422}
Tim Petersd1a7da62001-06-13 00:35:57 +00001423
Thomas Hellera4ea6032003-04-17 18:55:45 +00001424/* Get a C unsigned long int from a long int object, ignoring the high bits.
1425 Returns -1 and sets an error condition if an error occurs. */
1426
Guido van Rossumddefaf32007-01-14 03:31:43 +00001427static unsigned PY_LONG_LONG
1428_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001429{
1430 register PyLongObject *v;
1431 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001432 Py_ssize_t i;
1433 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001434
1435 if (vv == NULL || !PyLong_Check(vv)) {
1436 PyErr_BadInternalCall();
1437 return (unsigned long) -1;
1438 }
1439 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001440 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001441 case 0: return 0;
1442 case 1: return v->ob_digit[0];
1443 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001444 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001445 sign = 1;
1446 x = 0;
1447 if (i < 0) {
1448 sign = -1;
1449 i = -i;
1450 }
1451 while (--i >= 0) {
Mark Dickinson24f57852009-09-28 17:54:52 +00001452 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001453 }
1454 return x * sign;
1455}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001456
1457unsigned PY_LONG_LONG
1458PyLong_AsUnsignedLongLongMask(register PyObject *op)
1459{
1460 PyNumberMethods *nb;
1461 PyLongObject *lo;
1462 unsigned PY_LONG_LONG val;
1463
1464 if (op && PyLong_Check(op))
1465 return _PyLong_AsUnsignedLongLongMask(op);
1466
1467 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1468 nb->nb_int == NULL) {
1469 PyErr_SetString(PyExc_TypeError, "an integer is required");
1470 return (unsigned PY_LONG_LONG)-1;
1471 }
1472
1473 lo = (PyLongObject*) (*nb->nb_int) (op);
1474 if (lo == NULL)
1475 return (unsigned PY_LONG_LONG)-1;
1476 if (PyLong_Check(lo)) {
1477 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1478 Py_DECREF(lo);
1479 if (PyErr_Occurred())
1480 return (unsigned PY_LONG_LONG)-1;
1481 return val;
1482 }
1483 else
1484 {
1485 Py_DECREF(lo);
1486 PyErr_SetString(PyExc_TypeError,
1487 "nb_int should return int object");
1488 return (unsigned PY_LONG_LONG)-1;
1489 }
1490}
Tim Petersd1a7da62001-06-13 00:35:57 +00001491#undef IS_LITTLE_ENDIAN
1492
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001493#endif /* HAVE_LONG_LONG */
1494
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001495#define CHECK_BINOP(v,w) \
1496 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001497 Py_INCREF(Py_NotImplemented); \
1498 return Py_NotImplemented; \
1499 }
1500
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001501/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1502 2**k if d is nonzero, else 0. */
1503
1504static const unsigned char BitLengthTable[32] = {
1505 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1506 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1507};
1508
1509static int
1510bits_in_digit(digit d)
1511{
1512 int d_bits = 0;
1513 while (d >= 32) {
1514 d_bits += 6;
1515 d >>= 6;
1516 }
1517 d_bits += (int)BitLengthTable[d];
1518 return d_bits;
1519}
1520
Tim Peters877a2122002-08-12 05:09:36 +00001521/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1522 * is modified in place, by adding y to it. Carries are propagated as far as
1523 * x[m-1], and the remaining carry (0 or 1) is returned.
1524 */
1525static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001526v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001527{
Mark Dickinson17e55872009-01-24 15:56:57 +00001528 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001529 digit carry = 0;
1530
1531 assert(m >= n);
1532 for (i = 0; i < n; ++i) {
1533 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001534 x[i] = carry & PyLong_MASK;
1535 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001536 assert((carry & 1) == carry);
1537 }
1538 for (; carry && i < m; ++i) {
1539 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001540 x[i] = carry & PyLong_MASK;
1541 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001542 assert((carry & 1) == carry);
1543 }
1544 return carry;
1545}
1546
1547/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1548 * is modified in place, by subtracting y from it. Borrows are propagated as
1549 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1550 */
1551static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001552v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001553{
Mark Dickinson17e55872009-01-24 15:56:57 +00001554 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001555 digit borrow = 0;
1556
1557 assert(m >= n);
1558 for (i = 0; i < n; ++i) {
1559 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001560 x[i] = borrow & PyLong_MASK;
1561 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001562 borrow &= 1; /* keep only 1 sign bit */
1563 }
1564 for (; borrow && i < m; ++i) {
1565 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001566 x[i] = borrow & PyLong_MASK;
1567 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001568 borrow &= 1;
1569 }
1570 return borrow;
1571}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001572
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001573/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1574 * result in z[0:m], and return the d bits shifted out of the top.
1575 */
1576static digit
1577v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001578{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001579 Py_ssize_t i;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001580 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001581
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001582 assert(0 <= d && d < PyLong_SHIFT);
1583 for (i=0; i < m; i++) {
1584 twodigits acc = (twodigits)a[i] << d | carry;
1585 z[i] = (digit)acc & PyLong_MASK;
1586 carry = (digit)(acc >> PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001587 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001588 return carry;
1589}
1590
1591/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1592 * result in z[0:m], and return the d bits shifted out of the bottom.
1593 */
1594static digit
1595v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1596{
1597 Py_ssize_t i;
1598 digit carry = 0;
1599 digit mask = ((digit)1 << d) - 1U;
1600
1601 assert(0 <= d && d < PyLong_SHIFT);
1602 for (i=m; i-- > 0;) {
1603 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1604 carry = (digit)acc & mask;
1605 z[i] = (digit)(acc >> d);
1606 }
1607 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001608}
1609
Tim Peters212e6142001-07-14 12:23:19 +00001610/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1611 in pout, and returning the remainder. pin and pout point at the LSD.
1612 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001613 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001614 immutable. */
1615
1616static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001617inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001618{
1619 twodigits rem = 0;
1620
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001621 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001622 pin += size;
1623 pout += size;
1624 while (--size >= 0) {
1625 digit hi;
Mark Dickinson24f57852009-09-28 17:54:52 +00001626 rem = (rem << PyLong_SHIFT) | *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001627 *--pout = hi = (digit)(rem / n);
Mark Dickinson17e55872009-01-24 15:56:57 +00001628 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001629 }
1630 return (digit)rem;
1631}
1632
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001633/* Divide a long integer by a digit, returning both the quotient
1634 (as function result) and the remainder (through *prem).
1635 The sign of a is ignored; n should not be zero. */
1636
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001637static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001638divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001639{
Christian Heimes90aa7642007-12-19 02:45:37 +00001640 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001641 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001642
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001643 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001644 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001645 if (z == NULL)
1646 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001647 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001648 return long_normalize(z);
1649}
1650
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001651/* Convert a long integer to a base 10 string. Returns a new non-shared
1652 string. (Return value is non-shared so that callers can modify the
1653 returned value if necessary.) */
1654
1655static PyObject *
1656long_to_decimal_string(PyObject *aa)
1657{
1658 PyLongObject *scratch, *a;
1659 PyObject *str;
1660 Py_ssize_t size, strlen, size_a, i, j;
1661 digit *pout, *pin, rem, tenpow;
1662 Py_UNICODE *p;
1663 int negative;
1664
1665 a = (PyLongObject *)aa;
1666 if (a == NULL || !PyLong_Check(a)) {
1667 PyErr_BadInternalCall();
1668 return NULL;
1669 }
1670 size_a = ABS(Py_SIZE(a));
1671 negative = Py_SIZE(a) < 0;
1672
1673 /* quick and dirty upper bound for the number of digits
1674 required to express a in base _PyLong_DECIMAL_BASE:
1675
1676 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1677
1678 But log2(a) < size_a * PyLong_SHIFT, and
1679 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1680 > 3 * _PyLong_DECIMAL_SHIFT
1681 */
1682 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1683 PyErr_SetString(PyExc_OverflowError,
1684 "long is too large to format");
1685 return NULL;
1686 }
1687 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1688 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1689 scratch = _PyLong_New(size);
1690 if (scratch == NULL)
1691 return NULL;
1692
1693 /* convert array of base _PyLong_BASE digits in pin to an array of
1694 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1695 Volume 2 (3rd edn), section 4.4, Method 1b). */
1696 pin = a->ob_digit;
1697 pout = scratch->ob_digit;
1698 size = 0;
1699 for (i = size_a; --i >= 0; ) {
1700 digit hi = pin[i];
1701 for (j = 0; j < size; j++) {
1702 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
Mark Dickinson741984d2009-09-21 16:18:27 +00001703 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1704 pout[j] = (digit)(z - (twodigits)hi *
1705 _PyLong_DECIMAL_BASE);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001706 }
1707 while (hi) {
1708 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1709 hi /= _PyLong_DECIMAL_BASE;
1710 }
1711 /* check for keyboard interrupt */
1712 SIGCHECK({
1713 Py_DECREF(scratch);
1714 return NULL;
1715 })
1716 }
1717 /* pout should have at least one digit, so that the case when a = 0
1718 works correctly */
1719 if (size == 0)
1720 pout[size++] = 0;
1721
1722 /* calculate exact length of output string, and allocate */
1723 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1724 tenpow = 10;
1725 rem = pout[size-1];
1726 while (rem >= tenpow) {
1727 tenpow *= 10;
1728 strlen++;
1729 }
1730 str = PyUnicode_FromUnicode(NULL, strlen);
1731 if (str == NULL) {
1732 Py_DECREF(scratch);
1733 return NULL;
1734 }
1735
1736 /* fill the string right-to-left */
1737 p = PyUnicode_AS_UNICODE(str) + strlen;
1738 *p = '\0';
1739 /* pout[0] through pout[size-2] contribute exactly
1740 _PyLong_DECIMAL_SHIFT digits each */
1741 for (i=0; i < size - 1; i++) {
1742 rem = pout[i];
1743 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1744 *--p = '0' + rem % 10;
1745 rem /= 10;
1746 }
1747 }
1748 /* pout[size-1]: always produce at least one decimal digit */
1749 rem = pout[i];
1750 do {
1751 *--p = '0' + rem % 10;
1752 rem /= 10;
1753 } while (rem != 0);
1754
1755 /* and sign */
1756 if (negative)
1757 *--p = '-';
1758
1759 /* check we've counted correctly */
1760 assert(p == PyUnicode_AS_UNICODE(str));
1761 Py_DECREF(scratch);
1762 return (PyObject *)str;
1763}
1764
Mark Dickinsoncd068122009-09-18 14:53:08 +00001765/* Convert a long int object to a string, using a given conversion base,
1766 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001767 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001768
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001769PyObject *
1770_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001771{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001772 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001773 PyObject *str;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001774 Py_ssize_t i, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001775 Py_ssize_t size_a;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001776 Py_UNICODE *p, sign = '\0';
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001777 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001778
Mark Dickinsoncd068122009-09-18 14:53:08 +00001779 assert(base == 2 || base == 8 || base == 10 || base == 16);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001780 if (base == 10)
1781 return long_to_decimal_string((PyObject *)a);
1782
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001783 if (a == NULL || !PyLong_Check(a)) {
1784 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001785 return NULL;
1786 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001787 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001788
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001789 /* Compute a rough upper bound for the length of the string */
Mark Dickinsoncd068122009-09-18 14:53:08 +00001790 switch (base) {
1791 case 16:
1792 bits = 4;
1793 break;
1794 case 8:
1795 bits = 3;
1796 break;
1797 case 2:
1798 bits = 1;
1799 break;
1800 default:
1801 assert(0); /* shouldn't ever get here */
1802 bits = 0; /* to silence gcc warning */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001803 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001804 /* compute length of output string: allow 2 characters for prefix and
1805 1 for possible '-' sign. */
1806 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001807 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001808 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001809 return NULL;
1810 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001811 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1812 is safe from overflow */
1813 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001814 assert(sz >= 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001815 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001816 if (str == NULL)
1817 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001818 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001819 *p = '\0';
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001820 if (Py_SIZE(a) < 0)
1821 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001822
Christian Heimes90aa7642007-12-19 02:45:37 +00001823 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001824 *--p = '0';
1825 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001826 else {
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001827 /* JRH: special case for power-of-2 bases */
1828 twodigits accum = 0;
1829 int accumbits = 0; /* # of bits in accum */
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001830 for (i = 0; i < size_a; ++i) {
1831 accum |= (twodigits)a->ob_digit[i] << accumbits;
1832 accumbits += PyLong_SHIFT;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001833 assert(accumbits >= bits);
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001834 do {
Mark Dickinson1f7e18c2009-09-24 18:31:17 +00001835 Py_UNICODE cdigit;
1836 cdigit = (Py_UNICODE)(accum & (base - 1));
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001837 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1838 assert(p > PyUnicode_AS_UNICODE(str));
1839 *--p = cdigit;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001840 accumbits -= bits;
1841 accum >>= bits;
1842 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001843 }
1844 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001845
Mark Dickinsoncd068122009-09-18 14:53:08 +00001846 if (base == 16)
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001847 *--p = 'x';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001848 else if (base == 8)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001849 *--p = 'o';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001850 else /* (base == 2) */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001851 *--p = 'b';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001852 *--p = '0';
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001853 if (sign)
1854 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001855 if (p != PyUnicode_AS_UNICODE(str)) {
1856 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001857 assert(p > q);
1858 do {
1859 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001860 q--;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001861 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1862 PyUnicode_AS_UNICODE(str)))) {
Walter Dörwald1ab83302007-05-18 17:15:44 +00001863 Py_DECREF(str);
1864 return NULL;
1865 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001866 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001867 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001868}
1869
Thomas Wouters477c8d52006-05-27 19:21:47 +00001870/* Table of digit values for 8-bit string -> integer conversion.
1871 * '0' maps to 0, ..., '9' maps to 9.
1872 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1873 * All other indices map to 37.
1874 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001875 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001876 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001877unsigned char _PyLong_DigitValue[256] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001878 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1881 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1882 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1883 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1884 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1885 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1894};
1895
1896/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001897 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1898 * non-digit (which may be *str!). A normalized long is returned.
1899 * The point to this routine is that it takes time linear in the number of
1900 * string characters.
1901 */
1902static PyLongObject *
1903long_from_binary_base(char **str, int base)
1904{
1905 char *p = *str;
1906 char *start = p;
1907 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001908 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001909 PyLongObject *z;
1910 twodigits accum;
1911 int bits_in_accum;
1912 digit *pdigit;
1913
1914 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1915 n = base;
1916 for (bits_per_char = -1; n; ++bits_per_char)
1917 n >>= 1;
1918 /* n <- total # of bits needed, while setting p to end-of-string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001919 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001920 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001921 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001922 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1923 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001924 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001925 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001926 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001927 return NULL;
1928 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001929 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001930 z = _PyLong_New(n);
1931 if (z == NULL)
1932 return NULL;
1933 /* Read string from right, and fill in long from left; i.e.,
1934 * from least to most significant in both.
1935 */
1936 accum = 0;
1937 bits_in_accum = 0;
1938 pdigit = z->ob_digit;
1939 while (--p >= start) {
Raymond Hettinger35631532009-01-09 03:58:09 +00001940 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001941 assert(k >= 0 && k < base);
Mark Dickinson17e55872009-01-24 15:56:57 +00001942 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001943 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001944 if (bits_in_accum >= PyLong_SHIFT) {
1945 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinson17e55872009-01-24 15:56:57 +00001946 assert(pdigit - z->ob_digit <= n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001947 accum >>= PyLong_SHIFT;
1948 bits_in_accum -= PyLong_SHIFT;
1949 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001950 }
1951 }
1952 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001953 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001954 *pdigit++ = (digit)accum;
Mark Dickinson17e55872009-01-24 15:56:57 +00001955 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001956 }
1957 while (pdigit - z->ob_digit < n)
1958 *pdigit++ = 0;
1959 return long_normalize(z);
1960}
1961
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001962PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001963PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001964{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001965 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001966 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001967 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001968 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001969 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001970
Guido van Rossum472c04f1996-12-05 21:57:21 +00001971 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001972 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001973 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001974 return NULL;
1975 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001976 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001977 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001978 if (*str == '+')
1979 ++str;
1980 else if (*str == '-') {
1981 ++str;
1982 sign = -1;
1983 }
1984 if (base == 0) {
1985 if (str[0] != '0')
1986 base = 10;
1987 else if (str[1] == 'x' || str[1] == 'X')
1988 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001989 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001990 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001991 else if (str[1] == 'b' || str[1] == 'B')
1992 base = 2;
1993 else {
1994 /* "old" (C-style) octal literal, now invalid.
1995 it might still be zero though */
1996 error_if_nonzero = 1;
1997 base = 10;
1998 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001999 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002000 if (str[0] == '0' &&
2001 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2002 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2003 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002005
Guido van Rossume6762971998-06-22 03:54:46 +00002006 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00002007 if ((base & (base - 1)) == 0)
2008 z = long_from_binary_base(&str, base);
2009 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002010/***
2011Binary bases can be converted in time linear in the number of digits, because
2012Python's representation base is binary. Other bases (including decimal!) use
2013the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002014
Thomas Wouters477c8d52006-05-27 19:21:47 +00002015First some math: the largest integer that can be expressed in N base-B digits
2016is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2017case number of Python digits needed to hold it is the smallest integer n s.t.
2018
2019 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2020 BASE**n >= B**N [taking logs to base BASE]
2021 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2022
2023The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2024this quickly. A Python long with that much space is reserved near the start,
2025and the result is computed into it.
2026
2027The input string is actually treated as being in base base**i (i.e., i digits
2028are processed at a time), where two more static arrays hold:
2029
2030 convwidth_base[base] = the largest integer i such that base**i <= BASE
2031 convmultmax_base[base] = base ** convwidth_base[base]
2032
2033The first of these is the largest i such that i consecutive input digits
2034must fit in a single Python digit. The second is effectively the input
2035base we're really using.
2036
2037Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2038convmultmax_base[base], the result is "simply"
2039
2040 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2041
2042where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002043
2044Error analysis: as above, the number of Python digits `n` needed is worst-
2045case
2046
2047 n >= N * log(B)/log(BASE)
2048
2049where `N` is the number of input digits in base `B`. This is computed via
2050
2051 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2052
2053below. Two numeric concerns are how much space this can waste, and whether
2054the computed result can be too small. To be concrete, assume BASE = 2**15,
2055which is the default (and it's unlikely anyone changes that).
2056
2057Waste isn't a problem: provided the first input digit isn't 0, the difference
2058between the worst-case input with N digits and the smallest input with N
2059digits is about a factor of B, but B is small compared to BASE so at most
2060one allocated Python digit can remain unused on that count. If
2061N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2062and adding 1 returns a result 1 larger than necessary. However, that can't
2063happen: whenever B is a power of 2, long_from_binary_base() is called
2064instead, and it's impossible for B**i to be an integer power of 2**15 when
2065B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2066an exact integer when B is not a power of 2, since B**i has a prime factor
2067other than 2 in that case, but (2**15)**j's only prime factor is 2).
2068
2069The computed result can be too small if the true value of N*log(B)/log(BASE)
2070is a little bit larger than an exact integer, but due to roundoff errors (in
2071computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2072yields a numeric result a little less than that integer. Unfortunately, "how
2073close can a transcendental function get to an integer over some range?"
2074questions are generally theoretically intractable. Computer analysis via
2075continued fractions is practical: expand log(B)/log(BASE) via continued
2076fractions, giving a sequence i/j of "the best" rational approximations. Then
2077j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2078we can get very close to being in trouble, but very rarely. For example,
207976573 is a denominator in one of the continued-fraction approximations to
2080log(10)/log(2**15), and indeed:
2081
2082 >>> log(10)/log(2**15)*76573
2083 16958.000000654003
2084
2085is very close to an integer. If we were working with IEEE single-precision,
2086rounding errors could kill us. Finding worst cases in IEEE double-precision
2087requires better-than-double-precision log() functions, and Tim didn't bother.
2088Instead the code checks to see whether the allocated space is enough as each
2089new Python digit is added, and copies the whole thing to a larger long if not.
2090This should happen extremely rarely, and in fact I don't have a test case
2091that triggers it(!). Instead the code was tested by artificially allocating
2092just 1 digit at the start, so that the copying code was exercised for every
2093digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002094***/
2095 register twodigits c; /* current input character */
2096 Py_ssize_t size_z;
2097 int i;
2098 int convwidth;
2099 twodigits convmultmax, convmult;
2100 digit *pz, *pzstop;
2101 char* scan;
2102
2103 static double log_base_BASE[37] = {0.0e0,};
2104 static int convwidth_base[37] = {0,};
2105 static twodigits convmultmax_base[37] = {0,};
2106
2107 if (log_base_BASE[base] == 0.0) {
2108 twodigits convmax = base;
2109 int i = 1;
2110
2111 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002112 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002113 for (;;) {
2114 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002115 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002116 break;
2117 convmax = next;
2118 ++i;
2119 }
2120 convmultmax_base[base] = convmax;
2121 assert(i > 0);
2122 convwidth_base[base] = i;
2123 }
2124
2125 /* Find length of the string of numeric characters. */
2126 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00002127 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002128 ++scan;
2129
2130 /* Create a long object that can contain the largest possible
2131 * integer with this base and length. Note that there's no
2132 * need to initialize z->ob_digit -- no slot is read up before
2133 * being stored into.
2134 */
2135 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002136 /* Uncomment next line to test exceedingly rare copy code */
2137 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002138 assert(size_z > 0);
2139 z = _PyLong_New(size_z);
2140 if (z == NULL)
2141 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002142 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002143
2144 /* `convwidth` consecutive input digits are treated as a single
2145 * digit in base `convmultmax`.
2146 */
2147 convwidth = convwidth_base[base];
2148 convmultmax = convmultmax_base[base];
2149
2150 /* Work ;-) */
2151 while (str < scan) {
2152 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00002153 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002154 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2155 c = (twodigits)(c * base +
Raymond Hettinger35631532009-01-09 03:58:09 +00002156 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002157 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002158 }
2159
2160 convmult = convmultmax;
2161 /* Calculate the shift only if we couldn't get
2162 * convwidth digits.
2163 */
2164 if (i != convwidth) {
2165 convmult = base;
2166 for ( ; i > 1; --i)
2167 convmult *= base;
2168 }
2169
2170 /* Multiply z by convmult, and add c. */
2171 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00002172 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002173 for (; pz < pzstop; ++pz) {
2174 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002175 *pz = (digit)(c & PyLong_MASK);
2176 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002177 }
2178 /* carry off the current end? */
2179 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002180 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00002181 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002182 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00002183 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002184 }
2185 else {
2186 PyLongObject *tmp;
2187 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002188 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002189 tmp = _PyLong_New(size_z + 1);
2190 if (tmp == NULL) {
2191 Py_DECREF(z);
2192 return NULL;
2193 }
2194 memcpy(tmp->ob_digit,
2195 z->ob_digit,
2196 sizeof(digit) * size_z);
2197 Py_DECREF(z);
2198 z = tmp;
2199 z->ob_digit[size_z] = (digit)c;
2200 ++size_z;
2201 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002202 }
Tim Petersbf2674b2003-02-02 07:51:32 +00002203 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002204 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00002205 if (z == NULL)
2206 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002207 if (error_if_nonzero) {
2208 /* reset the base to 0, else the exception message
2209 doesn't make too much sense */
2210 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00002211 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002212 goto onError;
2213 /* there might still be other problems, therefore base
2214 remains zero here for the same reason */
2215 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00002216 if (str == start)
2217 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002218 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00002219 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00002220 while (*str && isspace(Py_CHARMASK(*str)))
2221 str++;
2222 if (*str != '\0')
2223 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002224 if (pend)
2225 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00002226 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002227 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002228
2229 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002230 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002231 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002232 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002233 if (strobj == NULL)
2234 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002235 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002236 "invalid literal for int() with base %d: %R",
2237 base, strobj);
2238 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002239 return NULL;
2240}
2241
2242PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002243PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002244{
Walter Dörwald07e14762002-11-06 16:15:14 +00002245 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002246 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002247
Walter Dörwald07e14762002-11-06 16:15:14 +00002248 if (buffer == NULL)
2249 return NULL;
2250
2251 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2252 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002253 return NULL;
2254 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002255 result = PyLong_FromString(buffer, NULL, base);
2256 PyMem_FREE(buffer);
2257 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002258}
2259
Tim Peters9f688bf2000-07-07 15:53:28 +00002260/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002261static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002262 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002263static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002264
2265/* Long division with remainder, top-level routine */
2266
Guido van Rossume32e0141992-01-19 16:31:05 +00002267static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002268long_divrem(PyLongObject *a, PyLongObject *b,
2269 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002270{
Christian Heimes90aa7642007-12-19 02:45:37 +00002271 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002272 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002273
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002274 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002275 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002276 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002277 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002278 }
2279 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002280 (size_a == size_b &&
2281 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002282 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002283 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002284 if (*pdiv == NULL)
2285 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002286 Py_INCREF(a);
2287 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002288 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002289 }
2290 if (size_b == 1) {
2291 digit rem = 0;
2292 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002293 if (z == NULL)
2294 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002295 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002296 if (*prem == NULL) {
2297 Py_DECREF(z);
2298 return -1;
2299 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002300 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002301 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002302 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002303 if (z == NULL)
2304 return -1;
2305 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002306 /* Set the signs.
2307 The quotient z has the sign of a*b;
2308 the remainder r has the sign of a,
2309 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002310 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002311 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002312 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002313 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002314 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002315 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002316}
2317
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002318/* Unsigned long division with remainder -- the algorithm. The arguments v1
2319 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002320
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002321static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002322x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002323{
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002324 PyLongObject *v, *w, *a;
2325 Py_ssize_t i, k, size_v, size_w;
2326 int d;
2327 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2328 twodigits vv;
2329 sdigit zhi;
2330 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002331
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002332 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2333 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2334 handle the special case when the initial estimate q for a quotient
2335 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2336 that won't overflow a digit. */
2337
2338 /* allocate space; w will also be used to hold the final remainder */
2339 size_v = ABS(Py_SIZE(v1));
2340 size_w = ABS(Py_SIZE(w1));
2341 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2342 v = _PyLong_New(size_v+1);
2343 if (v == NULL) {
2344 *prem = NULL;
2345 return NULL;
2346 }
2347 w = _PyLong_New(size_w);
2348 if (w == NULL) {
2349 Py_DECREF(v);
2350 *prem = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002351 return NULL;
2352 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002353
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002354 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2355 shift v1 left by the same amount. Results go into w and v. */
2356 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2357 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2358 assert(carry == 0);
2359 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2360 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2361 v->ob_digit[size_v] = carry;
2362 size_v++;
2363 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002364
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002365 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2366 at most (and usually exactly) k = size_v - size_w digits. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002367 k = size_v - size_w;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002368 assert(k >= 0);
2369 a = _PyLong_New(k);
2370 if (a == NULL) {
2371 Py_DECREF(w);
2372 Py_DECREF(v);
2373 *prem = NULL;
2374 return NULL;
2375 }
2376 v0 = v->ob_digit;
2377 w0 = w->ob_digit;
2378 wm1 = w0[size_w-1];
2379 wm2 = w0[size_w-2];
2380 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2381 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2382 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002383
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002384 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002385 Py_DECREF(a);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002386 Py_DECREF(w);
2387 Py_DECREF(v);
2388 *prem = NULL;
2389 return NULL;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002390 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002391
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002392 /* estimate quotient digit q; may overestimate by 1 (rare) */
2393 vtop = vk[size_w];
2394 assert(vtop <= wm1);
2395 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2396 q = (digit)(vv / wm1);
2397 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2398 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2399 | vk[size_w-2])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002400 --q;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002401 r += wm1;
2402 if (r >= PyLong_BASE)
2403 break;
2404 }
2405 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002406
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002407 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2408 zhi = 0;
2409 for (i = 0; i < size_w; ++i) {
2410 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2411 -PyLong_BASE * q <= z < PyLong_BASE */
2412 z = (sdigit)vk[i] + zhi -
2413 (stwodigits)q * (stwodigits)w0[i];
2414 vk[i] = (digit)z & PyLong_MASK;
2415 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2416 z, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002417 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002418
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002419 /* add w back if q was too large (this branch taken rarely) */
2420 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2421 if ((sdigit)vtop + zhi < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002422 carry = 0;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002423 for (i = 0; i < size_w; ++i) {
2424 carry += vk[i] + w0[i];
2425 vk[i] = carry & PyLong_MASK;
2426 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002427 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002428 --q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002429 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002430
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002431 /* store quotient digit */
2432 assert(q < PyLong_BASE);
2433 *--ak = q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002434 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002435
2436 /* unshift remainder; we reuse w to store the result */
2437 carry = v_rshift(w0, v0, size_w, d);
2438 assert(carry==0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002439 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002440
2441 *prem = long_normalize(w);
2442 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002443}
2444
2445/* Methods */
2446
2447static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002448long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002449{
Christian Heimes90aa7642007-12-19 02:45:37 +00002450 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002451}
2452
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002453static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002454long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002455{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002456 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002457
Christian Heimes90aa7642007-12-19 02:45:37 +00002458 if (Py_SIZE(a) != Py_SIZE(b)) {
2459 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002460 sign = 0;
2461 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002462 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002463 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002464 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002465 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002466 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2467 ;
2468 if (i < 0)
2469 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002470 else {
Mark Dickinsone4416742009-02-15 15:14:57 +00002471 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002472 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002473 sign = -sign;
2474 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002475 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002476 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002477}
2478
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002479#define TEST_COND(cond) \
2480 ((cond) ? Py_True : Py_False)
2481
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002482static PyObject *
2483long_richcompare(PyObject *self, PyObject *other, int op)
2484{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002485 int result;
2486 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002487 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002488 if (self == other)
2489 result = 0;
2490 else
2491 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2492 /* Convert the return value to a Boolean */
2493 switch (op) {
2494 case Py_EQ:
2495 v = TEST_COND(result == 0);
2496 break;
2497 case Py_NE:
2498 v = TEST_COND(result != 0);
2499 break;
2500 case Py_LE:
2501 v = TEST_COND(result <= 0);
2502 break;
2503 case Py_GE:
2504 v = TEST_COND(result >= 0);
2505 break;
2506 case Py_LT:
2507 v = TEST_COND(result == -1);
2508 break;
2509 case Py_GT:
2510 v = TEST_COND(result == 1);
2511 break;
2512 default:
2513 PyErr_BadArgument();
2514 return NULL;
2515 }
2516 Py_INCREF(v);
2517 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002518}
2519
Guido van Rossum9bfef441993-03-29 10:43:31 +00002520static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002521long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002522{
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002523 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002524 Py_ssize_t i;
2525 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002526
2527 /* This is designed so that Python ints and longs with the
2528 same value hash to the same value, otherwise comparisons
2529 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002530 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002531 switch(i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00002532 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00002533 case 0: return 0;
2534 case 1: return v->ob_digit[0];
2535 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002536 sign = 1;
2537 x = 0;
2538 if (i < 0) {
2539 sign = -1;
2540 i = -(i);
2541 }
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002542 /* The following loop produces a C unsigned long x such that x is
2543 congruent to the absolute value of v modulo ULONG_MAX. The
Thomas Woutersce272b62007-09-19 21:19:28 +00002544 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002545 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002546 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002547 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002548 x += v->ob_digit[i];
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002549 /* If the addition above overflowed we compensate by
2550 incrementing. This preserves the value modulo
2551 ULONG_MAX. */
2552 if (x < v->ob_digit[i])
Thomas Woutersce272b62007-09-19 21:19:28 +00002553 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002554 }
2555 x = x * sign;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002556 if (x == (unsigned long)-1)
2557 x = (unsigned long)-2;
2558 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002559}
2560
2561
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002562/* Add the absolute values of two long integers. */
2563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002564static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002565x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002566{
Christian Heimes90aa7642007-12-19 02:45:37 +00002567 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002568 PyLongObject *z;
Mark Dickinson17e55872009-01-24 15:56:57 +00002569 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002570 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002571
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002572 /* Ensure a is the larger of the two: */
2573 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002574 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002575 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002576 size_a = size_b;
2577 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002578 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002579 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002580 if (z == NULL)
2581 return NULL;
2582 for (i = 0; i < size_b; ++i) {
2583 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002584 z->ob_digit[i] = carry & PyLong_MASK;
2585 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002586 }
2587 for (; i < size_a; ++i) {
2588 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002589 z->ob_digit[i] = carry & PyLong_MASK;
2590 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002591 }
2592 z->ob_digit[i] = carry;
2593 return long_normalize(z);
2594}
2595
2596/* Subtract the absolute values of two integers. */
2597
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002598static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002599x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002600{
Christian Heimes90aa7642007-12-19 02:45:37 +00002601 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002602 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002603 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002604 int sign = 1;
2605 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002606
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002607 /* Ensure a is the larger of the two: */
2608 if (size_a < size_b) {
2609 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002610 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002611 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002612 size_a = size_b;
2613 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002614 }
2615 else if (size_a == size_b) {
2616 /* Find highest digit where a and b differ: */
2617 i = size_a;
2618 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2619 ;
2620 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002621 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002622 if (a->ob_digit[i] < b->ob_digit[i]) {
2623 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002624 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002625 }
2626 size_a = size_b = i+1;
2627 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002628 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002629 if (z == NULL)
2630 return NULL;
2631 for (i = 0; i < size_b; ++i) {
2632 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002633 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002634 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002635 z->ob_digit[i] = borrow & PyLong_MASK;
2636 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002637 borrow &= 1; /* Keep only one sign bit */
2638 }
2639 for (; i < size_a; ++i) {
2640 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002641 z->ob_digit[i] = borrow & PyLong_MASK;
2642 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002643 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002644 }
2645 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002646 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002647 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002648 return long_normalize(z);
2649}
2650
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002651static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002652long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002653{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002654 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002655
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002656 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002657
Christian Heimes90aa7642007-12-19 02:45:37 +00002658 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002659 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002660 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002661 return result;
2662 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002663 if (Py_SIZE(a) < 0) {
2664 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002665 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002666 if (z != NULL && Py_SIZE(z) != 0)
2667 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002668 }
2669 else
2670 z = x_sub(b, a);
2671 }
2672 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002673 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002674 z = x_sub(a, b);
2675 else
2676 z = x_add(a, b);
2677 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002678 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002679}
2680
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002681static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002682long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002683{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002684 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002685
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002686 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002687
Christian Heimes90aa7642007-12-19 02:45:37 +00002688 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002689 PyObject* r;
2690 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002691 return r;
2692 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002693 if (Py_SIZE(a) < 0) {
2694 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002695 z = x_sub(a, b);
2696 else
2697 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002698 if (z != NULL && Py_SIZE(z) != 0)
2699 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002700 }
2701 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002702 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002703 z = x_add(a, b);
2704 else
2705 z = x_sub(a, b);
2706 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002707 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002708}
2709
Tim Peters5af4e6c2002-08-12 02:31:19 +00002710/* Grade school multiplication, ignoring the signs.
2711 * Returns the absolute value of the product, or NULL if error.
2712 */
2713static PyLongObject *
2714x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002715{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002716 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002717 Py_ssize_t size_a = ABS(Py_SIZE(a));
2718 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002719 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002720
Tim Peters5af4e6c2002-08-12 02:31:19 +00002721 z = _PyLong_New(size_a + size_b);
2722 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002723 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002724
Christian Heimes90aa7642007-12-19 02:45:37 +00002725 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002726 if (a == b) {
2727 /* Efficient squaring per HAC, Algorithm 14.16:
2728 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2729 * Gives slightly less than a 2x speedup when a == b,
2730 * via exploiting that each entry in the multiplication
2731 * pyramid appears twice (except for the size_a squares).
2732 */
2733 for (i = 0; i < size_a; ++i) {
2734 twodigits carry;
2735 twodigits f = a->ob_digit[i];
2736 digit *pz = z->ob_digit + (i << 1);
2737 digit *pa = a->ob_digit + i + 1;
2738 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002739
Tim Peters0973b992004-08-29 22:16:50 +00002740 SIGCHECK({
2741 Py_DECREF(z);
2742 return NULL;
2743 })
2744
2745 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002746 *pz++ = (digit)(carry & PyLong_MASK);
2747 carry >>= PyLong_SHIFT;
2748 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002749
2750 /* Now f is added in twice in each column of the
2751 * pyramid it appears. Same as adding f<<1 once.
2752 */
2753 f <<= 1;
2754 while (pa < paend) {
2755 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002756 *pz++ = (digit)(carry & PyLong_MASK);
2757 carry >>= PyLong_SHIFT;
2758 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002759 }
2760 if (carry) {
2761 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002762 *pz++ = (digit)(carry & PyLong_MASK);
2763 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002764 }
2765 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002766 *pz += (digit)(carry & PyLong_MASK);
2767 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002768 }
Tim Peters0973b992004-08-29 22:16:50 +00002769 }
2770 else { /* a is not the same as b -- gradeschool long mult */
2771 for (i = 0; i < size_a; ++i) {
2772 twodigits carry = 0;
2773 twodigits f = a->ob_digit[i];
2774 digit *pz = z->ob_digit + i;
2775 digit *pb = b->ob_digit;
2776 digit *pbend = b->ob_digit + size_b;
2777
2778 SIGCHECK({
2779 Py_DECREF(z);
2780 return NULL;
2781 })
2782
2783 while (pb < pbend) {
2784 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002785 *pz++ = (digit)(carry & PyLong_MASK);
2786 carry >>= PyLong_SHIFT;
2787 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002788 }
2789 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002790 *pz += (digit)(carry & PyLong_MASK);
2791 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002792 }
2793 }
Tim Peters44121a62002-08-12 06:17:58 +00002794 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002795}
2796
2797/* A helper for Karatsuba multiplication (k_mul).
2798 Takes a long "n" and an integer "size" representing the place to
2799 split, and sets low and high such that abs(n) == (high << size) + low,
2800 viewing the shift as being by digits. The sign bit is ignored, and
2801 the return values are >= 0.
2802 Returns 0 on success, -1 on failure.
2803*/
2804static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002805kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002806{
2807 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002808 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002809 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002810
2811 size_lo = MIN(size_n, size);
2812 size_hi = size_n - size_lo;
2813
2814 if ((hi = _PyLong_New(size_hi)) == NULL)
2815 return -1;
2816 if ((lo = _PyLong_New(size_lo)) == NULL) {
2817 Py_DECREF(hi);
2818 return -1;
2819 }
2820
2821 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2822 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2823
2824 *high = long_normalize(hi);
2825 *low = long_normalize(lo);
2826 return 0;
2827}
2828
Tim Peters60004642002-08-12 22:01:34 +00002829static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2830
Tim Peters5af4e6c2002-08-12 02:31:19 +00002831/* Karatsuba multiplication. Ignores the input signs, and returns the
2832 * absolute value of the product (or NULL if error).
2833 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2834 */
2835static PyLongObject *
2836k_mul(PyLongObject *a, PyLongObject *b)
2837{
Christian Heimes90aa7642007-12-19 02:45:37 +00002838 Py_ssize_t asize = ABS(Py_SIZE(a));
2839 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002840 PyLongObject *ah = NULL;
2841 PyLongObject *al = NULL;
2842 PyLongObject *bh = NULL;
2843 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002844 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002845 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002846 Py_ssize_t shift; /* the number of digits we split off */
2847 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002848
Tim Peters5af4e6c2002-08-12 02:31:19 +00002849 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2850 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2851 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002852 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002853 * By picking X to be a power of 2, "*X" is just shifting, and it's
2854 * been reduced to 3 multiplies on numbers half the size.
2855 */
2856
Tim Petersfc07e562002-08-12 02:54:10 +00002857 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002858 * is largest.
2859 */
Tim Peters738eda72002-08-12 15:08:20 +00002860 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002861 t1 = a;
2862 a = b;
2863 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002864
2865 i = asize;
2866 asize = bsize;
2867 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002868 }
2869
2870 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002871 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2872 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002873 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002874 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002875 else
2876 return x_mul(a, b);
2877 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002878
Tim Peters60004642002-08-12 22:01:34 +00002879 /* If a is small compared to b, splitting on b gives a degenerate
2880 * case with ah==0, and Karatsuba may be (even much) less efficient
2881 * than "grade school" then. However, we can still win, by viewing
2882 * b as a string of "big digits", each of width a->ob_size. That
2883 * leads to a sequence of balanced calls to k_mul.
2884 */
2885 if (2 * asize <= bsize)
2886 return k_lopsided_mul(a, b);
2887
Tim Petersd6974a52002-08-13 20:37:51 +00002888 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002889 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002890 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002891 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002892
Tim Peters0973b992004-08-29 22:16:50 +00002893 if (a == b) {
2894 bh = ah;
2895 bl = al;
2896 Py_INCREF(bh);
2897 Py_INCREF(bl);
2898 }
2899 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002900
Tim Petersd64c1de2002-08-12 17:36:03 +00002901 /* The plan:
2902 * 1. Allocate result space (asize + bsize digits: that's always
2903 * enough).
2904 * 2. Compute ah*bh, and copy into result at 2*shift.
2905 * 3. Compute al*bl, and copy into result at 0. Note that this
2906 * can't overlap with #2.
2907 * 4. Subtract al*bl from the result, starting at shift. This may
2908 * underflow (borrow out of the high digit), but we don't care:
2909 * we're effectively doing unsigned arithmetic mod
2910 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2911 * borrows and carries out of the high digit can be ignored.
2912 * 5. Subtract ah*bh from the result, starting at shift.
2913 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2914 * at shift.
2915 */
2916
2917 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002918 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002919 if (ret == NULL) goto fail;
2920#ifdef Py_DEBUG
2921 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002922 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002923#endif
Tim Peters44121a62002-08-12 06:17:58 +00002924
Tim Petersd64c1de2002-08-12 17:36:03 +00002925 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002926 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002927 assert(Py_SIZE(t1) >= 0);
2928 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002929 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002930 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002931
2932 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002933 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002934 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002935 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002936 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002937
Tim Petersd64c1de2002-08-12 17:36:03 +00002938 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002939 if ((t2 = k_mul(al, bl)) == NULL) {
2940 Py_DECREF(t1);
2941 goto fail;
2942 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002943 assert(Py_SIZE(t2) >= 0);
2944 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2945 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002946
2947 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002948 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002949 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002950 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002951
Tim Petersd64c1de2002-08-12 17:36:03 +00002952 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2953 * because it's fresher in cache.
2954 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002955 i = Py_SIZE(ret) - shift; /* # digits after shift */
2956 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002957 Py_DECREF(t2);
2958
Christian Heimes90aa7642007-12-19 02:45:37 +00002959 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002960 Py_DECREF(t1);
2961
Tim Petersd64c1de2002-08-12 17:36:03 +00002962 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002963 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2964 Py_DECREF(ah);
2965 Py_DECREF(al);
2966 ah = al = NULL;
2967
Tim Peters0973b992004-08-29 22:16:50 +00002968 if (a == b) {
2969 t2 = t1;
2970 Py_INCREF(t2);
2971 }
2972 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002973 Py_DECREF(t1);
2974 goto fail;
2975 }
2976 Py_DECREF(bh);
2977 Py_DECREF(bl);
2978 bh = bl = NULL;
2979
Tim Peters738eda72002-08-12 15:08:20 +00002980 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002981 Py_DECREF(t1);
2982 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002983 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002984 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002985
Tim Petersd6974a52002-08-13 20:37:51 +00002986 /* Add t3. It's not obvious why we can't run out of room here.
2987 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002988 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002989 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002990 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002991
Tim Peters5af4e6c2002-08-12 02:31:19 +00002992 return long_normalize(ret);
2993
2994 fail:
2995 Py_XDECREF(ret);
2996 Py_XDECREF(ah);
2997 Py_XDECREF(al);
2998 Py_XDECREF(bh);
2999 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003000 return NULL;
3001}
3002
Tim Petersd6974a52002-08-13 20:37:51 +00003003/* (*) Why adding t3 can't "run out of room" above.
3004
Tim Petersab86c2b2002-08-15 20:06:00 +00003005Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3006to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003007
Tim Petersab86c2b2002-08-15 20:06:00 +000030081. For any integer i, i = c(i/2) + f(i/2). In particular,
3009 bsize = c(bsize/2) + f(bsize/2).
30102. shift = f(bsize/2)
30113. asize <= bsize
30124. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3013 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003014
Tim Petersab86c2b2002-08-15 20:06:00 +00003015We allocated asize + bsize result digits, and add t3 into them at an offset
3016of shift. This leaves asize+bsize-shift allocated digit positions for t3
3017to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3018asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003019
Tim Petersab86c2b2002-08-15 20:06:00 +00003020bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3021at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003022
Tim Petersab86c2b2002-08-15 20:06:00 +00003023If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3024digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3025most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003026
Tim Petersab86c2b2002-08-15 20:06:00 +00003027The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003028
Tim Petersab86c2b2002-08-15 20:06:00 +00003029 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003030
Tim Petersab86c2b2002-08-15 20:06:00 +00003031and we have asize + c(bsize/2) available digit positions. We need to show
3032this is always enough. An instance of c(bsize/2) cancels out in both, so
3033the question reduces to whether asize digits is enough to hold
3034(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3035then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3036asize 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 +00003037digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003038asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003039c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3040is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3041bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003042
Tim Peters48d52c02002-08-14 17:07:32 +00003043Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3044clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3045ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003046*/
3047
Tim Peters60004642002-08-12 22:01:34 +00003048/* b has at least twice the digits of a, and a is big enough that Karatsuba
3049 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3050 * of slices, each with a->ob_size digits, and multiply the slices by a,
3051 * one at a time. This gives k_mul balanced inputs to work with, and is
3052 * also cache-friendly (we compute one double-width slice of the result
3053 * at a time, then move on, never bactracking except for the helpful
3054 * single-width slice overlap between successive partial sums).
3055 */
3056static PyLongObject *
3057k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3058{
Christian Heimes90aa7642007-12-19 02:45:37 +00003059 const Py_ssize_t asize = ABS(Py_SIZE(a));
3060 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00003061 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00003062 PyLongObject *ret;
3063 PyLongObject *bslice = NULL;
3064
3065 assert(asize > KARATSUBA_CUTOFF);
3066 assert(2 * asize <= bsize);
3067
3068 /* Allocate result space, and zero it out. */
3069 ret = _PyLong_New(asize + bsize);
3070 if (ret == NULL)
3071 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003072 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003073
3074 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00003075 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00003076 if (bslice == NULL)
3077 goto fail;
3078
3079 nbdone = 0;
3080 while (bsize > 0) {
3081 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003082 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003083
3084 /* Multiply the next slice of b by a. */
3085 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3086 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00003087 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00003088 product = k_mul(a, bslice);
3089 if (product == NULL)
3090 goto fail;
3091
3092 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003093 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3094 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00003095 Py_DECREF(product);
3096
3097 bsize -= nbtouse;
3098 nbdone += nbtouse;
3099 }
3100
3101 Py_DECREF(bslice);
3102 return long_normalize(ret);
3103
3104 fail:
3105 Py_DECREF(ret);
3106 Py_XDECREF(bslice);
3107 return NULL;
3108}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003109
3110static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003111long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003112{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003113 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003114
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003115 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003116
Mark Dickinsonbd792642009-03-18 20:06:12 +00003117 /* fast path for single-digit multiplication */
Christian Heimes90aa7642007-12-19 02:45:37 +00003118 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonbd792642009-03-18 20:06:12 +00003119 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
3120#ifdef HAVE_LONG_LONG
3121 return PyLong_FromLongLong((PY_LONG_LONG)v);
3122#else
3123 /* if we don't have long long then we're almost certainly
3124 using 15-bit digits, so v will fit in a long. In the
3125 unlikely event that we're using 30-bit digits on a platform
3126 without long long, a large v will just cause us to fall
3127 through to the general multiplication code below. */
3128 if (v >= LONG_MIN && v <= LONG_MAX)
3129 return PyLong_FromLong((long)v);
3130#endif
Martin v. Löwis14b6d922007-02-06 21:05:30 +00003131 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003132
Tim Petersd64c1de2002-08-12 17:36:03 +00003133 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00003134 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003135 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003136 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00003137 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003138}
3139
Guido van Rossume32e0141992-01-19 16:31:05 +00003140/* The / and % operators are now defined in terms of divmod().
3141 The expression a mod b has the value a - b*floor(a/b).
3142 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003143 |a| by |b|, with the sign of a. This is also expressed
3144 as a - b*trunc(a/b), if trunc truncates towards zero.
3145 Some examples:
3146 a b a rem b a mod b
3147 13 10 3 3
3148 -13 10 -3 7
3149 13 -10 3 -7
3150 -13 -10 -3 -3
3151 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003152 have different signs. We then subtract one from the 'div'
3153 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003154
Tim Peters47e52ee2004-08-30 02:44:38 +00003155/* Compute
3156 * *pdiv, *pmod = divmod(v, w)
3157 * NULL can be passed for pdiv or pmod, in which case that part of
3158 * the result is simply thrown away. The caller owns a reference to
3159 * each of these it requests (does not pass NULL for).
3160 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003161static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003162l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00003163 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003164{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003165 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003166
Guido van Rossume32e0141992-01-19 16:31:05 +00003167 if (long_divrem(v, w, &div, &mod) < 0)
3168 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00003169 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3170 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003171 PyLongObject *temp;
3172 PyLongObject *one;
3173 temp = (PyLongObject *) long_add(mod, w);
3174 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00003175 mod = temp;
3176 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003177 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003178 return -1;
3179 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003180 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00003181 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003182 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3183 Py_DECREF(mod);
3184 Py_DECREF(div);
3185 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00003186 return -1;
3187 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003188 Py_DECREF(one);
3189 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003190 div = temp;
3191 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003192 if (pdiv != NULL)
3193 *pdiv = div;
3194 else
3195 Py_DECREF(div);
3196
3197 if (pmod != NULL)
3198 *pmod = mod;
3199 else
3200 Py_DECREF(mod);
3201
Guido van Rossume32e0141992-01-19 16:31:05 +00003202 return 0;
3203}
3204
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003205static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003206long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003207{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003208 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003209
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003210 CHECK_BINOP(a, b);
3211 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003212 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003213 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003214}
3215
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003216static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003217long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00003218{
Tim Peterse2a60002001-09-04 06:17:36 +00003219 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00003220 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00003221
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003222 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00003223 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
3224 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00003225 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00003226 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00003227 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00003228 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
3229 but should really be set correctly after sucessful calls to
3230 _PyLong_AsScaledDouble() */
3231 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00003232
3233 if (bd == 0.0) {
3234 PyErr_SetString(PyExc_ZeroDivisionError,
Mark Dickinson0b9293f2009-12-07 19:34:59 +00003235 "integer division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00003236 return NULL;
3237 }
3238
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003239 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00003240 ad /= bd; /* overflow/underflow impossible here */
3241 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003242 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00003243 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003244 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00003245 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003246 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003247 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00003248 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003249 goto overflow;
3250 return PyFloat_FromDouble(ad);
3251
3252overflow:
3253 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003254 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00003255 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003256
Tim Peters20dab9f2001-09-04 05:31:47 +00003257}
3258
3259static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003260long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003261{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003262 PyLongObject *mod;
3263
3264 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003265
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003266 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003267 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003268 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003269}
3270
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003271static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003272long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003273{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003274 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003275 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003276
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003277 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003278
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003279 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003280 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003281 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003282 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003283 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003284 PyTuple_SetItem(z, 0, (PyObject *) div);
3285 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003286 }
3287 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003288 Py_DECREF(div);
3289 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003290 }
3291 return z;
3292}
3293
Tim Peters47e52ee2004-08-30 02:44:38 +00003294/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003295static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003296long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003297{
Tim Peters47e52ee2004-08-30 02:44:38 +00003298 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3299 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003300
Tim Peters47e52ee2004-08-30 02:44:38 +00003301 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003302 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003303 PyLongObject *temp = NULL;
3304
3305 /* 5-ary values. If the exponent is large enough, table is
3306 * precomputed so that table[i] == a**i % c for i in range(32).
3307 */
3308 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3309 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3310
3311 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003312 CHECK_BINOP(v, w);
3313 a = (PyLongObject*)v; Py_INCREF(a);
3314 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003315 if (PyLong_Check(x)) {
3316 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003317 Py_INCREF(x);
3318 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003319 else if (x == Py_None)
3320 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003321 else {
3322 Py_DECREF(a);
3323 Py_DECREF(b);
3324 Py_INCREF(Py_NotImplemented);
3325 return Py_NotImplemented;
3326 }
Tim Peters4c483c42001-09-05 06:24:58 +00003327
Christian Heimes90aa7642007-12-19 02:45:37 +00003328 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003329 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003330 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003331 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003332 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003333 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003334 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003335 /* else return a float. This works because we know
3336 that this calls float_pow() which converts its
3337 arguments to double. */
3338 Py_DECREF(a);
3339 Py_DECREF(b);
3340 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003341 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003342 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003343
3344 if (c) {
3345 /* if modulus == 0:
3346 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003347 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003348 PyErr_SetString(PyExc_ValueError,
3349 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003350 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003351 }
3352
3353 /* if modulus < 0:
3354 negativeOutput = True
3355 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003356 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003357 negativeOutput = 1;
3358 temp = (PyLongObject *)_PyLong_Copy(c);
3359 if (temp == NULL)
3360 goto Error;
3361 Py_DECREF(c);
3362 c = temp;
3363 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003364 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003365 }
3366
3367 /* if modulus == 1:
3368 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003369 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003370 z = (PyLongObject *)PyLong_FromLong(0L);
3371 goto Done;
3372 }
3373
3374 /* if base < 0:
3375 base = base % modulus
3376 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003377 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003378 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003379 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003380 Py_DECREF(a);
3381 a = temp;
3382 temp = NULL;
3383 }
3384 }
3385
3386 /* At this point a, b, and c are guaranteed non-negative UNLESS
3387 c is NULL, in which case a may be negative. */
3388
3389 z = (PyLongObject *)PyLong_FromLong(1L);
3390 if (z == NULL)
3391 goto Error;
3392
3393 /* Perform a modular reduction, X = X % c, but leave X alone if c
3394 * is NULL.
3395 */
3396#define REDUCE(X) \
3397 if (c != NULL) { \
3398 if (l_divmod(X, c, NULL, &temp) < 0) \
3399 goto Error; \
3400 Py_XDECREF(X); \
3401 X = temp; \
3402 temp = NULL; \
3403 }
3404
3405 /* Multiply two values, then reduce the result:
3406 result = X*Y % c. If c is NULL, skip the mod. */
3407#define MULT(X, Y, result) \
3408{ \
3409 temp = (PyLongObject *)long_mul(X, Y); \
3410 if (temp == NULL) \
3411 goto Error; \
3412 Py_XDECREF(result); \
3413 result = temp; \
3414 temp = NULL; \
3415 REDUCE(result) \
3416}
3417
Christian Heimes90aa7642007-12-19 02:45:37 +00003418 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003419 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3420 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003421 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003422 digit bi = b->ob_digit[i];
3423
Mark Dickinsone4416742009-02-15 15:14:57 +00003424 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003425 MULT(z, z, z)
3426 if (bi & j)
3427 MULT(z, a, z)
3428 }
3429 }
3430 }
3431 else {
3432 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3433 Py_INCREF(z); /* still holds 1L */
3434 table[0] = z;
3435 for (i = 1; i < 32; ++i)
3436 MULT(table[i-1], a, table[i])
3437
Christian Heimes90aa7642007-12-19 02:45:37 +00003438 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003439 const digit bi = b->ob_digit[i];
3440
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003441 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003442 const int index = (bi >> j) & 0x1f;
3443 for (k = 0; k < 5; ++k)
3444 MULT(z, z, z)
3445 if (index)
3446 MULT(z, table[index], z)
3447 }
3448 }
3449 }
3450
Christian Heimes90aa7642007-12-19 02:45:37 +00003451 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003452 temp = (PyLongObject *)long_sub(z, c);
3453 if (temp == NULL)
3454 goto Error;
3455 Py_DECREF(z);
3456 z = temp;
3457 temp = NULL;
3458 }
3459 goto Done;
3460
3461 Error:
3462 if (z != NULL) {
3463 Py_DECREF(z);
3464 z = NULL;
3465 }
3466 /* fall through */
3467 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003468 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003469 for (i = 0; i < 32; ++i)
3470 Py_XDECREF(table[i]);
3471 }
Tim Petersde7990b2005-07-17 23:45:23 +00003472 Py_DECREF(a);
3473 Py_DECREF(b);
3474 Py_XDECREF(c);
3475 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003476 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003477}
3478
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003479static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003480long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003481{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003482 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003483 PyLongObject *x;
3484 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003485 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003486 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003487 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003488 if (w == NULL)
3489 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003490 x = (PyLongObject *) long_add(v, w);
3491 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003492 if (x == NULL)
3493 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003494 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003495 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003496}
3497
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003498static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003499long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003500{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003501 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003502 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003503 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003504 z = (PyLongObject *)_PyLong_Copy(v);
3505 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003506 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003507 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003508}
3509
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003510static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003511long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003512{
Christian Heimes90aa7642007-12-19 02:45:37 +00003513 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003514 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003515 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003516 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003517}
3518
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003519static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003520long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003521{
Christian Heimes90aa7642007-12-19 02:45:37 +00003522 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003523}
3524
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003525static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003526long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003527{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003528 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003529 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003530 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003531 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003532
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003533 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003534
Christian Heimes90aa7642007-12-19 02:45:37 +00003535 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003536 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003537 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003538 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003539 if (a1 == NULL)
3540 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003541 a2 = (PyLongObject *) long_rshift(a1, b);
3542 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003543 if (a2 == NULL)
3544 goto rshift_error;
3545 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003546 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003547 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003548 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003549
Neil Schemenauerba872e22001-01-04 01:46:03 +00003550 shiftby = PyLong_AsLong((PyObject *)b);
3551 if (shiftby == -1L && PyErr_Occurred())
3552 goto rshift_error;
3553 if (shiftby < 0) {
3554 PyErr_SetString(PyExc_ValueError,
3555 "negative shift count");
3556 goto rshift_error;
3557 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003558 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003559 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003560 if (newsize <= 0)
3561 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003562 loshift = shiftby % PyLong_SHIFT;
3563 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003564 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003565 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003566 z = _PyLong_New(newsize);
3567 if (z == NULL)
3568 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003569 if (Py_SIZE(a) < 0)
3570 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003571 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3572 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3573 if (i+1 < newsize)
3574 z->ob_digit[i] |=
3575 (a->ob_digit[j+1] << hishift) & himask;
3576 }
3577 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003578 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003579rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003580 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003581
Guido van Rossumc6913e71991-11-19 20:26:46 +00003582}
3583
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003584static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003585long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003586{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003587 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003588 PyLongObject *a = (PyLongObject*)v;
3589 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003590 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003591 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003592 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003593 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003594
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003595 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003596
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003597 shiftby = PyLong_AsLong((PyObject *)b);
3598 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003599 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003600 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003601 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003602 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003603 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003604 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003605 PyErr_SetString(PyExc_ValueError,
3606 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003607 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003608 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003609 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3610 wordshift = (int)shiftby / PyLong_SHIFT;
3611 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003612
Christian Heimes90aa7642007-12-19 02:45:37 +00003613 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003614 newsize = oldsize + wordshift;
3615 if (remshift)
3616 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003617 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003618 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003619 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003620 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003621 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003622 for (i = 0; i < wordshift; i++)
3623 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003624 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003625 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003626 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003627 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3628 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003629 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003630 if (remshift)
3631 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003632 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003633 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003634 z = long_normalize(z);
3635lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003636 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003637}
3638
Mark Dickinson27a87a22009-10-25 20:43:34 +00003639/* Compute two's complement of digit vector a[0:m], writing result to
3640 z[0:m]. The digit vector a need not be normalized, but should not
3641 be entirely zero. a and z may point to the same digit vector. */
3642
3643static void
3644v_complement(digit *z, digit *a, Py_ssize_t m)
3645{
3646 Py_ssize_t i;
3647 digit carry = 1;
3648 for (i = 0; i < m; ++i) {
3649 carry += a[i] ^ PyLong_MASK;
3650 z[i] = carry & PyLong_MASK;
3651 carry >>= PyLong_SHIFT;
3652 }
3653 assert(carry == 0);
3654}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003655
3656/* Bitwise and/xor/or operations */
3657
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003658static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003659long_bitwise(PyLongObject *a,
3660 int op, /* '&', '|', '^' */
3661 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003662{
Mark Dickinson27a87a22009-10-25 20:43:34 +00003663 int nega, negb, negz;
Mark Dickinsone4416742009-02-15 15:14:57 +00003664 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003665 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003666
Mark Dickinson27a87a22009-10-25 20:43:34 +00003667 /* Bitwise operations for negative numbers operate as though
3668 on a two's complement representation. So convert arguments
3669 from sign-magnitude to two's complement, and convert the
3670 result back to sign-magnitude at the end. */
3671
3672 /* If a is negative, replace it by its two's complement. */
3673 size_a = ABS(Py_SIZE(a));
3674 nega = Py_SIZE(a) < 0;
3675 if (nega) {
3676 z = _PyLong_New(size_a);
3677 if (z == NULL)
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003678 return NULL;
Mark Dickinson27a87a22009-10-25 20:43:34 +00003679 v_complement(z->ob_digit, a->ob_digit, size_a);
3680 a = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003681 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003682 else
3683 /* Keep reference count consistent. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003684 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003685
3686 /* Same for b. */
3687 size_b = ABS(Py_SIZE(b));
3688 negb = Py_SIZE(b) < 0;
3689 if (negb) {
3690 z = _PyLong_New(size_b);
3691 if (z == NULL) {
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003692 Py_DECREF(a);
3693 return NULL;
3694 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003695 v_complement(z->ob_digit, b->ob_digit, size_b);
3696 b = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003697 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003698 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003699 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003700
Mark Dickinson27a87a22009-10-25 20:43:34 +00003701 /* Swap a and b if necessary to ensure size_a >= size_b. */
3702 if (size_a < size_b) {
3703 z = a; a = b; b = z;
3704 size_z = size_a; size_a = size_b; size_b = size_z;
3705 negz = nega; nega = negb; negb = negz;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003706 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003707
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003708 /* JRH: The original logic here was to allocate the result value (z)
3709 as the longer of the two operands. However, there are some cases
3710 where the result is guaranteed to be shorter than that: AND of two
3711 positives, OR of two negatives: use the shorter number. AND with
3712 mixed signs: use the positive number. OR with mixed signs: use the
Mark Dickinson27a87a22009-10-25 20:43:34 +00003713 negative number.
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003714 */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003715 switch (op) {
3716 case '^':
3717 negz = nega ^ negb;
3718 size_z = size_a;
3719 break;
3720 case '&':
3721 negz = nega & negb;
3722 size_z = negb ? size_a : size_b;
3723 break;
3724 case '|':
3725 negz = nega | negb;
3726 size_z = negb ? size_b : size_a;
3727 break;
3728 default:
3729 PyErr_BadArgument();
3730 return NULL;
3731 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003732
Mark Dickinson27a87a22009-10-25 20:43:34 +00003733 /* We allow an extra digit if z is negative, to make sure that
3734 the final two's complement of z doesn't overflow. */
3735 z = _PyLong_New(size_z + negz);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003736 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003737 Py_DECREF(a);
3738 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003739 return NULL;
3740 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003741
Mark Dickinson27a87a22009-10-25 20:43:34 +00003742 /* Compute digits for overlap of a and b. */
3743 switch(op) {
3744 case '&':
3745 for (i = 0; i < size_b; ++i)
3746 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3747 break;
3748 case '|':
3749 for (i = 0; i < size_b; ++i)
3750 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3751 break;
3752 case '^':
3753 for (i = 0; i < size_b; ++i)
3754 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3755 break;
3756 default:
3757 PyErr_BadArgument();
3758 return NULL;
3759 }
3760
3761 /* Copy any remaining digits of a, inverting if necessary. */
3762 if (op == '^' && negb)
3763 for (; i < size_z; ++i)
3764 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
3765 else if (i < size_z)
3766 memcpy(&z->ob_digit[i], &a->ob_digit[i],
3767 (size_z-i)*sizeof(digit));
3768
3769 /* Complement result if negative. */
3770 if (negz) {
3771 Py_SIZE(z) = -(Py_SIZE(z));
3772 z->ob_digit[size_z] = PyLong_MASK;
3773 v_complement(z->ob_digit, z->ob_digit, size_z+1);
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003774 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003775
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003776 Py_DECREF(a);
3777 Py_DECREF(b);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003778 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00003779}
3780
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003781static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003782long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003783{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003784 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003785 CHECK_BINOP(a, b);
3786 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003787 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003788}
3789
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003790static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003791long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003792{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003793 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003794 CHECK_BINOP(a, b);
3795 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003796 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003797}
3798
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003799static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003800long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003801{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003802 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003803 CHECK_BINOP(a, b);
3804 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003805 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003806}
3807
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003808static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003809long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003810{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003811 if (PyLong_CheckExact(v))
3812 Py_INCREF(v);
3813 else
3814 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003815 return v;
3816}
3817
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003818static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003819long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003820{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003821 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003822 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003823 if (result == -1.0 && PyErr_Occurred())
3824 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003825 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003826}
3827
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003828static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003829long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003830
Tim Peters6d6c1a32001-08-02 04:15:00 +00003831static PyObject *
3832long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3833{
3834 PyObject *x = NULL;
3835 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003836 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837
Guido van Rossumbef14172001-08-29 15:47:46 +00003838 if (type != &PyLong_Type)
3839 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003840 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841 &x, &base))
3842 return NULL;
3843 if (x == NULL)
3844 return PyLong_FromLong(0L);
3845 if (base == -909)
3846 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003847 else if (PyUnicode_Check(x))
3848 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3849 PyUnicode_GET_SIZE(x),
3850 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003851 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003852 /* Since PyLong_FromString doesn't have a length parameter,
3853 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003854 char *string;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003855 Py_ssize_t size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003856 if (PyByteArray_Check(x))
3857 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003858 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003859 string = PyBytes_AS_STRING(x);
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003860 if (strlen(string) != (size_t)size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003861 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003862 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003863 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003864 "invalid literal for int() with base %d: %R",
3865 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003866 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003867 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003868 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003869 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003870 else {
3871 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003872 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003873 return NULL;
3874 }
3875}
3876
Guido van Rossumbef14172001-08-29 15:47:46 +00003877/* Wimpy, slow approach to tp_new calls for subtypes of long:
3878 first create a regular long from whatever arguments we got,
3879 then allocate a subtype instance and initialize it from
3880 the regular long. The regular long is then thrown away.
3881*/
3882static PyObject *
3883long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3884{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003885 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003886 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003887
3888 assert(PyType_IsSubtype(type, &PyLong_Type));
3889 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3890 if (tmp == NULL)
3891 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003892 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003893 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003894 if (n < 0)
3895 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003896 newobj = (PyLongObject *)type->tp_alloc(type, n);
3897 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003898 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003899 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003900 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003901 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003902 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003903 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003904 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003905 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003906 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003907}
3908
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003909static PyObject *
3910long_getnewargs(PyLongObject *v)
3911{
3912 return Py_BuildValue("(N)", _PyLong_Copy(v));
3913}
3914
Guido van Rossumb43daf72007-08-01 18:08:08 +00003915static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00003916long_get0(PyLongObject *v, void *context) {
3917 return PyLong_FromLong(0L);
3918}
3919
3920static PyObject *
3921long_get1(PyLongObject *v, void *context) {
3922 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003923}
3924
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003925static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003926long__format__(PyObject *self, PyObject *args)
3927{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003928 PyObject *format_spec;
3929
3930 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3931 return NULL;
3932 return _PyLong_FormatAdvanced(self,
3933 PyUnicode_AS_UNICODE(format_spec),
3934 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003935}
3936
Eric Smith8c663262007-08-25 02:26:07 +00003937static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003938long_round(PyObject *self, PyObject *args)
3939{
Mark Dickinson1124e712009-01-28 21:25:58 +00003940 PyObject *o_ndigits=NULL, *temp;
3941 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
3942 int errcode;
3943 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003944
Mark Dickinson1124e712009-01-28 21:25:58 +00003945 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
3946 the straightforward method is:
3947
3948 (1) divide by 10**n
3949 (2) round to nearest integer (round to even in case of tie)
3950 (3) multiply result by 10**n.
3951
3952 But the rounding step involves examining the fractional part of the
3953 quotient to see whether it's greater than 0.5 or not. Since we
3954 want to do the whole calculation in integer arithmetic, it's
3955 simpler to do:
3956
3957 (1) divide by (10**n)/2
3958 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
3959 (3) multiply result by (10**n)/2.
3960
3961 Then all we need to know about the fractional part of the quotient
3962 arising in step (2) is whether it's zero or not.
3963
3964 Doing both a multiplication and division is wasteful, and is easily
3965 avoided if we just figure out how much to adjust the original input
3966 by to do the rounding.
3967
3968 Here's the whole algorithm expressed in Python.
3969
3970 def round(self, ndigits = None):
3971 """round(int, int) -> int"""
3972 if ndigits is None or ndigits >= 0:
3973 return self
3974 pow = 10**-ndigits >> 1
3975 q, r = divmod(self, pow)
3976 self -= r
3977 if (q & 1 != 0):
3978 if (q & 2 == r == 0):
3979 self -= pow
3980 else:
3981 self += pow
3982 return self
3983
3984 */
3985 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
3986 return NULL;
3987 if (o_ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003988 return long_long(self);
3989
Mark Dickinson1124e712009-01-28 21:25:58 +00003990 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
3991 if (ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003992 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00003993
3994 if (Py_SIZE(ndigits) >= 0) {
3995 Py_DECREF(ndigits);
3996 return long_long(self);
3997 }
3998
3999 Py_INCREF(self); /* to keep refcounting simple */
4000 /* we now own references to self, ndigits */
4001
4002 /* pow = 10 ** -ndigits >> 1 */
4003 pow = (PyLongObject *)PyLong_FromLong(10L);
4004 if (pow == NULL)
4005 goto error;
4006 temp = long_neg(ndigits);
4007 Py_DECREF(ndigits);
4008 ndigits = (PyLongObject *)temp;
4009 if (ndigits == NULL)
4010 goto error;
4011 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
4012 Py_DECREF(pow);
4013 pow = (PyLongObject *)temp;
4014 if (pow == NULL)
4015 goto error;
4016 assert(PyLong_Check(pow)); /* check long_pow returned a long */
4017 one = (PyLongObject *)PyLong_FromLong(1L);
4018 if (one == NULL)
4019 goto error;
4020 temp = long_rshift(pow, one);
4021 Py_DECREF(one);
4022 Py_DECREF(pow);
4023 pow = (PyLongObject *)temp;
4024 if (pow == NULL)
4025 goto error;
4026
4027 /* q, r = divmod(self, pow) */
4028 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
4029 if (errcode == -1)
4030 goto error;
4031
4032 /* self -= r */
4033 temp = long_sub((PyLongObject *)self, r);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004034 Py_DECREF(self);
Mark Dickinson1124e712009-01-28 21:25:58 +00004035 self = temp;
4036 if (self == NULL)
4037 goto error;
4038
4039 /* get value of quotient modulo 4 */
4040 if (Py_SIZE(q) == 0)
4041 q_mod_4 = 0;
4042 else if (Py_SIZE(q) > 0)
4043 q_mod_4 = q->ob_digit[0] & 3;
4044 else
4045 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
4046
4047 if ((q_mod_4 & 1) == 1) {
4048 /* q is odd; round self up or down by adding or subtracting pow */
4049 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
4050 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
4051 else
4052 temp = (PyObject *)long_add((PyLongObject *)self, pow);
4053 Py_DECREF(self);
4054 self = temp;
4055 if (self == NULL)
4056 goto error;
4057 }
4058 Py_DECREF(q);
4059 Py_DECREF(r);
4060 Py_DECREF(pow);
4061 Py_DECREF(ndigits);
4062 return self;
4063
4064 error:
4065 Py_XDECREF(q);
4066 Py_XDECREF(r);
4067 Py_XDECREF(pow);
4068 Py_XDECREF(self);
4069 Py_XDECREF(ndigits);
4070 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004071}
4072
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004073static PyObject *
4074long_sizeof(PyLongObject *v)
4075{
4076 Py_ssize_t res;
4077
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004078 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004079 return PyLong_FromSsize_t(res);
4080}
4081
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004082static PyObject *
4083long_bit_length(PyLongObject *v)
4084{
4085 PyLongObject *result, *x, *y;
4086 Py_ssize_t ndigits, msd_bits = 0;
4087 digit msd;
4088
4089 assert(v != NULL);
4090 assert(PyLong_Check(v));
4091
4092 ndigits = ABS(Py_SIZE(v));
4093 if (ndigits == 0)
4094 return PyLong_FromLong(0);
4095
4096 msd = v->ob_digit[ndigits-1];
4097 while (msd >= 32) {
4098 msd_bits += 6;
4099 msd >>= 6;
4100 }
4101 msd_bits += (long)(BitLengthTable[msd]);
4102
4103 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4104 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
4105
4106 /* expression above may overflow; use Python integers instead */
4107 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4108 if (result == NULL)
4109 return NULL;
4110 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4111 if (x == NULL)
4112 goto error;
4113 y = (PyLongObject *)long_mul(result, x);
4114 Py_DECREF(x);
4115 if (y == NULL)
4116 goto error;
4117 Py_DECREF(result);
4118 result = y;
4119
4120 x = (PyLongObject *)PyLong_FromLong(msd_bits);
4121 if (x == NULL)
4122 goto error;
4123 y = (PyLongObject *)long_add(result, x);
4124 Py_DECREF(x);
4125 if (y == NULL)
4126 goto error;
4127 Py_DECREF(result);
4128 result = y;
4129
4130 return (PyObject *)result;
4131
4132error:
4133 Py_DECREF(result);
4134 return NULL;
4135}
4136
4137PyDoc_STRVAR(long_bit_length_doc,
4138"int.bit_length() -> int\n\
4139\n\
4140Number of bits necessary to represent self in binary.\n\
4141>>> bin(37)\n\
4142'0b100101'\n\
4143>>> (37).bit_length()\n\
41446");
4145
Christian Heimes53876d92008-04-19 00:31:39 +00004146#if 0
4147static PyObject *
4148long_is_finite(PyObject *v)
4149{
4150 Py_RETURN_TRUE;
4151}
4152#endif
4153
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004154static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00004155 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4156 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004157 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4158 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004159#if 0
4160 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4161 "Returns always True."},
4162#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004163 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4164 "Truncating an Integral returns itself."},
4165 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4166 "Flooring an Integral returns itself."},
4167 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4168 "Ceiling of an Integral returns itself."},
4169 {"__round__", (PyCFunction)long_round, METH_VARARGS,
Mark Dickinson1124e712009-01-28 21:25:58 +00004170 "Rounding an Integral returns itself.\n"
4171 "Rounding with an ndigits argument also returns an integer."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004172 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00004173 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004174 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4175 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004176 {NULL, NULL} /* sentinel */
4177};
4178
Guido van Rossumb43daf72007-08-01 18:08:08 +00004179static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004180 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004181 (getter)long_long, (setter)NULL,
4182 "the real part of a complex number",
4183 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004184 {"imag",
4185 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004186 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004187 NULL},
4188 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004189 (getter)long_long, (setter)NULL,
4190 "the numerator of a rational number in lowest terms",
4191 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004192 {"denominator",
4193 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004194 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004195 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004196 {NULL} /* Sentinel */
4197};
4198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004199PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004200"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004202Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004203point argument will be truncated towards zero (this does not include a\n\
4204string representation of a floating point number!) When converting a\n\
4205string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004206converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004207
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004208static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00004209 (binaryfunc) long_add, /*nb_add*/
4210 (binaryfunc) long_sub, /*nb_subtract*/
4211 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004212 long_mod, /*nb_remainder*/
4213 long_divmod, /*nb_divmod*/
4214 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004215 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004216 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004217 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00004218 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004219 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004220 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004221 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004222 long_and, /*nb_and*/
4223 long_xor, /*nb_xor*/
4224 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004225 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00004226 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004227 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00004228 0, /* nb_inplace_add */
4229 0, /* nb_inplace_subtract */
4230 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00004231 0, /* nb_inplace_remainder */
4232 0, /* nb_inplace_power */
4233 0, /* nb_inplace_lshift */
4234 0, /* nb_inplace_rshift */
4235 0, /* nb_inplace_and */
4236 0, /* nb_inplace_xor */
4237 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004238 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00004239 long_true_divide, /* nb_true_divide */
4240 0, /* nb_inplace_floor_divide */
4241 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004242 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004243};
4244
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004245PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004246 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00004247 "int", /* tp_name */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004248 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004250 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004251 0, /* tp_print */
4252 0, /* tp_getattr */
4253 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00004254 0, /* tp_reserved */
Mark Dickinson2031d132009-09-17 00:17:48 +00004255 long_to_decimal_string, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004256 &long_as_number, /* tp_as_number */
4257 0, /* tp_as_sequence */
4258 0, /* tp_as_mapping */
4259 (hashfunc)long_hash, /* tp_hash */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004260 0, /* tp_call */
Mark Dickinson2031d132009-09-17 00:17:48 +00004261 long_to_decimal_string, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262 PyObject_GenericGetAttr, /* tp_getattro */
4263 0, /* tp_setattro */
4264 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00004265 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4266 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004267 long_doc, /* tp_doc */
4268 0, /* tp_traverse */
4269 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00004270 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004271 0, /* tp_weaklistoffset */
4272 0, /* tp_iter */
4273 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004274 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004275 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00004276 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004277 0, /* tp_base */
4278 0, /* tp_dict */
4279 0, /* tp_descr_get */
4280 0, /* tp_descr_set */
4281 0, /* tp_dictoffset */
4282 0, /* tp_init */
4283 0, /* tp_alloc */
4284 long_new, /* tp_new */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004285 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004286};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004287
Mark Dickinsonbd792642009-03-18 20:06:12 +00004288static PyTypeObject Int_InfoType;
4289
4290PyDoc_STRVAR(int_info__doc__,
4291"sys.int_info\n\
4292\n\
4293A struct sequence that holds information about Python's\n\
4294internal representation of integers. The attributes are read only.");
4295
4296static PyStructSequence_Field int_info_fields[] = {
4297 {"bits_per_digit", "size of a digit in bits"},
4298 {"sizeof_digit", "size in bytes of the C type used to "
4299 "represent a digit"},
4300 {NULL, NULL}
4301};
4302
4303static PyStructSequence_Desc int_info_desc = {
4304 "sys.int_info", /* name */
4305 int_info__doc__, /* doc */
4306 int_info_fields, /* fields */
4307 2 /* number of fields */
4308};
4309
4310PyObject *
4311PyLong_GetInfo(void)
4312{
4313 PyObject* int_info;
4314 int field = 0;
4315 int_info = PyStructSequence_New(&Int_InfoType);
4316 if (int_info == NULL)
4317 return NULL;
Mark Dickinson0bdab682009-04-02 18:41:40 +00004318 PyStructSequence_SET_ITEM(int_info, field++,
4319 PyLong_FromLong(PyLong_SHIFT));
4320 PyStructSequence_SET_ITEM(int_info, field++,
4321 PyLong_FromLong(sizeof(digit)));
Mark Dickinsonbd792642009-03-18 20:06:12 +00004322 if (PyErr_Occurred()) {
4323 Py_CLEAR(int_info);
4324 return NULL;
4325 }
4326 return int_info;
4327}
4328
Guido van Rossumddefaf32007-01-14 03:31:43 +00004329int
4330_PyLong_Init(void)
4331{
4332#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004333 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004334 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004335
4336 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4337 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4338 if (Py_TYPE(v) == &PyLong_Type) {
4339 /* The element is already initialized, most likely
4340 * the Python interpreter was initialized before.
4341 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00004342 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004343 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004344
Christian Heimes48aa4b12008-02-01 16:56:30 +00004345 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4346 _Py_NewReference(op);
4347 /* _Py_NewReference sets the ref count to 1 but
4348 * the ref count might be larger. Set the refcnt
4349 * to the original refcnt + 1 */
4350 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004351 assert(Py_SIZE(op) == size);
4352 assert(v->ob_digit[0] == abs(ival));
4353 }
4354 else {
4355 PyObject_INIT(v, &PyLong_Type);
4356 }
4357 Py_SIZE(v) = size;
4358 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004359 }
4360#endif
Mark Dickinsonbd792642009-03-18 20:06:12 +00004361 /* initialize int_info */
4362 if (Int_InfoType.tp_name == 0)
4363 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
4364
Guido van Rossumddefaf32007-01-14 03:31:43 +00004365 return 1;
4366}
4367
4368void
4369PyLong_Fini(void)
4370{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004371 /* Integers are currently statically allocated. Py_DECREF is not
4372 needed, but Python must forget about the reference or multiple
4373 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004374#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004375 int i;
4376 PyLongObject *v = small_ints;
4377 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4378 _Py_DEC_REFTOTAL;
4379 _Py_ForgetReference((PyObject*)v);
4380 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004381#endif
4382}