blob: 3e7ae04a48dd50eaa47ec8b2a8a1cfc9fa607335 [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) \
Skip Montanarod581d772002-09-03 20:10:45 +000099 if (--_Py_Ticker < 0) { \
100 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000101 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000102 }
103
Mark Dickinsonc6300392009-04-20 21:38:00 +0000104/* forward declaration */
105static int bits_in_digit(digit d);
106
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000107/* Normalize (remove leading zeros from) a long int object.
108 Doesn't attempt to free the storage--in most cases, due to the nature
109 of the algorithms used, this could save at most be one word anyway. */
110
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000112long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000113{
Christian Heimes90aa7642007-12-19 02:45:37 +0000114 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000115 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000116
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117 while (i > 0 && v->ob_digit[i-1] == 0)
118 --i;
119 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000120 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000121 return v;
122}
123
124/* Allocate a new long int object with size digits.
125 Return NULL and set exception if we run out of memory. */
126
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000127#define MAX_LONG_DIGITS \
128 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
129
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000131_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000132{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000133 PyLongObject *result;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000134 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
135 sizeof(digit)*size. Previous incarnations of this code used
136 sizeof(PyVarObject) instead of the offsetof, but this risks being
137 incorrect in the presence of padding between the PyVarObject header
138 and the digits. */
Mark Dickinsone4416742009-02-15 15:14:57 +0000139 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000140 PyErr_SetString(PyExc_OverflowError,
141 "too many digits in integer");
142 return NULL;
143 }
144 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
Guido van Rossumddefaf32007-01-14 03:31:43 +0000145 size*sizeof(digit));
146 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000147 PyErr_NoMemory();
148 return NULL;
149 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000150 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000151}
152
Tim Peters64b5ce32001-09-10 20:52:51 +0000153PyObject *
154_PyLong_Copy(PyLongObject *src)
155{
156 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000157 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000158
159 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000160 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000161 if (i < 0)
162 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000163 if (i < 2) {
Mark Dickinsone4416742009-02-15 15:14:57 +0000164 sdigit ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000165 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000166 ival = -ival;
167 CHECK_SMALL_INT(ival);
168 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000169 result = _PyLong_New(i);
170 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000171 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000172 while (--i >= 0)
173 result->ob_digit[i] = src->ob_digit[i];
174 }
175 return (PyObject *)result;
176}
177
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000178/* Create a new long int object from a C long int */
179
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000180PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000181PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000182{
Tim Petersce9de2f2001-06-14 04:56:19 +0000183 PyLongObject *v;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000184 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000185 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
186 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000187 int sign = 1;
188
189 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000190
191 if (ival < 0) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000192 /* negate: can't write this as abs_ival = -ival since that
193 invokes undefined behaviour when ival is LONG_MIN */
194 abs_ival = 0U-(unsigned long)ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000195 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000196 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000197 else {
198 abs_ival = (unsigned long)ival;
199 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000200
Mark Dickinsond4624c32009-01-24 15:02:35 +0000201 /* Fast path for single-digit ints */
202 if (!(abs_ival >> PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000203 v = _PyLong_New(1);
204 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000205 Py_SIZE(v) = sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000206 v->ob_digit[0] = Py_SAFE_DOWNCAST(
207 abs_ival, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000208 }
209 return (PyObject*)v;
210 }
211
Mark Dickinson249b8982009-04-27 19:41:00 +0000212#if PyLong_SHIFT==15
Guido van Rossumddefaf32007-01-14 03:31:43 +0000213 /* 2 digits */
Mark Dickinsond4624c32009-01-24 15:02:35 +0000214 if (!(abs_ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000215 v = _PyLong_New(2);
216 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000217 Py_SIZE(v) = 2*sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000218 v->ob_digit[0] = Py_SAFE_DOWNCAST(
219 abs_ival & PyLong_MASK, unsigned long, digit);
220 v->ob_digit[1] = Py_SAFE_DOWNCAST(
221 abs_ival >> PyLong_SHIFT, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000222 }
223 return (PyObject*)v;
224 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000225#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000226
227 /* Larger numbers: loop to determine number of digits */
Christian Heimesdae2a892008-04-19 00:55:37 +0000228 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000229 while (t) {
230 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000231 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000232 }
233 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000234 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000235 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000236 Py_SIZE(v) = ndigits*sign;
Christian Heimesdae2a892008-04-19 00:55:37 +0000237 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000238 while (t) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000239 *p++ = Py_SAFE_DOWNCAST(
240 t & PyLong_MASK, unsigned long, digit);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000241 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000242 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000243 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000245}
246
Guido van Rossum53756b11997-01-03 17:14:46 +0000247/* Create a new long int object from a C unsigned long int */
248
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000249PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000250PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000251{
Tim Petersce9de2f2001-06-14 04:56:19 +0000252 PyLongObject *v;
253 unsigned long t;
254 int ndigits = 0;
255
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000256 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000257 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000258 /* Count the number of Python digits. */
259 t = (unsigned long)ival;
260 while (t) {
261 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000262 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000263 }
264 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000265 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000266 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000267 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000268 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000269 *p++ = (digit)(ival & PyLong_MASK);
270 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000271 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000272 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000273 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000274}
275
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000276/* Create a new long int object from a C double */
277
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000278PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000279PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000280{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000281 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000282 double frac;
283 int i, ndig, expo, neg;
284 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000285 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000286 PyErr_SetString(PyExc_OverflowError,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000287 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000288 return NULL;
289 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000290 if (Py_IS_NAN(dval)) {
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000291 PyErr_SetString(PyExc_ValueError,
292 "cannot convert float NaN to integer");
Christian Heimes386cd1e2008-01-15 02:01:20 +0000293 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000294 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000295 if (dval < 0.0) {
296 neg = 1;
297 dval = -dval;
298 }
299 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
300 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000301 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000302 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000304 if (v == NULL)
305 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000306 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000307 for (i = ndig; --i >= 0; ) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000308 digit bits = (digit)frac;
309 v->ob_digit[i] = bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000310 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000311 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000312 }
313 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000314 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000315 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000316}
317
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
319 * anything about what happens when a signed integer operation overflows,
320 * and some compilers think they're doing you a favor by being "clever"
321 * then. The bit pattern for the largest postive signed long is
322 * (unsigned long)LONG_MAX, and for the smallest negative signed long
323 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
324 * However, some other compilers warn about applying unary minus to an
325 * unsigned operand. Hence the weird "0-".
326 */
327#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
328#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
329
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000330/* Get a C long int from a long int object.
331 Returns -1 and sets an error condition if overflow occurs. */
332
333long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000334PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000335{
Guido van Rossumf7531811998-05-26 14:33:37 +0000336 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000338 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000339 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000340 Py_ssize_t i;
341 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000342 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000343
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000344 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000345 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000346 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000347 return -1;
348 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000349
350 if (!PyLong_Check(vv)) {
351 PyNumberMethods *nb;
352 if ((nb = vv->ob_type->tp_as_number) == NULL ||
353 nb->nb_int == NULL) {
354 PyErr_SetString(PyExc_TypeError, "an integer is required");
355 return -1;
356 }
357 vv = (*nb->nb_int) (vv);
358 if (vv == NULL)
359 return -1;
360 do_decref = 1;
361 if (!PyLong_Check(vv)) {
362 Py_DECREF(vv);
363 PyErr_SetString(PyExc_TypeError,
364 "nb_int should return int object");
365 return -1;
366 }
367 }
368
Georg Brandl61c31b02007-02-26 14:46:30 +0000369 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000371 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000372
Georg Brandl61c31b02007-02-26 14:46:30 +0000373 switch (i) {
374 case -1:
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000375 res = -(sdigit)v->ob_digit[0];
Georg Brandl61c31b02007-02-26 14:46:30 +0000376 break;
377 case 0:
378 res = 0;
379 break;
380 case 1:
381 res = v->ob_digit[0];
382 break;
383 default:
384 sign = 1;
385 x = 0;
386 if (i < 0) {
387 sign = -1;
388 i = -(i);
389 }
390 while (--i >= 0) {
391 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000392 x = (x << PyLong_SHIFT) + v->ob_digit[i];
393 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000394 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000395 goto exit;
396 }
397 }
398 /* Haven't lost any bits, but casting to long requires extra care
399 * (see comment above).
400 */
401 if (x <= (unsigned long)LONG_MAX) {
402 res = (long)x * sign;
403 }
404 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
405 res = LONG_MIN;
406 }
407 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000408 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000409 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000410 }
411 }
412 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000413 if (do_decref) {
414 Py_DECREF(vv);
415 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000416 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000417}
418
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000419long
420PyLong_AsLong(PyObject *obj)
421{
422 int overflow;
423 long result = PyLong_AsLongAndOverflow(obj, &overflow);
424 if (overflow) {
425 /* XXX: could be cute and give a different
426 message for overflow == -1 */
427 PyErr_SetString(PyExc_OverflowError,
428 "Python int too large to convert to C long");
429 }
430 return result;
431}
432
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000433/* Get a Py_ssize_t from a long int object.
434 Returns -1 and sets an error condition if overflow occurs. */
435
436Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000437PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000438 register PyLongObject *v;
439 size_t x, prev;
440 Py_ssize_t i;
441 int sign;
442
443 if (vv == NULL || !PyLong_Check(vv)) {
444 PyErr_BadInternalCall();
445 return -1;
446 }
447 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000448 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000449 switch (i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000450 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +0000451 case 0: return 0;
452 case 1: return v->ob_digit[0];
453 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000454 sign = 1;
455 x = 0;
456 if (i < 0) {
457 sign = -1;
458 i = -(i);
459 }
460 while (--i >= 0) {
461 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000462 x = (x << PyLong_SHIFT) + v->ob_digit[i];
463 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000464 goto overflow;
465 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466 /* Haven't lost any bits, but casting to a signed type requires
467 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000469 if (x <= (size_t)PY_SSIZE_T_MAX) {
470 return (Py_ssize_t)x * sign;
471 }
472 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
473 return PY_SSIZE_T_MIN;
474 }
475 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000476
477 overflow:
478 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000479 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000480 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000481}
482
Guido van Rossumd8c80482002-08-13 00:24:58 +0000483/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000484 Returns -1 and sets an error condition if overflow occurs. */
485
486unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000487PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000488{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000490 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000491 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000492
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493 if (vv == NULL || !PyLong_Check(vv)) {
494 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000495 return (unsigned long) -1;
496 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000497 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000498 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000499 x = 0;
500 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000501 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000502 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000503 return (unsigned long) -1;
504 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000505 switch (i) {
506 case 0: return 0;
507 case 1: return v->ob_digit[0];
508 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000509 while (--i >= 0) {
510 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000511 x = (x << PyLong_SHIFT) + v->ob_digit[i];
512 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000513 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000514 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000515 return (unsigned long) -1;
516 }
517 }
518 return x;
519}
520
521/* Get a C unsigned long int from a long int object.
522 Returns -1 and sets an error condition if overflow occurs. */
523
524size_t
525PyLong_AsSize_t(PyObject *vv)
526{
527 register PyLongObject *v;
528 size_t x, prev;
529 Py_ssize_t i;
530
531 if (vv == NULL || !PyLong_Check(vv)) {
532 PyErr_BadInternalCall();
533 return (unsigned long) -1;
534 }
535 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000536 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000537 x = 0;
538 if (i < 0) {
539 PyErr_SetString(PyExc_OverflowError,
540 "can't convert negative value to size_t");
541 return (size_t) -1;
542 }
543 switch (i) {
544 case 0: return 0;
545 case 1: return v->ob_digit[0];
546 }
547 while (--i >= 0) {
548 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000549 x = (x << PyLong_SHIFT) + v->ob_digit[i];
550 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000551 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000552 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000553 return (unsigned long) -1;
554 }
555 }
556 return x;
557}
558
Thomas Hellera4ea6032003-04-17 18:55:45 +0000559/* Get a C unsigned long int from a long int object, ignoring the high bits.
560 Returns -1 and sets an error condition if an error occurs. */
561
Guido van Rossumddefaf32007-01-14 03:31:43 +0000562static unsigned long
563_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000564{
565 register PyLongObject *v;
566 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000567 Py_ssize_t i;
568 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000569
570 if (vv == NULL || !PyLong_Check(vv)) {
571 PyErr_BadInternalCall();
572 return (unsigned long) -1;
573 }
574 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000575 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000576 switch (i) {
577 case 0: return 0;
578 case 1: return v->ob_digit[0];
579 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000580 sign = 1;
581 x = 0;
582 if (i < 0) {
583 sign = -1;
584 i = -i;
585 }
586 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000587 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000588 }
589 return x * sign;
590}
591
Guido van Rossumddefaf32007-01-14 03:31:43 +0000592unsigned long
593PyLong_AsUnsignedLongMask(register PyObject *op)
594{
595 PyNumberMethods *nb;
596 PyLongObject *lo;
597 unsigned long val;
598
599 if (op && PyLong_Check(op))
600 return _PyLong_AsUnsignedLongMask(op);
601
602 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
603 nb->nb_int == NULL) {
604 PyErr_SetString(PyExc_TypeError, "an integer is required");
605 return (unsigned long)-1;
606 }
607
608 lo = (PyLongObject*) (*nb->nb_int) (op);
609 if (lo == NULL)
610 return (unsigned long)-1;
611 if (PyLong_Check(lo)) {
612 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
613 Py_DECREF(lo);
614 if (PyErr_Occurred())
615 return (unsigned long)-1;
616 return val;
617 }
618 else
619 {
620 Py_DECREF(lo);
621 PyErr_SetString(PyExc_TypeError,
622 "nb_int should return int object");
623 return (unsigned long)-1;
624 }
625}
626
Tim Peters5b8132f2003-01-31 15:52:05 +0000627int
628_PyLong_Sign(PyObject *vv)
629{
630 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000631
632 assert(v != NULL);
633 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000634
Christian Heimes90aa7642007-12-19 02:45:37 +0000635 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000636}
637
Tim Petersbaefd9e2003-01-28 20:37:45 +0000638size_t
639_PyLong_NumBits(PyObject *vv)
640{
641 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000642 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000643 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000644
645 assert(v != NULL);
646 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000647 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000648 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
649 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000650 digit msd = v->ob_digit[ndigits - 1];
651
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000652 result = (ndigits - 1) * PyLong_SHIFT;
653 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000654 goto Overflow;
655 do {
656 ++result;
657 if (result == 0)
658 goto Overflow;
659 msd >>= 1;
660 } while (msd);
661 }
662 return result;
663
664Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000665 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000666 "to express in a platform size_t");
667 return (size_t)-1;
668}
669
Tim Peters2a9b3672001-06-11 21:23:58 +0000670PyObject *
671_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
672 int little_endian, int is_signed)
673{
674 const unsigned char* pstartbyte;/* LSB of bytes */
675 int incr; /* direction to move pstartbyte */
676 const unsigned char* pendbyte; /* MSB of bytes */
677 size_t numsignificantbytes; /* number of bytes that matter */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000678 Py_ssize_t ndigits; /* number of Python long digits */
Tim Peters2a9b3672001-06-11 21:23:58 +0000679 PyLongObject* v; /* result */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000680 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000681
682 if (n == 0)
683 return PyLong_FromLong(0L);
684
685 if (little_endian) {
686 pstartbyte = bytes;
687 pendbyte = bytes + n - 1;
688 incr = 1;
689 }
690 else {
691 pstartbyte = bytes + n - 1;
692 pendbyte = bytes;
693 incr = -1;
694 }
695
696 if (is_signed)
697 is_signed = *pendbyte >= 0x80;
698
699 /* Compute numsignificantbytes. This consists of finding the most
700 significant byte. Leading 0 bytes are insignficant if the number
701 is positive, and leading 0xff bytes if negative. */
702 {
703 size_t i;
704 const unsigned char* p = pendbyte;
705 const int pincr = -incr; /* search MSB to LSB */
706 const unsigned char insignficant = is_signed ? 0xff : 0x00;
707
708 for (i = 0; i < n; ++i, p += pincr) {
709 if (*p != insignficant)
710 break;
711 }
712 numsignificantbytes = n - i;
713 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
714 actually has 2 significant bytes. OTOH, 0xff0001 ==
715 -0x00ffff, so we wouldn't *need* to bump it there; but we
716 do for 0xffff = -0x0001. To be safe without bothering to
717 check every case, bump it regardless. */
718 if (is_signed && numsignificantbytes < n)
719 ++numsignificantbytes;
720 }
721
722 /* How many Python long digits do we need? We have
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000723 8*numsignificantbytes bits, and each Python long digit has
724 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
725 /* catch overflow before it happens */
726 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
727 PyErr_SetString(PyExc_OverflowError,
728 "byte array too long to convert to int");
729 return NULL;
730 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000731 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000732 v = _PyLong_New(ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000733 if (v == NULL)
734 return NULL;
735
736 /* Copy the bits over. The tricky parts are computing 2's-comp on
737 the fly for signed numbers, and dealing with the mismatch between
738 8-bit bytes and (probably) 15-bit Python digits.*/
739 {
740 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000741 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000742 twodigits accum = 0; /* sliding register */
743 unsigned int accumbits = 0; /* number of bits in accum */
744 const unsigned char* p = pstartbyte;
745
746 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000747 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000748 /* Compute correction for 2's comp, if needed. */
749 if (is_signed) {
750 thisbyte = (0xff ^ thisbyte) + carry;
751 carry = thisbyte >> 8;
752 thisbyte &= 0xff;
753 }
754 /* Because we're going LSB to MSB, thisbyte is
755 more significant than what's already in accum,
756 so needs to be prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000757 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000758 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000759 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000760 /* There's enough to fill a Python digit. */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000761 assert(idigit < ndigits);
762 v->ob_digit[idigit] = (digit)(accum &
763 PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000764 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000765 accum >>= PyLong_SHIFT;
766 accumbits -= PyLong_SHIFT;
767 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000768 }
769 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000770 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000771 if (accumbits) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000772 assert(idigit < ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000773 v->ob_digit[idigit] = (digit)accum;
774 ++idigit;
775 }
776 }
777
Christian Heimes90aa7642007-12-19 02:45:37 +0000778 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000779 return (PyObject *)long_normalize(v);
780}
781
782int
783_PyLong_AsByteArray(PyLongObject* v,
784 unsigned char* bytes, size_t n,
785 int little_endian, int is_signed)
786{
Mark Dickinson17e55872009-01-24 15:56:57 +0000787 Py_ssize_t i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000788 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000789 twodigits accum; /* sliding register */
790 unsigned int accumbits; /* # bits in accum */
791 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
Mark Dickinson1e2d8702009-01-25 22:25:06 +0000792 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000793 size_t j; /* # bytes filled */
794 unsigned char* p; /* pointer to next byte in bytes */
795 int pincr; /* direction to move p */
796
797 assert(v != NULL && PyLong_Check(v));
798
Christian Heimes90aa7642007-12-19 02:45:37 +0000799 if (Py_SIZE(v) < 0) {
800 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000801 if (!is_signed) {
Mark Dickinson21776072009-02-10 16:13:25 +0000802 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000803 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000804 return -1;
805 }
806 do_twos_comp = 1;
807 }
808 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000809 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000810 do_twos_comp = 0;
811 }
812
813 if (little_endian) {
814 p = bytes;
815 pincr = 1;
816 }
817 else {
818 p = bytes + n - 1;
819 pincr = -1;
820 }
821
Tim Peters898cf852001-06-13 20:50:08 +0000822 /* Copy over all the Python digits.
823 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000824 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000825 normalized. */
826 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000827 j = 0;
828 accum = 0;
829 accumbits = 0;
830 carry = do_twos_comp ? 1 : 0;
831 for (i = 0; i < ndigits; ++i) {
Mark Dickinson17e55872009-01-24 15:56:57 +0000832 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000833 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000834 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
835 carry = thisdigit >> PyLong_SHIFT;
836 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000837 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000838 /* Because we're going LSB to MSB, thisdigit is more
839 significant than what's already in accum, so needs to be
840 prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000841 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000842
Tim Petersede05092001-06-14 08:53:38 +0000843 /* The most-significant digit may be (probably is) at least
844 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000845 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000846 /* Count # of sign bits -- they needn't be stored,
847 * although for signed conversion we need later to
Mark Dickinson17e55872009-01-24 15:56:57 +0000848 * make sure at least one sign bit gets stored. */
849 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
850 thisdigit;
851 while (s != 0) {
852 s >>= 1;
853 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000854 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000855 }
Mark Dickinson17e55872009-01-24 15:56:57 +0000856 else
857 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000858
Tim Peters2a9b3672001-06-11 21:23:58 +0000859 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000860 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000861 if (j >= n)
862 goto Overflow;
863 ++j;
864 *p = (unsigned char)(accum & 0xff);
865 p += pincr;
866 accumbits -= 8;
867 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000868 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000869 }
870
871 /* Store the straggler (if any). */
872 assert(accumbits < 8);
873 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000874 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000875 if (j >= n)
876 goto Overflow;
877 ++j;
878 if (do_twos_comp) {
879 /* Fill leading bits of the byte with sign bits
880 (appropriately pretending that the long had an
881 infinite supply of sign bits). */
882 accum |= (~(twodigits)0) << accumbits;
883 }
884 *p = (unsigned char)(accum & 0xff);
885 p += pincr;
886 }
Tim Peters05607ad2001-06-13 21:01:27 +0000887 else if (j == n && n > 0 && is_signed) {
888 /* The main loop filled the byte array exactly, so the code
889 just above didn't get to ensure there's a sign bit, and the
890 loop below wouldn't add one either. Make sure a sign bit
891 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000892 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000893 int sign_bit_set = msb >= 0x80;
894 assert(accumbits == 0);
895 if (sign_bit_set == do_twos_comp)
896 return 0;
897 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000898 goto Overflow;
899 }
Tim Peters05607ad2001-06-13 21:01:27 +0000900
901 /* Fill remaining bytes with copies of the sign bit. */
902 {
903 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
904 for ( ; j < n; ++j, p += pincr)
905 *p = signbyte;
906 }
907
Tim Peters2a9b3672001-06-11 21:23:58 +0000908 return 0;
909
910Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000911 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000912 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000913
Tim Peters2a9b3672001-06-11 21:23:58 +0000914}
915
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000916double
917_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
918{
919/* NBITS_WANTED should be > the number of bits in a double's precision,
920 but small enough so that 2**NBITS_WANTED is within the normal double
921 range. nbitsneeded is set to 1 less than that because the most-significant
922 Python digit contains at least 1 significant bit, but we don't want to
923 bother counting them (catering to the worst case cheaply).
924
925 57 is one more than VAX-D double precision; I (Tim) don't know of a double
926 format with more precision than that; it's 1 larger so that we add in at
927 least one round bit to stand in for the ignored least-significant bits.
928*/
929#define NBITS_WANTED 57
930 PyLongObject *v;
931 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000932 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000933 Py_ssize_t i;
934 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000935 int nbitsneeded;
936
937 if (vv == NULL || !PyLong_Check(vv)) {
938 PyErr_BadInternalCall();
939 return -1;
940 }
941 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000942 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000943 sign = 1;
944 if (i < 0) {
945 sign = -1;
946 i = -(i);
947 }
948 else if (i == 0) {
949 *exponent = 0;
950 return 0.0;
951 }
952 --i;
953 x = (double)v->ob_digit[i];
954 nbitsneeded = NBITS_WANTED - 1;
955 /* Invariant: i Python digits remain unaccounted for. */
956 while (i > 0 && nbitsneeded > 0) {
957 --i;
958 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000959 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000960 }
961 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000962 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000963 *exponent = i;
964 assert(x > 0.0);
965 return x * sign;
966#undef NBITS_WANTED
967}
968
Mark Dickinsonc6300392009-04-20 21:38:00 +0000969/* Get a C double from a long int object. Rounds to the nearest double,
970 using the round-half-to-even rule in the case of a tie. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000971
972double
Tim Peters9f688bf2000-07-07 15:53:28 +0000973PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000974{
Mark Dickinsonc6300392009-04-20 21:38:00 +0000975 PyLongObject *v = (PyLongObject *)vv;
976 Py_ssize_t rnd_digit, rnd_bit, m, n;
977 digit lsb, *d;
978 int round_up = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000979 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000980
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000981 if (vv == NULL || !PyLong_Check(vv)) {
982 PyErr_BadInternalCall();
Tim Peters9fffa3e2001-09-04 05:14:19 +0000983 return -1.0;
Mark Dickinsonc6300392009-04-20 21:38:00 +0000984 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000985
Mark Dickinsonc6300392009-04-20 21:38:00 +0000986 /* Notes on the method: for simplicity, assume v is positive and >=
987 2**DBL_MANT_DIG. (For negative v we just ignore the sign until the
988 end; for small v no rounding is necessary.) Write n for the number
989 of bits in v, so that 2**(n-1) <= v < 2**n, and n > DBL_MANT_DIG.
990
991 Some terminology: the *rounding bit* of v is the 1st bit of v that
992 will be rounded away (bit n - DBL_MANT_DIG - 1); the *parity bit*
993 is the bit immediately above. The round-half-to-even rule says
994 that we round up if the rounding bit is set, unless v is exactly
995 halfway between two floats and the parity bit is zero.
996
997 Write d[0] ... d[m] for the digits of v, least to most significant.
998 Let rnd_bit be the index of the rounding bit, and rnd_digit the
999 index of the PyLong digit containing the rounding bit. Then the
1000 bits of the digit d[rnd_digit] look something like:
1001
1002 rounding bit
1003 |
1004 v
1005 msb -> sssssrttttttttt <- lsb
1006 ^
1007 |
1008 parity bit
1009
1010 where 's' represents a 'significant bit' that will be included in
1011 the mantissa of the result, 'r' is the rounding bit, and 't'
1012 represents a 'trailing bit' following the rounding bit. Note that
1013 if the rounding bit is at the top of d[rnd_digit] then the parity
1014 bit will be the lsb of d[rnd_digit+1]. If we set
1015
1016 lsb = 1 << (rnd_bit % PyLong_SHIFT)
1017
1018 then d[rnd_digit] & (PyLong_BASE - 2*lsb) selects just the
1019 significant bits of d[rnd_digit], d[rnd_digit] & (lsb-1) gets the
1020 trailing bits, and d[rnd_digit] & lsb gives the rounding bit.
1021
1022 We initialize the double x to the integer given by digits
1023 d[rnd_digit:m-1], but with the rounding bit and trailing bits of
1024 d[rnd_digit] masked out. So the value of x comes from the top
1025 DBL_MANT_DIG bits of v, multiplied by 2*lsb. Note that in the loop
1026 that produces x, all floating-point operations are exact (assuming
1027 that FLT_RADIX==2). Now if we're rounding down, the value we want
1028 to return is simply
1029
1030 x * 2**(PyLong_SHIFT * rnd_digit).
1031
1032 and if we're rounding up, it's
1033
1034 (x + 2*lsb) * 2**(PyLong_SHIFT * rnd_digit).
1035
1036 Under the round-half-to-even rule, we round up if, and only
1037 if, the rounding bit is set *and* at least one of the
1038 following three conditions is satisfied:
1039
1040 (1) the parity bit is set, or
1041 (2) at least one of the trailing bits of d[rnd_digit] is set, or
1042 (3) at least one of the digits d[i], 0 <= i < rnd_digit
1043 is nonzero.
1044
1045 Finally, we have to worry about overflow. If v >= 2**DBL_MAX_EXP,
1046 or equivalently n > DBL_MAX_EXP, then overflow occurs. If v <
1047 2**DBL_MAX_EXP then we're usually safe, but there's a corner case
1048 to consider: if v is very close to 2**DBL_MAX_EXP then it's
1049 possible that v is rounded up to exactly 2**DBL_MAX_EXP, and then
1050 again overflow occurs.
1051 */
1052
1053 if (Py_SIZE(v) == 0)
1054 return 0.0;
1055 m = ABS(Py_SIZE(v)) - 1;
1056 d = v->ob_digit;
1057 assert(d[m]); /* v should be normalized */
1058
1059 /* fast path for case where 0 < abs(v) < 2**DBL_MANT_DIG */
1060 if (m < DBL_MANT_DIG / PyLong_SHIFT ||
1061 (m == DBL_MANT_DIG / PyLong_SHIFT &&
1062 d[m] < (digit)1 << DBL_MANT_DIG%PyLong_SHIFT)) {
1063 x = d[m];
1064 while (--m >= 0)
1065 x = x*PyLong_BASE + d[m];
1066 return Py_SIZE(v) < 0 ? -x : x;
1067 }
1068
1069 /* if m is huge then overflow immediately; otherwise, compute the
1070 number of bits n in v. The condition below implies n (= #bits) >=
1071 m * PyLong_SHIFT + 1 > DBL_MAX_EXP, hence v >= 2**DBL_MAX_EXP. */
1072 if (m > (DBL_MAX_EXP-1)/PyLong_SHIFT)
1073 goto overflow;
1074 n = m * PyLong_SHIFT + bits_in_digit(d[m]);
1075 if (n > DBL_MAX_EXP)
1076 goto overflow;
1077
1078 /* find location of rounding bit */
1079 assert(n > DBL_MANT_DIG); /* dealt with |v| < 2**DBL_MANT_DIG above */
1080 rnd_bit = n - DBL_MANT_DIG - 1;
1081 rnd_digit = rnd_bit/PyLong_SHIFT;
1082 lsb = (digit)1 << (rnd_bit%PyLong_SHIFT);
1083
1084 /* Get top DBL_MANT_DIG bits of v. Assumes PyLong_SHIFT <
1085 DBL_MANT_DIG, so we'll need bits from at least 2 digits of v. */
1086 x = d[m];
1087 assert(m > rnd_digit);
1088 while (--m > rnd_digit)
1089 x = x*PyLong_BASE + d[m];
1090 x = x*PyLong_BASE + (d[m] & (PyLong_BASE-2*lsb));
1091
1092 /* decide whether to round up, using round-half-to-even */
1093 assert(m == rnd_digit);
1094 if (d[m] & lsb) { /* if (rounding bit is set) */
1095 digit parity_bit;
1096 if (lsb == PyLong_BASE/2)
1097 parity_bit = d[m+1] & 1;
1098 else
1099 parity_bit = d[m] & 2*lsb;
1100 if (parity_bit)
1101 round_up = 1;
1102 else if (d[m] & (lsb-1))
1103 round_up = 1;
1104 else {
1105 while (--m >= 0) {
1106 if (d[m]) {
1107 round_up = 1;
1108 break;
1109 }
1110 }
1111 }
1112 }
1113
1114 /* and round up if necessary */
1115 if (round_up) {
1116 x += 2*lsb;
1117 if (n == DBL_MAX_EXP &&
1118 x == ldexp((double)(2*lsb), DBL_MANT_DIG)) {
1119 /* overflow corner case */
1120 goto overflow;
1121 }
1122 }
1123
1124 /* shift, adjust for sign, and return */
1125 x = ldexp(x, rnd_digit*PyLong_SHIFT);
1126 return Py_SIZE(v) < 0 ? -x : x;
1127
1128 overflow:
Tim Peters9fffa3e2001-09-04 05:14:19 +00001129 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +00001130 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +00001131 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001132}
1133
Guido van Rossum78694d91998-09-18 14:14:13 +00001134/* Create a new long (or int) object from a C pointer */
1135
1136PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001137PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001138{
Tim Peters70128a12001-06-16 08:48:40 +00001139#ifndef HAVE_LONG_LONG
1140# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1141#endif
1142#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001143# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001144#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +00001145 /* special-case null pointer */
1146 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +00001147 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001148 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +00001149
Guido van Rossum78694d91998-09-18 14:14:13 +00001150}
1151
1152/* Get a C pointer from a long object (or an int object in some cases) */
1153
1154void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001155PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001156{
1157 /* This function will allow int or long objects. If vv is neither,
1158 then the PyLong_AsLong*() functions will raise the exception:
1159 PyExc_SystemError, "bad argument to internal function"
1160 */
Tim Peters70128a12001-06-16 08:48:40 +00001161#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001162 long x;
1163
Guido van Rossumddefaf32007-01-14 03:31:43 +00001164 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001165 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001166 else
1167 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001168#else
Tim Peters70128a12001-06-16 08:48:40 +00001169
1170#ifndef HAVE_LONG_LONG
1171# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1172#endif
1173#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001174# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001175#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001176 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001177
Guido van Rossumddefaf32007-01-14 03:31:43 +00001178 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001179 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001180 else
1181 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001182
1183#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001184
1185 if (x == -1 && PyErr_Occurred())
1186 return NULL;
1187 return (void *)x;
1188}
1189
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001190#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001191
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001192/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001193 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001194 */
1195
Tim Peterscf37dfc2001-06-14 18:42:50 +00001196#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001197
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001198/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001199
1200PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001201PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001202{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001203 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +00001204 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001205 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1206 int ndigits = 0;
1207 int negative = 0;
1208
Guido van Rossumddefaf32007-01-14 03:31:43 +00001209 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001210 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +00001211 /* avoid signed overflow on negation; see comments
1212 in PyLong_FromLong above. */
1213 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001214 negative = 1;
1215 }
Christian Heimesdae2a892008-04-19 00:55:37 +00001216 else {
1217 abs_ival = (unsigned PY_LONG_LONG)ival;
1218 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001219
1220 /* Count the number of Python digits.
1221 We used to pick 5 ("big enough for anything"), but that's a
1222 waste of time and space given that 5*15 = 75 bits are rarely
1223 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001224 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001225 while (t) {
1226 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001227 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001228 }
1229 v = _PyLong_New(ndigits);
1230 if (v != NULL) {
1231 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001232 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001233 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001234 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001235 *p++ = (digit)(t & PyLong_MASK);
1236 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001237 }
1238 }
1239 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001240}
1241
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001242/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001243
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001244PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001245PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001246{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001247 PyLongObject *v;
1248 unsigned PY_LONG_LONG t;
1249 int ndigits = 0;
1250
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001251 if (ival < PyLong_BASE)
Mark Dickinson50b2b6e2008-12-05 17:14:29 +00001252 return PyLong_FromLong((long)ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001253 /* Count the number of Python digits. */
1254 t = (unsigned PY_LONG_LONG)ival;
1255 while (t) {
1256 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001257 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001258 }
1259 v = _PyLong_New(ndigits);
1260 if (v != NULL) {
1261 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001262 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001263 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001264 *p++ = (digit)(ival & PyLong_MASK);
1265 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001266 }
1267 }
1268 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001269}
1270
Martin v. Löwis18e16552006-02-15 17:27:45 +00001271/* Create a new long int object from a C Py_ssize_t. */
1272
1273PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001274PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001275{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001276 PyLongObject *v;
1277 size_t abs_ival;
1278 size_t t; /* unsigned so >> doesn't propagate sign bit */
1279 int ndigits = 0;
1280 int negative = 0;
1281
1282 CHECK_SMALL_INT(ival);
1283 if (ival < 0) {
1284 /* avoid signed overflow when ival = SIZE_T_MIN */
1285 abs_ival = (size_t)(-1-ival)+1;
1286 negative = 1;
1287 }
1288 else {
1289 abs_ival = (size_t)ival;
1290 }
1291
1292 /* Count the number of Python digits. */
1293 t = abs_ival;
1294 while (t) {
1295 ++ndigits;
1296 t >>= PyLong_SHIFT;
1297 }
1298 v = _PyLong_New(ndigits);
1299 if (v != NULL) {
1300 digit *p = v->ob_digit;
1301 Py_SIZE(v) = negative ? -ndigits : ndigits;
1302 t = abs_ival;
1303 while (t) {
1304 *p++ = (digit)(t & PyLong_MASK);
1305 t >>= PyLong_SHIFT;
1306 }
1307 }
1308 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001309}
1310
1311/* Create a new long int object from a C size_t. */
1312
1313PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001314PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001315{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001316 PyLongObject *v;
1317 size_t t;
1318 int ndigits = 0;
1319
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001320 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001321 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001322 /* Count the number of Python digits. */
1323 t = ival;
1324 while (t) {
1325 ++ndigits;
1326 t >>= PyLong_SHIFT;
1327 }
1328 v = _PyLong_New(ndigits);
1329 if (v != NULL) {
1330 digit *p = v->ob_digit;
1331 Py_SIZE(v) = ndigits;
1332 while (ival) {
1333 *p++ = (digit)(ival & PyLong_MASK);
1334 ival >>= PyLong_SHIFT;
1335 }
1336 }
1337 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001338}
1339
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001340/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001341 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001342
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001343PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001344PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001345{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001346 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001347 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001348 int one = 1;
1349 int res;
1350
Tim Petersd38b1c72001-09-30 05:09:37 +00001351 if (vv == NULL) {
1352 PyErr_BadInternalCall();
1353 return -1;
1354 }
1355 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001356 PyNumberMethods *nb;
1357 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001358 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1359 nb->nb_int == NULL) {
1360 PyErr_SetString(PyExc_TypeError, "an integer is required");
1361 return -1;
1362 }
1363 io = (*nb->nb_int) (vv);
1364 if (io == NULL)
1365 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001366 if (PyLong_Check(io)) {
1367 bytes = PyLong_AsLongLong(io);
1368 Py_DECREF(io);
1369 return bytes;
1370 }
1371 Py_DECREF(io);
1372 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001373 return -1;
1374 }
1375
Guido van Rossumddefaf32007-01-14 03:31:43 +00001376 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001377 switch(Py_SIZE(v)) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00001378 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00001379 case 0: return 0;
1380 case 1: return v->ob_digit[0];
1381 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001382 res = _PyLong_AsByteArray(
1383 (PyLongObject *)vv, (unsigned char *)&bytes,
1384 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001385
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001386 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001387 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001388 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001389 else
1390 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001391}
1392
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001393/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001394 Return -1 and set an error if overflow occurs. */
1395
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001396unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001397PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001398{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001399 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001400 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001401 int one = 1;
1402 int res;
1403
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001404 if (vv == NULL || !PyLong_Check(vv)) {
1405 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001406 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001407 }
1408
Guido van Rossumddefaf32007-01-14 03:31:43 +00001409 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001410 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001411 case 0: return 0;
1412 case 1: return v->ob_digit[0];
1413 }
1414
Tim Petersd1a7da62001-06-13 00:35:57 +00001415 res = _PyLong_AsByteArray(
1416 (PyLongObject *)vv, (unsigned char *)&bytes,
1417 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001418
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001419 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001420 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001421 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001422 else
1423 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001424}
Tim Petersd1a7da62001-06-13 00:35:57 +00001425
Thomas Hellera4ea6032003-04-17 18:55:45 +00001426/* Get a C unsigned long int from a long int object, ignoring the high bits.
1427 Returns -1 and sets an error condition if an error occurs. */
1428
Guido van Rossumddefaf32007-01-14 03:31:43 +00001429static unsigned PY_LONG_LONG
1430_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001431{
1432 register PyLongObject *v;
1433 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001434 Py_ssize_t i;
1435 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001436
1437 if (vv == NULL || !PyLong_Check(vv)) {
1438 PyErr_BadInternalCall();
1439 return (unsigned long) -1;
1440 }
1441 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001442 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001443 case 0: return 0;
1444 case 1: return v->ob_digit[0];
1445 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001446 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001447 sign = 1;
1448 x = 0;
1449 if (i < 0) {
1450 sign = -1;
1451 i = -i;
1452 }
1453 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001454 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001455 }
1456 return x * sign;
1457}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001458
1459unsigned PY_LONG_LONG
1460PyLong_AsUnsignedLongLongMask(register PyObject *op)
1461{
1462 PyNumberMethods *nb;
1463 PyLongObject *lo;
1464 unsigned PY_LONG_LONG val;
1465
1466 if (op && PyLong_Check(op))
1467 return _PyLong_AsUnsignedLongLongMask(op);
1468
1469 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1470 nb->nb_int == NULL) {
1471 PyErr_SetString(PyExc_TypeError, "an integer is required");
1472 return (unsigned PY_LONG_LONG)-1;
1473 }
1474
1475 lo = (PyLongObject*) (*nb->nb_int) (op);
1476 if (lo == NULL)
1477 return (unsigned PY_LONG_LONG)-1;
1478 if (PyLong_Check(lo)) {
1479 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1480 Py_DECREF(lo);
1481 if (PyErr_Occurred())
1482 return (unsigned PY_LONG_LONG)-1;
1483 return val;
1484 }
1485 else
1486 {
1487 Py_DECREF(lo);
1488 PyErr_SetString(PyExc_TypeError,
1489 "nb_int should return int object");
1490 return (unsigned PY_LONG_LONG)-1;
1491 }
1492}
Tim Petersd1a7da62001-06-13 00:35:57 +00001493#undef IS_LITTLE_ENDIAN
1494
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001495#endif /* HAVE_LONG_LONG */
1496
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001497#define CHECK_BINOP(v,w) \
1498 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001499 Py_INCREF(Py_NotImplemented); \
1500 return Py_NotImplemented; \
1501 }
1502
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001503/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1504 2**k if d is nonzero, else 0. */
1505
1506static const unsigned char BitLengthTable[32] = {
1507 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1508 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1509};
1510
1511static int
1512bits_in_digit(digit d)
1513{
1514 int d_bits = 0;
1515 while (d >= 32) {
1516 d_bits += 6;
1517 d >>= 6;
1518 }
1519 d_bits += (int)BitLengthTable[d];
1520 return d_bits;
1521}
1522
Tim Peters877a2122002-08-12 05:09:36 +00001523/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1524 * is modified in place, by adding y to it. Carries are propagated as far as
1525 * x[m-1], and the remaining carry (0 or 1) is returned.
1526 */
1527static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001528v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001529{
Mark Dickinson17e55872009-01-24 15:56:57 +00001530 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001531 digit carry = 0;
1532
1533 assert(m >= n);
1534 for (i = 0; i < n; ++i) {
1535 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001536 x[i] = carry & PyLong_MASK;
1537 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001538 assert((carry & 1) == carry);
1539 }
1540 for (; carry && i < m; ++i) {
1541 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001542 x[i] = carry & PyLong_MASK;
1543 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001544 assert((carry & 1) == carry);
1545 }
1546 return carry;
1547}
1548
1549/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1550 * is modified in place, by subtracting y from it. Borrows are propagated as
1551 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1552 */
1553static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001554v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001555{
Mark Dickinson17e55872009-01-24 15:56:57 +00001556 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001557 digit borrow = 0;
1558
1559 assert(m >= n);
1560 for (i = 0; i < n; ++i) {
1561 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001562 x[i] = borrow & PyLong_MASK;
1563 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001564 borrow &= 1; /* keep only 1 sign bit */
1565 }
1566 for (; borrow && i < m; ++i) {
1567 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001568 x[i] = borrow & PyLong_MASK;
1569 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001570 borrow &= 1;
1571 }
1572 return borrow;
1573}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001574
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001575/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1576 * result in z[0:m], and return the d bits shifted out of the top.
1577 */
1578static digit
1579v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001580{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001581 Py_ssize_t i;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001582 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001583
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001584 assert(0 <= d && d < PyLong_SHIFT);
1585 for (i=0; i < m; i++) {
1586 twodigits acc = (twodigits)a[i] << d | carry;
1587 z[i] = (digit)acc & PyLong_MASK;
1588 carry = (digit)(acc >> PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001589 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001590 return carry;
1591}
1592
1593/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1594 * result in z[0:m], and return the d bits shifted out of the bottom.
1595 */
1596static digit
1597v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1598{
1599 Py_ssize_t i;
1600 digit carry = 0;
1601 digit mask = ((digit)1 << d) - 1U;
1602
1603 assert(0 <= d && d < PyLong_SHIFT);
1604 for (i=m; i-- > 0;) {
1605 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1606 carry = (digit)acc & mask;
1607 z[i] = (digit)(acc >> d);
1608 }
1609 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001610}
1611
Tim Peters212e6142001-07-14 12:23:19 +00001612/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1613 in pout, and returning the remainder. pin and pout point at the LSD.
1614 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001615 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001616 immutable. */
1617
1618static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001619inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001620{
1621 twodigits rem = 0;
1622
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001623 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001624 pin += size;
1625 pout += size;
1626 while (--size >= 0) {
1627 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001628 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001629 *--pout = hi = (digit)(rem / n);
Mark Dickinson17e55872009-01-24 15:56:57 +00001630 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001631 }
1632 return (digit)rem;
1633}
1634
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001635/* Divide a long integer by a digit, returning both the quotient
1636 (as function result) and the remainder (through *prem).
1637 The sign of a is ignored; n should not be zero. */
1638
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001639static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001640divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001641{
Christian Heimes90aa7642007-12-19 02:45:37 +00001642 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001643 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001644
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001645 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001646 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001647 if (z == NULL)
1648 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001649 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001650 return long_normalize(z);
1651}
1652
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001653/* Convert a long integer to a base 10 string. Returns a new non-shared
1654 string. (Return value is non-shared so that callers can modify the
1655 returned value if necessary.) */
1656
1657static PyObject *
1658long_to_decimal_string(PyObject *aa)
1659{
1660 PyLongObject *scratch, *a;
1661 PyObject *str;
1662 Py_ssize_t size, strlen, size_a, i, j;
1663 digit *pout, *pin, rem, tenpow;
1664 Py_UNICODE *p;
1665 int negative;
1666
1667 a = (PyLongObject *)aa;
1668 if (a == NULL || !PyLong_Check(a)) {
1669 PyErr_BadInternalCall();
1670 return NULL;
1671 }
1672 size_a = ABS(Py_SIZE(a));
1673 negative = Py_SIZE(a) < 0;
1674
1675 /* quick and dirty upper bound for the number of digits
1676 required to express a in base _PyLong_DECIMAL_BASE:
1677
1678 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1679
1680 But log2(a) < size_a * PyLong_SHIFT, and
1681 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1682 > 3 * _PyLong_DECIMAL_SHIFT
1683 */
1684 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1685 PyErr_SetString(PyExc_OverflowError,
1686 "long is too large to format");
1687 return NULL;
1688 }
1689 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1690 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1691 scratch = _PyLong_New(size);
1692 if (scratch == NULL)
1693 return NULL;
1694
1695 /* convert array of base _PyLong_BASE digits in pin to an array of
1696 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1697 Volume 2 (3rd edn), section 4.4, Method 1b). */
1698 pin = a->ob_digit;
1699 pout = scratch->ob_digit;
1700 size = 0;
1701 for (i = size_a; --i >= 0; ) {
1702 digit hi = pin[i];
1703 for (j = 0; j < size; j++) {
1704 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1705 hi = z / _PyLong_DECIMAL_BASE;
1706 pout[j] = z - (twodigits)hi * _PyLong_DECIMAL_BASE;
1707 }
1708 while (hi) {
1709 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1710 hi /= _PyLong_DECIMAL_BASE;
1711 }
1712 /* check for keyboard interrupt */
1713 SIGCHECK({
1714 Py_DECREF(scratch);
1715 return NULL;
1716 })
1717 }
1718 /* pout should have at least one digit, so that the case when a = 0
1719 works correctly */
1720 if (size == 0)
1721 pout[size++] = 0;
1722
1723 /* calculate exact length of output string, and allocate */
1724 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1725 tenpow = 10;
1726 rem = pout[size-1];
1727 while (rem >= tenpow) {
1728 tenpow *= 10;
1729 strlen++;
1730 }
1731 str = PyUnicode_FromUnicode(NULL, strlen);
1732 if (str == NULL) {
1733 Py_DECREF(scratch);
1734 return NULL;
1735 }
1736
1737 /* fill the string right-to-left */
1738 p = PyUnicode_AS_UNICODE(str) + strlen;
1739 *p = '\0';
1740 /* pout[0] through pout[size-2] contribute exactly
1741 _PyLong_DECIMAL_SHIFT digits each */
1742 for (i=0; i < size - 1; i++) {
1743 rem = pout[i];
1744 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1745 *--p = '0' + rem % 10;
1746 rem /= 10;
1747 }
1748 }
1749 /* pout[size-1]: always produce at least one decimal digit */
1750 rem = pout[i];
1751 do {
1752 *--p = '0' + rem % 10;
1753 rem /= 10;
1754 } while (rem != 0);
1755
1756 /* and sign */
1757 if (negative)
1758 *--p = '-';
1759
1760 /* check we've counted correctly */
1761 assert(p == PyUnicode_AS_UNICODE(str));
1762 Py_DECREF(scratch);
1763 return (PyObject *)str;
1764}
1765
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001766/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001767 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001768 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001769
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001770PyObject *
1771_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001772{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001773 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001774 PyObject *str;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001775 Py_ssize_t i, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001776 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001777 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001778 int bits;
1779 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001780
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001781 if (base == 10)
1782 return long_to_decimal_string((PyObject *)a);
1783
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001784 if (a == NULL || !PyLong_Check(a)) {
1785 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001786 return NULL;
1787 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001788 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001789 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001790
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001791 /* Compute a rough upper bound for the length of the string */
1792 i = base;
1793 bits = 0;
1794 while (i > 1) {
1795 ++bits;
1796 i >>= 1;
1797 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001798 i = 5;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001799 /* ensure we don't get signed overflow in sz calculation */
1800 if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001801 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001802 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001803 return NULL;
1804 }
Mark Dickinson659c7b12009-09-13 12:06:08 +00001805 sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
1806 assert(sz >= 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001807 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001808 if (str == NULL)
1809 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001810 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001811 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001812 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001813 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001814
Christian Heimes90aa7642007-12-19 02:45:37 +00001815 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001816 *--p = '0';
1817 }
1818 else if ((base & (base - 1)) == 0) {
1819 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001820 twodigits accum = 0;
1821 int accumbits = 0; /* # of bits in accum */
1822 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001823 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001824 while ((i >>= 1) > 1)
1825 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001826
1827 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001828 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001829 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001830 assert(accumbits >= basebits);
1831 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001832 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001833 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001834 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001835 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001836 accumbits -= basebits;
1837 accum >>= basebits;
1838 } while (i < size_a-1 ? accumbits >= basebits :
Mark Dickinson659c7b12009-09-13 12:06:08 +00001839 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001840 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001841 }
1842 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001843 /* Not 0, and base not a power of 2. Divide repeatedly by
1844 base, but for speed use the highest power of base that
1845 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001846 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001847 digit *pin = a->ob_digit;
1848 PyLongObject *scratch;
1849 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001850 digit powbase = base; /* powbase == base ** power */
1851 int power = 1;
1852 for (;;) {
Mark Dickinson134708a2009-02-25 20:33:49 +00001853 twodigits newpow = powbase * (twodigits)base;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001854 if (newpow >> PyLong_SHIFT)
1855 /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001856 break;
1857 powbase = (digit)newpow;
1858 ++power;
1859 }
Tim Peters212e6142001-07-14 12:23:19 +00001860
1861 /* Get a scratch area for repeated division. */
1862 scratch = _PyLong_New(size);
1863 if (scratch == NULL) {
1864 Py_DECREF(str);
1865 return NULL;
1866 }
1867
1868 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001869 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001870 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001871 digit rem = inplace_divrem1(scratch->ob_digit,
1872 pin, size, powbase);
1873 pin = scratch->ob_digit; /* no need to use a again */
1874 if (pin[size - 1] == 0)
1875 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001876 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001877 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001878 Py_DECREF(str);
1879 return NULL;
1880 })
Tim Peters212e6142001-07-14 12:23:19 +00001881
1882 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001883 assert(ntostore > 0);
1884 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001885 digit nextrem = (digit)(rem / base);
1886 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001887 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001888 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001889 *--p = c;
1890 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001891 --ntostore;
1892 /* Termination is a bit delicate: must not
1893 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001894 remaining quotient and rem are both 0. */
1895 } while (ntostore && (size || rem));
1896 } while (size != 0);
1897 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001898 }
1899
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001900 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001901 *--p = 'x';
1902 *--p = '0';
1903 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001904 else if (base == 8) {
1905 *--p = 'o';
1906 *--p = '0';
1907 }
1908 else if (base == 2) {
1909 *--p = 'b';
1910 *--p = '0';
1911 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001912 else if (base != 10) {
1913 *--p = '#';
1914 *--p = '0' + base%10;
1915 if (base > 10)
1916 *--p = '0' + base/10;
1917 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001918 if (sign)
1919 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001920 if (p != PyUnicode_AS_UNICODE(str)) {
1921 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001922 assert(p > q);
1923 do {
1924 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001925 q--;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001926 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1927 PyUnicode_AS_UNICODE(str)))) {
Walter Dörwald1ab83302007-05-18 17:15:44 +00001928 Py_DECREF(str);
1929 return NULL;
1930 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001931 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001932 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001933}
1934
Thomas Wouters477c8d52006-05-27 19:21:47 +00001935/* Table of digit values for 8-bit string -> integer conversion.
1936 * '0' maps to 0, ..., '9' maps to 9.
1937 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1938 * All other indices map to 37.
1939 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001940 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001941 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001942unsigned char _PyLong_DigitValue[256] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001943 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1944 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1945 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1946 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1947 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1948 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1949 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1950 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1951 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1952 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1953 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1954 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1955 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1956 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1957 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1958 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1959};
1960
1961/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001962 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1963 * non-digit (which may be *str!). A normalized long is returned.
1964 * The point to this routine is that it takes time linear in the number of
1965 * string characters.
1966 */
1967static PyLongObject *
1968long_from_binary_base(char **str, int base)
1969{
1970 char *p = *str;
1971 char *start = p;
1972 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001973 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001974 PyLongObject *z;
1975 twodigits accum;
1976 int bits_in_accum;
1977 digit *pdigit;
1978
1979 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1980 n = base;
1981 for (bits_per_char = -1; n; ++bits_per_char)
1982 n >>= 1;
1983 /* n <- total # of bits needed, while setting p to end-of-string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001984 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001985 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001986 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001987 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1988 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001989 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001990 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001991 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001992 return NULL;
1993 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001994 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001995 z = _PyLong_New(n);
1996 if (z == NULL)
1997 return NULL;
1998 /* Read string from right, and fill in long from left; i.e.,
1999 * from least to most significant in both.
2000 */
2001 accum = 0;
2002 bits_in_accum = 0;
2003 pdigit = z->ob_digit;
2004 while (--p >= start) {
Raymond Hettinger35631532009-01-09 03:58:09 +00002005 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00002006 assert(k >= 0 && k < base);
Mark Dickinson17e55872009-01-24 15:56:57 +00002007 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00002008 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002009 if (bits_in_accum >= PyLong_SHIFT) {
2010 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinson17e55872009-01-24 15:56:57 +00002011 assert(pdigit - z->ob_digit <= n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002012 accum >>= PyLong_SHIFT;
2013 bits_in_accum -= PyLong_SHIFT;
2014 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00002015 }
2016 }
2017 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002018 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00002019 *pdigit++ = (digit)accum;
Mark Dickinson17e55872009-01-24 15:56:57 +00002020 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00002021 }
2022 while (pdigit - z->ob_digit < n)
2023 *pdigit++ = 0;
2024 return long_normalize(z);
2025}
2026
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002027PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002028PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002029{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002030 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002031 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002032 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00002033 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002034 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002035
Guido van Rossum472c04f1996-12-05 21:57:21 +00002036 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002037 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002038 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002039 return NULL;
2040 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00002041 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002042 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002043 if (*str == '+')
2044 ++str;
2045 else if (*str == '-') {
2046 ++str;
2047 sign = -1;
2048 }
2049 if (base == 0) {
2050 if (str[0] != '0')
2051 base = 10;
2052 else if (str[1] == 'x' || str[1] == 'X')
2053 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002054 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002055 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002056 else if (str[1] == 'b' || str[1] == 'B')
2057 base = 2;
2058 else {
2059 /* "old" (C-style) octal literal, now invalid.
2060 it might still be zero though */
2061 error_if_nonzero = 1;
2062 base = 10;
2063 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002064 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002065 if (str[0] == '0' &&
2066 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2067 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2068 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002069 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002070
Guido van Rossume6762971998-06-22 03:54:46 +00002071 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00002072 if ((base & (base - 1)) == 0)
2073 z = long_from_binary_base(&str, base);
2074 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002075/***
2076Binary bases can be converted in time linear in the number of digits, because
2077Python's representation base is binary. Other bases (including decimal!) use
2078the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002079
Thomas Wouters477c8d52006-05-27 19:21:47 +00002080First some math: the largest integer that can be expressed in N base-B digits
2081is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2082case number of Python digits needed to hold it is the smallest integer n s.t.
2083
2084 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2085 BASE**n >= B**N [taking logs to base BASE]
2086 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2087
2088The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2089this quickly. A Python long with that much space is reserved near the start,
2090and the result is computed into it.
2091
2092The input string is actually treated as being in base base**i (i.e., i digits
2093are processed at a time), where two more static arrays hold:
2094
2095 convwidth_base[base] = the largest integer i such that base**i <= BASE
2096 convmultmax_base[base] = base ** convwidth_base[base]
2097
2098The first of these is the largest i such that i consecutive input digits
2099must fit in a single Python digit. The second is effectively the input
2100base we're really using.
2101
2102Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2103convmultmax_base[base], the result is "simply"
2104
2105 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2106
2107where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002108
2109Error analysis: as above, the number of Python digits `n` needed is worst-
2110case
2111
2112 n >= N * log(B)/log(BASE)
2113
2114where `N` is the number of input digits in base `B`. This is computed via
2115
2116 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2117
2118below. Two numeric concerns are how much space this can waste, and whether
2119the computed result can be too small. To be concrete, assume BASE = 2**15,
2120which is the default (and it's unlikely anyone changes that).
2121
2122Waste isn't a problem: provided the first input digit isn't 0, the difference
2123between the worst-case input with N digits and the smallest input with N
2124digits is about a factor of B, but B is small compared to BASE so at most
2125one allocated Python digit can remain unused on that count. If
2126N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2127and adding 1 returns a result 1 larger than necessary. However, that can't
2128happen: whenever B is a power of 2, long_from_binary_base() is called
2129instead, and it's impossible for B**i to be an integer power of 2**15 when
2130B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2131an exact integer when B is not a power of 2, since B**i has a prime factor
2132other than 2 in that case, but (2**15)**j's only prime factor is 2).
2133
2134The computed result can be too small if the true value of N*log(B)/log(BASE)
2135is a little bit larger than an exact integer, but due to roundoff errors (in
2136computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2137yields a numeric result a little less than that integer. Unfortunately, "how
2138close can a transcendental function get to an integer over some range?"
2139questions are generally theoretically intractable. Computer analysis via
2140continued fractions is practical: expand log(B)/log(BASE) via continued
2141fractions, giving a sequence i/j of "the best" rational approximations. Then
2142j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2143we can get very close to being in trouble, but very rarely. For example,
214476573 is a denominator in one of the continued-fraction approximations to
2145log(10)/log(2**15), and indeed:
2146
2147 >>> log(10)/log(2**15)*76573
2148 16958.000000654003
2149
2150is very close to an integer. If we were working with IEEE single-precision,
2151rounding errors could kill us. Finding worst cases in IEEE double-precision
2152requires better-than-double-precision log() functions, and Tim didn't bother.
2153Instead the code checks to see whether the allocated space is enough as each
2154new Python digit is added, and copies the whole thing to a larger long if not.
2155This should happen extremely rarely, and in fact I don't have a test case
2156that triggers it(!). Instead the code was tested by artificially allocating
2157just 1 digit at the start, so that the copying code was exercised for every
2158digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002159***/
2160 register twodigits c; /* current input character */
2161 Py_ssize_t size_z;
2162 int i;
2163 int convwidth;
2164 twodigits convmultmax, convmult;
2165 digit *pz, *pzstop;
2166 char* scan;
2167
2168 static double log_base_BASE[37] = {0.0e0,};
2169 static int convwidth_base[37] = {0,};
2170 static twodigits convmultmax_base[37] = {0,};
2171
2172 if (log_base_BASE[base] == 0.0) {
2173 twodigits convmax = base;
2174 int i = 1;
2175
2176 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002177 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002178 for (;;) {
2179 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002180 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002181 break;
2182 convmax = next;
2183 ++i;
2184 }
2185 convmultmax_base[base] = convmax;
2186 assert(i > 0);
2187 convwidth_base[base] = i;
2188 }
2189
2190 /* Find length of the string of numeric characters. */
2191 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00002192 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002193 ++scan;
2194
2195 /* Create a long object that can contain the largest possible
2196 * integer with this base and length. Note that there's no
2197 * need to initialize z->ob_digit -- no slot is read up before
2198 * being stored into.
2199 */
2200 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002201 /* Uncomment next line to test exceedingly rare copy code */
2202 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002203 assert(size_z > 0);
2204 z = _PyLong_New(size_z);
2205 if (z == NULL)
2206 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002207 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002208
2209 /* `convwidth` consecutive input digits are treated as a single
2210 * digit in base `convmultmax`.
2211 */
2212 convwidth = convwidth_base[base];
2213 convmultmax = convmultmax_base[base];
2214
2215 /* Work ;-) */
2216 while (str < scan) {
2217 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00002218 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002219 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2220 c = (twodigits)(c * base +
Raymond Hettinger35631532009-01-09 03:58:09 +00002221 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002222 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002223 }
2224
2225 convmult = convmultmax;
2226 /* Calculate the shift only if we couldn't get
2227 * convwidth digits.
2228 */
2229 if (i != convwidth) {
2230 convmult = base;
2231 for ( ; i > 1; --i)
2232 convmult *= base;
2233 }
2234
2235 /* Multiply z by convmult, and add c. */
2236 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00002237 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002238 for (; pz < pzstop; ++pz) {
2239 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002240 *pz = (digit)(c & PyLong_MASK);
2241 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002242 }
2243 /* carry off the current end? */
2244 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002245 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00002246 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002247 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00002248 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002249 }
2250 else {
2251 PyLongObject *tmp;
2252 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002253 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002254 tmp = _PyLong_New(size_z + 1);
2255 if (tmp == NULL) {
2256 Py_DECREF(z);
2257 return NULL;
2258 }
2259 memcpy(tmp->ob_digit,
2260 z->ob_digit,
2261 sizeof(digit) * size_z);
2262 Py_DECREF(z);
2263 z = tmp;
2264 z->ob_digit[size_z] = (digit)c;
2265 ++size_z;
2266 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002267 }
Tim Petersbf2674b2003-02-02 07:51:32 +00002268 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002269 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00002270 if (z == NULL)
2271 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002272 if (error_if_nonzero) {
2273 /* reset the base to 0, else the exception message
2274 doesn't make too much sense */
2275 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00002276 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002277 goto onError;
2278 /* there might still be other problems, therefore base
2279 remains zero here for the same reason */
2280 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00002281 if (str == start)
2282 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002283 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00002284 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00002285 while (*str && isspace(Py_CHARMASK(*str)))
2286 str++;
2287 if (*str != '\0')
2288 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002289 if (pend)
2290 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00002291 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002292 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002293
2294 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002295 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002296 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002297 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002298 if (strobj == NULL)
2299 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002300 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002301 "invalid literal for int() with base %d: %R",
2302 base, strobj);
2303 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002304 return NULL;
2305}
2306
2307PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002308PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002309{
Walter Dörwald07e14762002-11-06 16:15:14 +00002310 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002311 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002312
Walter Dörwald07e14762002-11-06 16:15:14 +00002313 if (buffer == NULL)
2314 return NULL;
2315
2316 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2317 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002318 return NULL;
2319 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002320 result = PyLong_FromString(buffer, NULL, base);
2321 PyMem_FREE(buffer);
2322 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002323}
2324
Tim Peters9f688bf2000-07-07 15:53:28 +00002325/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002326static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002327 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002328static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002329
2330/* Long division with remainder, top-level routine */
2331
Guido van Rossume32e0141992-01-19 16:31:05 +00002332static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002333long_divrem(PyLongObject *a, PyLongObject *b,
2334 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002335{
Christian Heimes90aa7642007-12-19 02:45:37 +00002336 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002337 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002338
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002339 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002340 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002341 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002342 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002343 }
2344 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002345 (size_a == size_b &&
2346 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002347 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002348 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002349 if (*pdiv == NULL)
2350 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002351 Py_INCREF(a);
2352 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002353 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002354 }
2355 if (size_b == 1) {
2356 digit rem = 0;
2357 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002358 if (z == NULL)
2359 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002360 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002361 if (*prem == NULL) {
2362 Py_DECREF(z);
2363 return -1;
2364 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002365 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002366 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002367 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002368 if (z == NULL)
2369 return -1;
2370 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002371 /* Set the signs.
2372 The quotient z has the sign of a*b;
2373 the remainder r has the sign of a,
2374 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002375 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002376 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002377 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002378 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002379 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002380 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002381}
2382
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002383/* Unsigned long division with remainder -- the algorithm. The arguments v1
2384 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002385
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002386static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002387x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002388{
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002389 PyLongObject *v, *w, *a;
2390 Py_ssize_t i, k, size_v, size_w;
2391 int d;
2392 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2393 twodigits vv;
2394 sdigit zhi;
2395 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002396
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002397 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2398 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2399 handle the special case when the initial estimate q for a quotient
2400 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2401 that won't overflow a digit. */
2402
2403 /* allocate space; w will also be used to hold the final remainder */
2404 size_v = ABS(Py_SIZE(v1));
2405 size_w = ABS(Py_SIZE(w1));
2406 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2407 v = _PyLong_New(size_v+1);
2408 if (v == NULL) {
2409 *prem = NULL;
2410 return NULL;
2411 }
2412 w = _PyLong_New(size_w);
2413 if (w == NULL) {
2414 Py_DECREF(v);
2415 *prem = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002416 return NULL;
2417 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002418
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002419 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2420 shift v1 left by the same amount. Results go into w and v. */
2421 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2422 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2423 assert(carry == 0);
2424 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2425 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2426 v->ob_digit[size_v] = carry;
2427 size_v++;
2428 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002429
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002430 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2431 at most (and usually exactly) k = size_v - size_w digits. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002432 k = size_v - size_w;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002433 assert(k >= 0);
2434 a = _PyLong_New(k);
2435 if (a == NULL) {
2436 Py_DECREF(w);
2437 Py_DECREF(v);
2438 *prem = NULL;
2439 return NULL;
2440 }
2441 v0 = v->ob_digit;
2442 w0 = w->ob_digit;
2443 wm1 = w0[size_w-1];
2444 wm2 = w0[size_w-2];
2445 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2446 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2447 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002448
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002449 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002450 Py_DECREF(a);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002451 Py_DECREF(w);
2452 Py_DECREF(v);
2453 *prem = NULL;
2454 return NULL;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002455 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002456
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002457 /* estimate quotient digit q; may overestimate by 1 (rare) */
2458 vtop = vk[size_w];
2459 assert(vtop <= wm1);
2460 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2461 q = (digit)(vv / wm1);
2462 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2463 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2464 | vk[size_w-2])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002465 --q;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002466 r += wm1;
2467 if (r >= PyLong_BASE)
2468 break;
2469 }
2470 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002471
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002472 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2473 zhi = 0;
2474 for (i = 0; i < size_w; ++i) {
2475 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2476 -PyLong_BASE * q <= z < PyLong_BASE */
2477 z = (sdigit)vk[i] + zhi -
2478 (stwodigits)q * (stwodigits)w0[i];
2479 vk[i] = (digit)z & PyLong_MASK;
2480 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2481 z, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002482 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002483
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002484 /* add w back if q was too large (this branch taken rarely) */
2485 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2486 if ((sdigit)vtop + zhi < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002487 carry = 0;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002488 for (i = 0; i < size_w; ++i) {
2489 carry += vk[i] + w0[i];
2490 vk[i] = carry & PyLong_MASK;
2491 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002492 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002493 --q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002494 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002495
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002496 /* store quotient digit */
2497 assert(q < PyLong_BASE);
2498 *--ak = q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002499 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002500
2501 /* unshift remainder; we reuse w to store the result */
2502 carry = v_rshift(w0, v0, size_w, d);
2503 assert(carry==0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002504 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002505
2506 *prem = long_normalize(w);
2507 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002508}
2509
2510/* Methods */
2511
2512static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002513long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002514{
Christian Heimes90aa7642007-12-19 02:45:37 +00002515 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002516}
2517
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002518static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002519long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002520{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002521 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002522}
2523
2524static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002525long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002526{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002527 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002528
Christian Heimes90aa7642007-12-19 02:45:37 +00002529 if (Py_SIZE(a) != Py_SIZE(b)) {
2530 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002531 sign = 0;
2532 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002533 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002534 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002535 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002536 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002537 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2538 ;
2539 if (i < 0)
2540 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002541 else {
Mark Dickinsone4416742009-02-15 15:14:57 +00002542 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002543 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002544 sign = -sign;
2545 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002546 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002547 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002548}
2549
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002550#define TEST_COND(cond) \
2551 ((cond) ? Py_True : Py_False)
2552
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002553static PyObject *
2554long_richcompare(PyObject *self, PyObject *other, int op)
2555{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002556 int result;
2557 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002558 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002559 if (self == other)
2560 result = 0;
2561 else
2562 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2563 /* Convert the return value to a Boolean */
2564 switch (op) {
2565 case Py_EQ:
2566 v = TEST_COND(result == 0);
2567 break;
2568 case Py_NE:
2569 v = TEST_COND(result != 0);
2570 break;
2571 case Py_LE:
2572 v = TEST_COND(result <= 0);
2573 break;
2574 case Py_GE:
2575 v = TEST_COND(result >= 0);
2576 break;
2577 case Py_LT:
2578 v = TEST_COND(result == -1);
2579 break;
2580 case Py_GT:
2581 v = TEST_COND(result == 1);
2582 break;
2583 default:
2584 PyErr_BadArgument();
2585 return NULL;
2586 }
2587 Py_INCREF(v);
2588 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002589}
2590
Guido van Rossum9bfef441993-03-29 10:43:31 +00002591static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002592long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002593{
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002594 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002595 Py_ssize_t i;
2596 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002597
2598 /* This is designed so that Python ints and longs with the
2599 same value hash to the same value, otherwise comparisons
2600 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002601 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002602 switch(i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00002603 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00002604 case 0: return 0;
2605 case 1: return v->ob_digit[0];
2606 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002607 sign = 1;
2608 x = 0;
2609 if (i < 0) {
2610 sign = -1;
2611 i = -(i);
2612 }
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002613 /* The following loop produces a C unsigned long x such that x is
2614 congruent to the absolute value of v modulo ULONG_MAX. The
Thomas Woutersce272b62007-09-19 21:19:28 +00002615 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002616 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002617 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002618 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002619 x += v->ob_digit[i];
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002620 /* If the addition above overflowed we compensate by
2621 incrementing. This preserves the value modulo
2622 ULONG_MAX. */
2623 if (x < v->ob_digit[i])
Thomas Woutersce272b62007-09-19 21:19:28 +00002624 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002625 }
2626 x = x * sign;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002627 if (x == (unsigned long)-1)
2628 x = (unsigned long)-2;
2629 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002630}
2631
2632
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002633/* Add the absolute values of two long integers. */
2634
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002635static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002636x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002637{
Christian Heimes90aa7642007-12-19 02:45:37 +00002638 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002639 PyLongObject *z;
Mark Dickinson17e55872009-01-24 15:56:57 +00002640 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002641 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002642
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002643 /* Ensure a is the larger of the two: */
2644 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002645 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002646 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002647 size_a = size_b;
2648 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002649 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002650 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002651 if (z == NULL)
2652 return NULL;
2653 for (i = 0; i < size_b; ++i) {
2654 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002655 z->ob_digit[i] = carry & PyLong_MASK;
2656 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002657 }
2658 for (; i < size_a; ++i) {
2659 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002660 z->ob_digit[i] = carry & PyLong_MASK;
2661 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002662 }
2663 z->ob_digit[i] = carry;
2664 return long_normalize(z);
2665}
2666
2667/* Subtract the absolute values of two integers. */
2668
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002669static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002670x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002671{
Christian Heimes90aa7642007-12-19 02:45:37 +00002672 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002673 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002674 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002675 int sign = 1;
2676 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002677
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002678 /* Ensure a is the larger of the two: */
2679 if (size_a < size_b) {
2680 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002681 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002682 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002683 size_a = size_b;
2684 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002685 }
2686 else if (size_a == size_b) {
2687 /* Find highest digit where a and b differ: */
2688 i = size_a;
2689 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2690 ;
2691 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002692 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002693 if (a->ob_digit[i] < b->ob_digit[i]) {
2694 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002695 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002696 }
2697 size_a = size_b = i+1;
2698 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002699 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002700 if (z == NULL)
2701 return NULL;
2702 for (i = 0; i < size_b; ++i) {
2703 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002704 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002705 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002706 z->ob_digit[i] = borrow & PyLong_MASK;
2707 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002708 borrow &= 1; /* Keep only one sign bit */
2709 }
2710 for (; i < size_a; ++i) {
2711 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002712 z->ob_digit[i] = borrow & PyLong_MASK;
2713 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002714 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002715 }
2716 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002717 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002718 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002719 return long_normalize(z);
2720}
2721
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002722static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002723long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002724{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002725 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002726
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002727 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002728
Christian Heimes90aa7642007-12-19 02:45:37 +00002729 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002730 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002731 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002732 return result;
2733 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002734 if (Py_SIZE(a) < 0) {
2735 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002736 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002737 if (z != NULL && Py_SIZE(z) != 0)
2738 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002739 }
2740 else
2741 z = x_sub(b, a);
2742 }
2743 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002744 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002745 z = x_sub(a, b);
2746 else
2747 z = x_add(a, b);
2748 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002749 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002750}
2751
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002752static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002753long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002754{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002755 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002756
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002757 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002758
Christian Heimes90aa7642007-12-19 02:45:37 +00002759 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002760 PyObject* r;
2761 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002762 return r;
2763 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002764 if (Py_SIZE(a) < 0) {
2765 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002766 z = x_sub(a, b);
2767 else
2768 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002769 if (z != NULL && Py_SIZE(z) != 0)
2770 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002771 }
2772 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002773 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002774 z = x_add(a, b);
2775 else
2776 z = x_sub(a, b);
2777 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002778 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002779}
2780
Tim Peters5af4e6c2002-08-12 02:31:19 +00002781/* Grade school multiplication, ignoring the signs.
2782 * Returns the absolute value of the product, or NULL if error.
2783 */
2784static PyLongObject *
2785x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002786{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002787 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002788 Py_ssize_t size_a = ABS(Py_SIZE(a));
2789 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002790 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002791
Tim Peters5af4e6c2002-08-12 02:31:19 +00002792 z = _PyLong_New(size_a + size_b);
2793 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002794 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002795
Christian Heimes90aa7642007-12-19 02:45:37 +00002796 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002797 if (a == b) {
2798 /* Efficient squaring per HAC, Algorithm 14.16:
2799 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2800 * Gives slightly less than a 2x speedup when a == b,
2801 * via exploiting that each entry in the multiplication
2802 * pyramid appears twice (except for the size_a squares).
2803 */
2804 for (i = 0; i < size_a; ++i) {
2805 twodigits carry;
2806 twodigits f = a->ob_digit[i];
2807 digit *pz = z->ob_digit + (i << 1);
2808 digit *pa = a->ob_digit + i + 1;
2809 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002810
Tim Peters0973b992004-08-29 22:16:50 +00002811 SIGCHECK({
2812 Py_DECREF(z);
2813 return NULL;
2814 })
2815
2816 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002817 *pz++ = (digit)(carry & PyLong_MASK);
2818 carry >>= PyLong_SHIFT;
2819 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002820
2821 /* Now f is added in twice in each column of the
2822 * pyramid it appears. Same as adding f<<1 once.
2823 */
2824 f <<= 1;
2825 while (pa < paend) {
2826 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002827 *pz++ = (digit)(carry & PyLong_MASK);
2828 carry >>= PyLong_SHIFT;
2829 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002830 }
2831 if (carry) {
2832 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002833 *pz++ = (digit)(carry & PyLong_MASK);
2834 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002835 }
2836 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002837 *pz += (digit)(carry & PyLong_MASK);
2838 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002839 }
Tim Peters0973b992004-08-29 22:16:50 +00002840 }
2841 else { /* a is not the same as b -- gradeschool long mult */
2842 for (i = 0; i < size_a; ++i) {
2843 twodigits carry = 0;
2844 twodigits f = a->ob_digit[i];
2845 digit *pz = z->ob_digit + i;
2846 digit *pb = b->ob_digit;
2847 digit *pbend = b->ob_digit + size_b;
2848
2849 SIGCHECK({
2850 Py_DECREF(z);
2851 return NULL;
2852 })
2853
2854 while (pb < pbend) {
2855 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002856 *pz++ = (digit)(carry & PyLong_MASK);
2857 carry >>= PyLong_SHIFT;
2858 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002859 }
2860 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002861 *pz += (digit)(carry & PyLong_MASK);
2862 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002863 }
2864 }
Tim Peters44121a62002-08-12 06:17:58 +00002865 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002866}
2867
2868/* A helper for Karatsuba multiplication (k_mul).
2869 Takes a long "n" and an integer "size" representing the place to
2870 split, and sets low and high such that abs(n) == (high << size) + low,
2871 viewing the shift as being by digits. The sign bit is ignored, and
2872 the return values are >= 0.
2873 Returns 0 on success, -1 on failure.
2874*/
2875static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002876kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002877{
2878 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002879 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002880 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002881
2882 size_lo = MIN(size_n, size);
2883 size_hi = size_n - size_lo;
2884
2885 if ((hi = _PyLong_New(size_hi)) == NULL)
2886 return -1;
2887 if ((lo = _PyLong_New(size_lo)) == NULL) {
2888 Py_DECREF(hi);
2889 return -1;
2890 }
2891
2892 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2893 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2894
2895 *high = long_normalize(hi);
2896 *low = long_normalize(lo);
2897 return 0;
2898}
2899
Tim Peters60004642002-08-12 22:01:34 +00002900static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2901
Tim Peters5af4e6c2002-08-12 02:31:19 +00002902/* Karatsuba multiplication. Ignores the input signs, and returns the
2903 * absolute value of the product (or NULL if error).
2904 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2905 */
2906static PyLongObject *
2907k_mul(PyLongObject *a, PyLongObject *b)
2908{
Christian Heimes90aa7642007-12-19 02:45:37 +00002909 Py_ssize_t asize = ABS(Py_SIZE(a));
2910 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002911 PyLongObject *ah = NULL;
2912 PyLongObject *al = NULL;
2913 PyLongObject *bh = NULL;
2914 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002915 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002916 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002917 Py_ssize_t shift; /* the number of digits we split off */
2918 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002919
Tim Peters5af4e6c2002-08-12 02:31:19 +00002920 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2921 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2922 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002923 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002924 * By picking X to be a power of 2, "*X" is just shifting, and it's
2925 * been reduced to 3 multiplies on numbers half the size.
2926 */
2927
Tim Petersfc07e562002-08-12 02:54:10 +00002928 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002929 * is largest.
2930 */
Tim Peters738eda72002-08-12 15:08:20 +00002931 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002932 t1 = a;
2933 a = b;
2934 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002935
2936 i = asize;
2937 asize = bsize;
2938 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002939 }
2940
2941 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002942 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2943 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002944 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002945 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002946 else
2947 return x_mul(a, b);
2948 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002949
Tim Peters60004642002-08-12 22:01:34 +00002950 /* If a is small compared to b, splitting on b gives a degenerate
2951 * case with ah==0, and Karatsuba may be (even much) less efficient
2952 * than "grade school" then. However, we can still win, by viewing
2953 * b as a string of "big digits", each of width a->ob_size. That
2954 * leads to a sequence of balanced calls to k_mul.
2955 */
2956 if (2 * asize <= bsize)
2957 return k_lopsided_mul(a, b);
2958
Tim Petersd6974a52002-08-13 20:37:51 +00002959 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002960 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002961 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002962 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002963
Tim Peters0973b992004-08-29 22:16:50 +00002964 if (a == b) {
2965 bh = ah;
2966 bl = al;
2967 Py_INCREF(bh);
2968 Py_INCREF(bl);
2969 }
2970 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002971
Tim Petersd64c1de2002-08-12 17:36:03 +00002972 /* The plan:
2973 * 1. Allocate result space (asize + bsize digits: that's always
2974 * enough).
2975 * 2. Compute ah*bh, and copy into result at 2*shift.
2976 * 3. Compute al*bl, and copy into result at 0. Note that this
2977 * can't overlap with #2.
2978 * 4. Subtract al*bl from the result, starting at shift. This may
2979 * underflow (borrow out of the high digit), but we don't care:
2980 * we're effectively doing unsigned arithmetic mod
2981 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2982 * borrows and carries out of the high digit can be ignored.
2983 * 5. Subtract ah*bh from the result, starting at shift.
2984 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2985 * at shift.
2986 */
2987
2988 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002989 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002990 if (ret == NULL) goto fail;
2991#ifdef Py_DEBUG
2992 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002993 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002994#endif
Tim Peters44121a62002-08-12 06:17:58 +00002995
Tim Petersd64c1de2002-08-12 17:36:03 +00002996 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002997 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002998 assert(Py_SIZE(t1) >= 0);
2999 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00003000 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00003001 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003002
3003 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003004 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00003005 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00003006 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00003007 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003008
Tim Petersd64c1de2002-08-12 17:36:03 +00003009 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00003010 if ((t2 = k_mul(al, bl)) == NULL) {
3011 Py_DECREF(t1);
3012 goto fail;
3013 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003014 assert(Py_SIZE(t2) >= 0);
3015 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3016 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003017
3018 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003019 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003020 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00003021 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003022
Tim Petersd64c1de2002-08-12 17:36:03 +00003023 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3024 * because it's fresher in cache.
3025 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003026 i = Py_SIZE(ret) - shift; /* # digits after shift */
3027 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00003028 Py_DECREF(t2);
3029
Christian Heimes90aa7642007-12-19 02:45:37 +00003030 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00003031 Py_DECREF(t1);
3032
Tim Petersd64c1de2002-08-12 17:36:03 +00003033 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003034 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3035 Py_DECREF(ah);
3036 Py_DECREF(al);
3037 ah = al = NULL;
3038
Tim Peters0973b992004-08-29 22:16:50 +00003039 if (a == b) {
3040 t2 = t1;
3041 Py_INCREF(t2);
3042 }
3043 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003044 Py_DECREF(t1);
3045 goto fail;
3046 }
3047 Py_DECREF(bh);
3048 Py_DECREF(bl);
3049 bh = bl = NULL;
3050
Tim Peters738eda72002-08-12 15:08:20 +00003051 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003052 Py_DECREF(t1);
3053 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003054 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00003055 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003056
Tim Petersd6974a52002-08-13 20:37:51 +00003057 /* Add t3. It's not obvious why we can't run out of room here.
3058 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00003059 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003060 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00003061 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003062
Tim Peters5af4e6c2002-08-12 02:31:19 +00003063 return long_normalize(ret);
3064
3065 fail:
3066 Py_XDECREF(ret);
3067 Py_XDECREF(ah);
3068 Py_XDECREF(al);
3069 Py_XDECREF(bh);
3070 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003071 return NULL;
3072}
3073
Tim Petersd6974a52002-08-13 20:37:51 +00003074/* (*) Why adding t3 can't "run out of room" above.
3075
Tim Petersab86c2b2002-08-15 20:06:00 +00003076Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3077to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003078
Tim Petersab86c2b2002-08-15 20:06:00 +000030791. For any integer i, i = c(i/2) + f(i/2). In particular,
3080 bsize = c(bsize/2) + f(bsize/2).
30812. shift = f(bsize/2)
30823. asize <= bsize
30834. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3084 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003085
Tim Petersab86c2b2002-08-15 20:06:00 +00003086We allocated asize + bsize result digits, and add t3 into them at an offset
3087of shift. This leaves asize+bsize-shift allocated digit positions for t3
3088to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3089asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003090
Tim Petersab86c2b2002-08-15 20:06:00 +00003091bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3092at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003093
Tim Petersab86c2b2002-08-15 20:06:00 +00003094If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3095digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3096most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003097
Tim Petersab86c2b2002-08-15 20:06:00 +00003098The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003099
Tim Petersab86c2b2002-08-15 20:06:00 +00003100 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003101
Tim Petersab86c2b2002-08-15 20:06:00 +00003102and we have asize + c(bsize/2) available digit positions. We need to show
3103this is always enough. An instance of c(bsize/2) cancels out in both, so
3104the question reduces to whether asize digits is enough to hold
3105(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3106then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3107asize 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 +00003108digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003109asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003110c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3111is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3112bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003113
Tim Peters48d52c02002-08-14 17:07:32 +00003114Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3115clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3116ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003117*/
3118
Tim Peters60004642002-08-12 22:01:34 +00003119/* b has at least twice the digits of a, and a is big enough that Karatsuba
3120 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3121 * of slices, each with a->ob_size digits, and multiply the slices by a,
3122 * one at a time. This gives k_mul balanced inputs to work with, and is
3123 * also cache-friendly (we compute one double-width slice of the result
3124 * at a time, then move on, never bactracking except for the helpful
3125 * single-width slice overlap between successive partial sums).
3126 */
3127static PyLongObject *
3128k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3129{
Christian Heimes90aa7642007-12-19 02:45:37 +00003130 const Py_ssize_t asize = ABS(Py_SIZE(a));
3131 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00003132 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00003133 PyLongObject *ret;
3134 PyLongObject *bslice = NULL;
3135
3136 assert(asize > KARATSUBA_CUTOFF);
3137 assert(2 * asize <= bsize);
3138
3139 /* Allocate result space, and zero it out. */
3140 ret = _PyLong_New(asize + bsize);
3141 if (ret == NULL)
3142 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003143 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003144
3145 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00003146 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00003147 if (bslice == NULL)
3148 goto fail;
3149
3150 nbdone = 0;
3151 while (bsize > 0) {
3152 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003153 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003154
3155 /* Multiply the next slice of b by a. */
3156 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3157 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00003158 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00003159 product = k_mul(a, bslice);
3160 if (product == NULL)
3161 goto fail;
3162
3163 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003164 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3165 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00003166 Py_DECREF(product);
3167
3168 bsize -= nbtouse;
3169 nbdone += nbtouse;
3170 }
3171
3172 Py_DECREF(bslice);
3173 return long_normalize(ret);
3174
3175 fail:
3176 Py_DECREF(ret);
3177 Py_XDECREF(bslice);
3178 return NULL;
3179}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003180
3181static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003182long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003183{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003184 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003185
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003186 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003187
Mark Dickinsonbd792642009-03-18 20:06:12 +00003188 /* fast path for single-digit multiplication */
Christian Heimes90aa7642007-12-19 02:45:37 +00003189 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonbd792642009-03-18 20:06:12 +00003190 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
3191#ifdef HAVE_LONG_LONG
3192 return PyLong_FromLongLong((PY_LONG_LONG)v);
3193#else
3194 /* if we don't have long long then we're almost certainly
3195 using 15-bit digits, so v will fit in a long. In the
3196 unlikely event that we're using 30-bit digits on a platform
3197 without long long, a large v will just cause us to fall
3198 through to the general multiplication code below. */
3199 if (v >= LONG_MIN && v <= LONG_MAX)
3200 return PyLong_FromLong((long)v);
3201#endif
Martin v. Löwis14b6d922007-02-06 21:05:30 +00003202 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003203
Tim Petersd64c1de2002-08-12 17:36:03 +00003204 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00003205 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003206 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003207 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00003208 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003209}
3210
Guido van Rossume32e0141992-01-19 16:31:05 +00003211/* The / and % operators are now defined in terms of divmod().
3212 The expression a mod b has the value a - b*floor(a/b).
3213 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003214 |a| by |b|, with the sign of a. This is also expressed
3215 as a - b*trunc(a/b), if trunc truncates towards zero.
3216 Some examples:
3217 a b a rem b a mod b
3218 13 10 3 3
3219 -13 10 -3 7
3220 13 -10 3 -7
3221 -13 -10 -3 -3
3222 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003223 have different signs. We then subtract one from the 'div'
3224 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003225
Tim Peters47e52ee2004-08-30 02:44:38 +00003226/* Compute
3227 * *pdiv, *pmod = divmod(v, w)
3228 * NULL can be passed for pdiv or pmod, in which case that part of
3229 * the result is simply thrown away. The caller owns a reference to
3230 * each of these it requests (does not pass NULL for).
3231 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003232static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003233l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00003234 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003235{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003236 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003237
Guido van Rossume32e0141992-01-19 16:31:05 +00003238 if (long_divrem(v, w, &div, &mod) < 0)
3239 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00003240 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3241 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003242 PyLongObject *temp;
3243 PyLongObject *one;
3244 temp = (PyLongObject *) long_add(mod, w);
3245 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00003246 mod = temp;
3247 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003248 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003249 return -1;
3250 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003251 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00003252 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003253 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3254 Py_DECREF(mod);
3255 Py_DECREF(div);
3256 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00003257 return -1;
3258 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003259 Py_DECREF(one);
3260 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003261 div = temp;
3262 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003263 if (pdiv != NULL)
3264 *pdiv = div;
3265 else
3266 Py_DECREF(div);
3267
3268 if (pmod != NULL)
3269 *pmod = mod;
3270 else
3271 Py_DECREF(mod);
3272
Guido van Rossume32e0141992-01-19 16:31:05 +00003273 return 0;
3274}
3275
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003276static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003277long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003278{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003279 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003280
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003281 CHECK_BINOP(a, b);
3282 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003283 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003284 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003285}
3286
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003287static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003288long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00003289{
Tim Peterse2a60002001-09-04 06:17:36 +00003290 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00003291 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00003292
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003293 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00003294 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
3295 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00003296 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00003297 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00003298 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00003299 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
3300 but should really be set correctly after sucessful calls to
3301 _PyLong_AsScaledDouble() */
3302 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00003303
3304 if (bd == 0.0) {
3305 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003306 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00003307 return NULL;
3308 }
3309
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003310 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00003311 ad /= bd; /* overflow/underflow impossible here */
3312 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003313 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00003314 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003315 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00003316 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003317 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003318 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00003319 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00003320 goto overflow;
3321 return PyFloat_FromDouble(ad);
3322
3323overflow:
3324 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003325 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00003326 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003327
Tim Peters20dab9f2001-09-04 05:31:47 +00003328}
3329
3330static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003331long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003332{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003333 PyLongObject *mod;
3334
3335 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003336
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003337 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003338 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003339 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003340}
3341
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003342static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003343long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003344{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003345 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003346 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003347
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003348 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003349
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003350 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003351 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003352 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003353 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003354 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003355 PyTuple_SetItem(z, 0, (PyObject *) div);
3356 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003357 }
3358 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003359 Py_DECREF(div);
3360 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003361 }
3362 return z;
3363}
3364
Tim Peters47e52ee2004-08-30 02:44:38 +00003365/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003366static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003367long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003368{
Tim Peters47e52ee2004-08-30 02:44:38 +00003369 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3370 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003371
Tim Peters47e52ee2004-08-30 02:44:38 +00003372 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003373 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003374 PyLongObject *temp = NULL;
3375
3376 /* 5-ary values. If the exponent is large enough, table is
3377 * precomputed so that table[i] == a**i % c for i in range(32).
3378 */
3379 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3380 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3381
3382 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003383 CHECK_BINOP(v, w);
3384 a = (PyLongObject*)v; Py_INCREF(a);
3385 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003386 if (PyLong_Check(x)) {
3387 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003388 Py_INCREF(x);
3389 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003390 else if (x == Py_None)
3391 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003392 else {
3393 Py_DECREF(a);
3394 Py_DECREF(b);
3395 Py_INCREF(Py_NotImplemented);
3396 return Py_NotImplemented;
3397 }
Tim Peters4c483c42001-09-05 06:24:58 +00003398
Christian Heimes90aa7642007-12-19 02:45:37 +00003399 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003400 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003401 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003402 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003403 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003404 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003405 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003406 /* else return a float. This works because we know
3407 that this calls float_pow() which converts its
3408 arguments to double. */
3409 Py_DECREF(a);
3410 Py_DECREF(b);
3411 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003412 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003413 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003414
3415 if (c) {
3416 /* if modulus == 0:
3417 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003418 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003419 PyErr_SetString(PyExc_ValueError,
3420 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003421 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003422 }
3423
3424 /* if modulus < 0:
3425 negativeOutput = True
3426 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003427 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003428 negativeOutput = 1;
3429 temp = (PyLongObject *)_PyLong_Copy(c);
3430 if (temp == NULL)
3431 goto Error;
3432 Py_DECREF(c);
3433 c = temp;
3434 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003435 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003436 }
3437
3438 /* if modulus == 1:
3439 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003440 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003441 z = (PyLongObject *)PyLong_FromLong(0L);
3442 goto Done;
3443 }
3444
3445 /* if base < 0:
3446 base = base % modulus
3447 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003448 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003449 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003450 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003451 Py_DECREF(a);
3452 a = temp;
3453 temp = NULL;
3454 }
3455 }
3456
3457 /* At this point a, b, and c are guaranteed non-negative UNLESS
3458 c is NULL, in which case a may be negative. */
3459
3460 z = (PyLongObject *)PyLong_FromLong(1L);
3461 if (z == NULL)
3462 goto Error;
3463
3464 /* Perform a modular reduction, X = X % c, but leave X alone if c
3465 * is NULL.
3466 */
3467#define REDUCE(X) \
3468 if (c != NULL) { \
3469 if (l_divmod(X, c, NULL, &temp) < 0) \
3470 goto Error; \
3471 Py_XDECREF(X); \
3472 X = temp; \
3473 temp = NULL; \
3474 }
3475
3476 /* Multiply two values, then reduce the result:
3477 result = X*Y % c. If c is NULL, skip the mod. */
3478#define MULT(X, Y, result) \
3479{ \
3480 temp = (PyLongObject *)long_mul(X, Y); \
3481 if (temp == NULL) \
3482 goto Error; \
3483 Py_XDECREF(result); \
3484 result = temp; \
3485 temp = NULL; \
3486 REDUCE(result) \
3487}
3488
Christian Heimes90aa7642007-12-19 02:45:37 +00003489 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003490 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3491 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003492 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003493 digit bi = b->ob_digit[i];
3494
Mark Dickinsone4416742009-02-15 15:14:57 +00003495 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003496 MULT(z, z, z)
3497 if (bi & j)
3498 MULT(z, a, z)
3499 }
3500 }
3501 }
3502 else {
3503 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3504 Py_INCREF(z); /* still holds 1L */
3505 table[0] = z;
3506 for (i = 1; i < 32; ++i)
3507 MULT(table[i-1], a, table[i])
3508
Christian Heimes90aa7642007-12-19 02:45:37 +00003509 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003510 const digit bi = b->ob_digit[i];
3511
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003512 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003513 const int index = (bi >> j) & 0x1f;
3514 for (k = 0; k < 5; ++k)
3515 MULT(z, z, z)
3516 if (index)
3517 MULT(z, table[index], z)
3518 }
3519 }
3520 }
3521
Christian Heimes90aa7642007-12-19 02:45:37 +00003522 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003523 temp = (PyLongObject *)long_sub(z, c);
3524 if (temp == NULL)
3525 goto Error;
3526 Py_DECREF(z);
3527 z = temp;
3528 temp = NULL;
3529 }
3530 goto Done;
3531
3532 Error:
3533 if (z != NULL) {
3534 Py_DECREF(z);
3535 z = NULL;
3536 }
3537 /* fall through */
3538 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003539 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003540 for (i = 0; i < 32; ++i)
3541 Py_XDECREF(table[i]);
3542 }
Tim Petersde7990b2005-07-17 23:45:23 +00003543 Py_DECREF(a);
3544 Py_DECREF(b);
3545 Py_XDECREF(c);
3546 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003547 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003548}
3549
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003550static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003551long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003552{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003553 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003554 PyLongObject *x;
3555 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003556 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003557 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003558 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003559 if (w == NULL)
3560 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003561 x = (PyLongObject *) long_add(v, w);
3562 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003563 if (x == NULL)
3564 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003565 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003566 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003567}
3568
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003569static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003570long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003571{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003572 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003573 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003574 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003575 z = (PyLongObject *)_PyLong_Copy(v);
3576 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003577 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003578 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003579}
3580
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003581static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003582long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003583{
Christian Heimes90aa7642007-12-19 02:45:37 +00003584 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003585 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003586 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003587 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003588}
3589
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003590static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003591long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003592{
Christian Heimes90aa7642007-12-19 02:45:37 +00003593 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003594}
3595
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003596static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003597long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003598{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003599 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003600 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003601 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003602 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003603
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003604 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003605
Christian Heimes90aa7642007-12-19 02:45:37 +00003606 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003607 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003608 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003609 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003610 if (a1 == NULL)
3611 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003612 a2 = (PyLongObject *) long_rshift(a1, b);
3613 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003614 if (a2 == NULL)
3615 goto rshift_error;
3616 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003617 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003618 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003619 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003620
Neil Schemenauerba872e22001-01-04 01:46:03 +00003621 shiftby = PyLong_AsLong((PyObject *)b);
3622 if (shiftby == -1L && PyErr_Occurred())
3623 goto rshift_error;
3624 if (shiftby < 0) {
3625 PyErr_SetString(PyExc_ValueError,
3626 "negative shift count");
3627 goto rshift_error;
3628 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003629 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003630 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003631 if (newsize <= 0)
3632 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003633 loshift = shiftby % PyLong_SHIFT;
3634 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003635 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003636 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003637 z = _PyLong_New(newsize);
3638 if (z == NULL)
3639 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003640 if (Py_SIZE(a) < 0)
3641 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003642 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3643 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3644 if (i+1 < newsize)
3645 z->ob_digit[i] |=
3646 (a->ob_digit[j+1] << hishift) & himask;
3647 }
3648 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003649 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003650rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003651 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003652
Guido van Rossumc6913e71991-11-19 20:26:46 +00003653}
3654
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003655static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003656long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003657{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003658 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003659 PyLongObject *a = (PyLongObject*)v;
3660 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003661 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003662 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003663 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003664 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003665
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003666 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003667
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003668 shiftby = PyLong_AsLong((PyObject *)b);
3669 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003670 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003671 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003672 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003673 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003674 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003675 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003676 PyErr_SetString(PyExc_ValueError,
3677 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003678 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003679 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003680 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3681 wordshift = (int)shiftby / PyLong_SHIFT;
3682 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003683
Christian Heimes90aa7642007-12-19 02:45:37 +00003684 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003685 newsize = oldsize + wordshift;
3686 if (remshift)
3687 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003688 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003689 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003690 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003691 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003692 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003693 for (i = 0; i < wordshift; i++)
3694 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003695 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003696 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003697 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003698 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3699 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003700 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003701 if (remshift)
3702 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003703 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003704 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003705 z = long_normalize(z);
3706lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003707 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003708}
3709
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003710
3711/* Bitwise and/xor/or operations */
3712
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003713static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003714long_bitwise(PyLongObject *a,
3715 int op, /* '&', '|', '^' */
3716 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003717{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003718 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003719 int negz;
Mark Dickinsone4416742009-02-15 15:14:57 +00003720 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003721 PyLongObject *z;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003722 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003723 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003724
Christian Heimes90aa7642007-12-19 02:45:37 +00003725 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003726 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003727 if (a == NULL)
3728 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003729 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003730 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003731 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003732 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003733 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003734 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003735 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003736 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003737 if (b == NULL) {
3738 Py_DECREF(a);
3739 return NULL;
3740 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003741 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003742 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003743 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003744 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003745 maskb = 0;
3746 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003747
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003748 negz = 0;
3749 switch (op) {
3750 case '^':
3751 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003752 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003753 negz = -1;
3754 }
3755 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003756 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003757 if (maska && maskb) {
3758 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003759 maska ^= PyLong_MASK;
3760 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003761 negz = -1;
3762 }
3763 break;
3764 case '|':
3765 if (maska || maskb) {
3766 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003767 maska ^= PyLong_MASK;
3768 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003769 negz = -1;
3770 }
3771 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003772 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003773
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003774 /* JRH: The original logic here was to allocate the result value (z)
3775 as the longer of the two operands. However, there are some cases
3776 where the result is guaranteed to be shorter than that: AND of two
3777 positives, OR of two negatives: use the shorter number. AND with
3778 mixed signs: use the positive number. OR with mixed signs: use the
3779 negative number. After the transformations above, op will be '&'
3780 iff one of these cases applies, and mask will be non-0 for operands
3781 whose length should be ignored.
3782 */
3783
Christian Heimes90aa7642007-12-19 02:45:37 +00003784 size_a = Py_SIZE(a);
3785 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003786 size_z = op == '&'
3787 ? (maska
3788 ? size_b
3789 : (maskb ? size_a : MIN(size_a, size_b)))
3790 : MAX(size_a, size_b);
3791 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003792 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003793 Py_DECREF(a);
3794 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003795 return NULL;
3796 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003797
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003798 for (i = 0; i < size_z; ++i) {
3799 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3800 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3801 switch (op) {
3802 case '&': z->ob_digit[i] = diga & digb; break;
3803 case '|': z->ob_digit[i] = diga | digb; break;
3804 case '^': z->ob_digit[i] = diga ^ digb; break;
3805 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003806 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003807
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003808 Py_DECREF(a);
3809 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003810 z = long_normalize(z);
3811 if (negz == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003812 return (PyObject *) maybe_small_long(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003813 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003814 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003815 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003816}
3817
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003818static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003819long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003820{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003821 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003822 CHECK_BINOP(a, b);
3823 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003824 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003825}
3826
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003827static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003828long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003829{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003830 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003831 CHECK_BINOP(a, b);
3832 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003833 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003834}
3835
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003836static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003837long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003838{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003839 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003840 CHECK_BINOP(a, b);
3841 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003842 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003843}
3844
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003845static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003846long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003847{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003848 if (PyLong_CheckExact(v))
3849 Py_INCREF(v);
3850 else
3851 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003852 return v;
3853}
3854
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003855static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003856long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003857{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003858 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003859 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003860 if (result == -1.0 && PyErr_Occurred())
3861 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003862 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003863}
3864
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003865static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003866long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003867
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868static PyObject *
3869long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3870{
3871 PyObject *x = NULL;
3872 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003873 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874
Guido van Rossumbef14172001-08-29 15:47:46 +00003875 if (type != &PyLong_Type)
3876 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003877 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003878 &x, &base))
3879 return NULL;
3880 if (x == NULL)
3881 return PyLong_FromLong(0L);
3882 if (base == -909)
3883 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003884 else if (PyUnicode_Check(x))
3885 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3886 PyUnicode_GET_SIZE(x),
3887 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003888 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003889 /* Since PyLong_FromString doesn't have a length parameter,
3890 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003891 char *string;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003892 Py_ssize_t size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003893 if (PyByteArray_Check(x))
3894 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003895 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003896 string = PyBytes_AS_STRING(x);
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003897 if (strlen(string) != (size_t)size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003898 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003899 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003900 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003901 "invalid literal for int() with base %d: %R",
3902 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003903 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003904 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003905 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003906 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003907 else {
3908 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003909 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003910 return NULL;
3911 }
3912}
3913
Guido van Rossumbef14172001-08-29 15:47:46 +00003914/* Wimpy, slow approach to tp_new calls for subtypes of long:
3915 first create a regular long from whatever arguments we got,
3916 then allocate a subtype instance and initialize it from
3917 the regular long. The regular long is then thrown away.
3918*/
3919static PyObject *
3920long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3921{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003922 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003923 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003924
3925 assert(PyType_IsSubtype(type, &PyLong_Type));
3926 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3927 if (tmp == NULL)
3928 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003929 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003930 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003931 if (n < 0)
3932 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003933 newobj = (PyLongObject *)type->tp_alloc(type, n);
3934 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003935 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003936 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003937 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003938 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003939 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003940 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003941 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003942 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003943 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003944}
3945
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003946static PyObject *
3947long_getnewargs(PyLongObject *v)
3948{
3949 return Py_BuildValue("(N)", _PyLong_Copy(v));
3950}
3951
Guido van Rossumb43daf72007-08-01 18:08:08 +00003952static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00003953long_get0(PyLongObject *v, void *context) {
3954 return PyLong_FromLong(0L);
3955}
3956
3957static PyObject *
3958long_get1(PyLongObject *v, void *context) {
3959 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003960}
3961
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003962static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003963long__format__(PyObject *self, PyObject *args)
3964{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003965 PyObject *format_spec;
3966
3967 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3968 return NULL;
3969 return _PyLong_FormatAdvanced(self,
3970 PyUnicode_AS_UNICODE(format_spec),
3971 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003972}
3973
Eric Smith8c663262007-08-25 02:26:07 +00003974static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003975long_round(PyObject *self, PyObject *args)
3976{
Mark Dickinson1124e712009-01-28 21:25:58 +00003977 PyObject *o_ndigits=NULL, *temp;
3978 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
3979 int errcode;
3980 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003981
Mark Dickinson1124e712009-01-28 21:25:58 +00003982 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
3983 the straightforward method is:
3984
3985 (1) divide by 10**n
3986 (2) round to nearest integer (round to even in case of tie)
3987 (3) multiply result by 10**n.
3988
3989 But the rounding step involves examining the fractional part of the
3990 quotient to see whether it's greater than 0.5 or not. Since we
3991 want to do the whole calculation in integer arithmetic, it's
3992 simpler to do:
3993
3994 (1) divide by (10**n)/2
3995 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
3996 (3) multiply result by (10**n)/2.
3997
3998 Then all we need to know about the fractional part of the quotient
3999 arising in step (2) is whether it's zero or not.
4000
4001 Doing both a multiplication and division is wasteful, and is easily
4002 avoided if we just figure out how much to adjust the original input
4003 by to do the rounding.
4004
4005 Here's the whole algorithm expressed in Python.
4006
4007 def round(self, ndigits = None):
4008 """round(int, int) -> int"""
4009 if ndigits is None or ndigits >= 0:
4010 return self
4011 pow = 10**-ndigits >> 1
4012 q, r = divmod(self, pow)
4013 self -= r
4014 if (q & 1 != 0):
4015 if (q & 2 == r == 0):
4016 self -= pow
4017 else:
4018 self += pow
4019 return self
4020
4021 */
4022 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4023 return NULL;
4024 if (o_ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004025 return long_long(self);
4026
Mark Dickinson1124e712009-01-28 21:25:58 +00004027 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
4028 if (ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004029 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004030
4031 if (Py_SIZE(ndigits) >= 0) {
4032 Py_DECREF(ndigits);
4033 return long_long(self);
4034 }
4035
4036 Py_INCREF(self); /* to keep refcounting simple */
4037 /* we now own references to self, ndigits */
4038
4039 /* pow = 10 ** -ndigits >> 1 */
4040 pow = (PyLongObject *)PyLong_FromLong(10L);
4041 if (pow == NULL)
4042 goto error;
4043 temp = long_neg(ndigits);
4044 Py_DECREF(ndigits);
4045 ndigits = (PyLongObject *)temp;
4046 if (ndigits == NULL)
4047 goto error;
4048 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
4049 Py_DECREF(pow);
4050 pow = (PyLongObject *)temp;
4051 if (pow == NULL)
4052 goto error;
4053 assert(PyLong_Check(pow)); /* check long_pow returned a long */
4054 one = (PyLongObject *)PyLong_FromLong(1L);
4055 if (one == NULL)
4056 goto error;
4057 temp = long_rshift(pow, one);
4058 Py_DECREF(one);
4059 Py_DECREF(pow);
4060 pow = (PyLongObject *)temp;
4061 if (pow == NULL)
4062 goto error;
4063
4064 /* q, r = divmod(self, pow) */
4065 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
4066 if (errcode == -1)
4067 goto error;
4068
4069 /* self -= r */
4070 temp = long_sub((PyLongObject *)self, r);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004071 Py_DECREF(self);
Mark Dickinson1124e712009-01-28 21:25:58 +00004072 self = temp;
4073 if (self == NULL)
4074 goto error;
4075
4076 /* get value of quotient modulo 4 */
4077 if (Py_SIZE(q) == 0)
4078 q_mod_4 = 0;
4079 else if (Py_SIZE(q) > 0)
4080 q_mod_4 = q->ob_digit[0] & 3;
4081 else
4082 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
4083
4084 if ((q_mod_4 & 1) == 1) {
4085 /* q is odd; round self up or down by adding or subtracting pow */
4086 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
4087 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
4088 else
4089 temp = (PyObject *)long_add((PyLongObject *)self, pow);
4090 Py_DECREF(self);
4091 self = temp;
4092 if (self == NULL)
4093 goto error;
4094 }
4095 Py_DECREF(q);
4096 Py_DECREF(r);
4097 Py_DECREF(pow);
4098 Py_DECREF(ndigits);
4099 return self;
4100
4101 error:
4102 Py_XDECREF(q);
4103 Py_XDECREF(r);
4104 Py_XDECREF(pow);
4105 Py_XDECREF(self);
4106 Py_XDECREF(ndigits);
4107 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004108}
4109
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004110static PyObject *
4111long_sizeof(PyLongObject *v)
4112{
4113 Py_ssize_t res;
4114
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004115 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004116 return PyLong_FromSsize_t(res);
4117}
4118
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004119static PyObject *
4120long_bit_length(PyLongObject *v)
4121{
4122 PyLongObject *result, *x, *y;
4123 Py_ssize_t ndigits, msd_bits = 0;
4124 digit msd;
4125
4126 assert(v != NULL);
4127 assert(PyLong_Check(v));
4128
4129 ndigits = ABS(Py_SIZE(v));
4130 if (ndigits == 0)
4131 return PyLong_FromLong(0);
4132
4133 msd = v->ob_digit[ndigits-1];
4134 while (msd >= 32) {
4135 msd_bits += 6;
4136 msd >>= 6;
4137 }
4138 msd_bits += (long)(BitLengthTable[msd]);
4139
4140 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4141 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
4142
4143 /* expression above may overflow; use Python integers instead */
4144 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4145 if (result == NULL)
4146 return NULL;
4147 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4148 if (x == NULL)
4149 goto error;
4150 y = (PyLongObject *)long_mul(result, x);
4151 Py_DECREF(x);
4152 if (y == NULL)
4153 goto error;
4154 Py_DECREF(result);
4155 result = y;
4156
4157 x = (PyLongObject *)PyLong_FromLong(msd_bits);
4158 if (x == NULL)
4159 goto error;
4160 y = (PyLongObject *)long_add(result, x);
4161 Py_DECREF(x);
4162 if (y == NULL)
4163 goto error;
4164 Py_DECREF(result);
4165 result = y;
4166
4167 return (PyObject *)result;
4168
4169error:
4170 Py_DECREF(result);
4171 return NULL;
4172}
4173
4174PyDoc_STRVAR(long_bit_length_doc,
4175"int.bit_length() -> int\n\
4176\n\
4177Number of bits necessary to represent self in binary.\n\
4178>>> bin(37)\n\
4179'0b100101'\n\
4180>>> (37).bit_length()\n\
41816");
4182
Christian Heimes53876d92008-04-19 00:31:39 +00004183#if 0
4184static PyObject *
4185long_is_finite(PyObject *v)
4186{
4187 Py_RETURN_TRUE;
4188}
4189#endif
4190
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004191static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00004192 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4193 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004194 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4195 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004196#if 0
4197 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4198 "Returns always True."},
4199#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004200 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4201 "Truncating an Integral returns itself."},
4202 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4203 "Flooring an Integral returns itself."},
4204 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4205 "Ceiling of an Integral returns itself."},
4206 {"__round__", (PyCFunction)long_round, METH_VARARGS,
Mark Dickinson1124e712009-01-28 21:25:58 +00004207 "Rounding an Integral returns itself.\n"
4208 "Rounding with an ndigits argument also returns an integer."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004209 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00004210 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004211 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4212 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004213 {NULL, NULL} /* sentinel */
4214};
4215
Guido van Rossumb43daf72007-08-01 18:08:08 +00004216static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004217 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004218 (getter)long_long, (setter)NULL,
4219 "the real part of a complex number",
4220 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004221 {"imag",
4222 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004223 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004224 NULL},
4225 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004226 (getter)long_long, (setter)NULL,
4227 "the numerator of a rational number in lowest terms",
4228 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004229 {"denominator",
4230 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004231 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004232 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004233 {NULL} /* Sentinel */
4234};
4235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004236PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004237"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004238\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004239Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004240point argument will be truncated towards zero (this does not include a\n\
4241string representation of a floating point number!) When converting a\n\
4242string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004243converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004244
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004245static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00004246 (binaryfunc) long_add, /*nb_add*/
4247 (binaryfunc) long_sub, /*nb_subtract*/
4248 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004249 long_mod, /*nb_remainder*/
4250 long_divmod, /*nb_divmod*/
4251 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004252 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004253 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004254 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00004255 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004256 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004257 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004258 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004259 long_and, /*nb_and*/
4260 long_xor, /*nb_xor*/
4261 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004262 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00004263 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004264 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00004265 0, /* nb_inplace_add */
4266 0, /* nb_inplace_subtract */
4267 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00004268 0, /* nb_inplace_remainder */
4269 0, /* nb_inplace_power */
4270 0, /* nb_inplace_lshift */
4271 0, /* nb_inplace_rshift */
4272 0, /* nb_inplace_and */
4273 0, /* nb_inplace_xor */
4274 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004275 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00004276 long_true_divide, /* nb_true_divide */
4277 0, /* nb_inplace_floor_divide */
4278 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004279 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004280};
4281
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004282PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004283 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00004284 "int", /* tp_name */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004285 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004287 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004288 0, /* tp_print */
4289 0, /* tp_getattr */
4290 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00004291 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004292 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293 &long_as_number, /* tp_as_number */
4294 0, /* tp_as_sequence */
4295 0, /* tp_as_mapping */
4296 (hashfunc)long_hash, /* tp_hash */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004297 0, /* tp_call */
4298 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299 PyObject_GenericGetAttr, /* tp_getattro */
4300 0, /* tp_setattro */
4301 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00004302 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4303 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004304 long_doc, /* tp_doc */
4305 0, /* tp_traverse */
4306 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00004307 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004308 0, /* tp_weaklistoffset */
4309 0, /* tp_iter */
4310 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004311 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004312 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00004313 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004314 0, /* tp_base */
4315 0, /* tp_dict */
4316 0, /* tp_descr_get */
4317 0, /* tp_descr_set */
4318 0, /* tp_dictoffset */
4319 0, /* tp_init */
4320 0, /* tp_alloc */
4321 long_new, /* tp_new */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004322 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004323};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004324
Mark Dickinsonbd792642009-03-18 20:06:12 +00004325static PyTypeObject Int_InfoType;
4326
4327PyDoc_STRVAR(int_info__doc__,
4328"sys.int_info\n\
4329\n\
4330A struct sequence that holds information about Python's\n\
4331internal representation of integers. The attributes are read only.");
4332
4333static PyStructSequence_Field int_info_fields[] = {
4334 {"bits_per_digit", "size of a digit in bits"},
4335 {"sizeof_digit", "size in bytes of the C type used to "
4336 "represent a digit"},
4337 {NULL, NULL}
4338};
4339
4340static PyStructSequence_Desc int_info_desc = {
4341 "sys.int_info", /* name */
4342 int_info__doc__, /* doc */
4343 int_info_fields, /* fields */
4344 2 /* number of fields */
4345};
4346
4347PyObject *
4348PyLong_GetInfo(void)
4349{
4350 PyObject* int_info;
4351 int field = 0;
4352 int_info = PyStructSequence_New(&Int_InfoType);
4353 if (int_info == NULL)
4354 return NULL;
Mark Dickinson0bdab682009-04-02 18:41:40 +00004355 PyStructSequence_SET_ITEM(int_info, field++,
4356 PyLong_FromLong(PyLong_SHIFT));
4357 PyStructSequence_SET_ITEM(int_info, field++,
4358 PyLong_FromLong(sizeof(digit)));
Mark Dickinsonbd792642009-03-18 20:06:12 +00004359 if (PyErr_Occurred()) {
4360 Py_CLEAR(int_info);
4361 return NULL;
4362 }
4363 return int_info;
4364}
4365
Guido van Rossumddefaf32007-01-14 03:31:43 +00004366int
4367_PyLong_Init(void)
4368{
4369#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004370 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004371 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004372
4373 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4374 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4375 if (Py_TYPE(v) == &PyLong_Type) {
4376 /* The element is already initialized, most likely
4377 * the Python interpreter was initialized before.
4378 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00004379 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004380 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004381
Christian Heimes48aa4b12008-02-01 16:56:30 +00004382 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4383 _Py_NewReference(op);
4384 /* _Py_NewReference sets the ref count to 1 but
4385 * the ref count might be larger. Set the refcnt
4386 * to the original refcnt + 1 */
4387 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004388 assert(Py_SIZE(op) == size);
4389 assert(v->ob_digit[0] == abs(ival));
4390 }
4391 else {
4392 PyObject_INIT(v, &PyLong_Type);
4393 }
4394 Py_SIZE(v) = size;
4395 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004396 }
4397#endif
Mark Dickinsonbd792642009-03-18 20:06:12 +00004398 /* initialize int_info */
4399 if (Int_InfoType.tp_name == 0)
4400 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
4401
Guido van Rossumddefaf32007-01-14 03:31:43 +00004402 return 1;
4403}
4404
4405void
4406PyLong_Fini(void)
4407{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004408 /* Integers are currently statically allocated. Py_DECREF is not
4409 needed, but Python must forget about the reference or multiple
4410 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004411#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004412 int i;
4413 PyLongObject *v = small_ints;
4414 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4415 _Py_DEC_REFTOTAL;
4416 _Py_ForgetReference((PyObject*)v);
4417 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004418#endif
4419}