blob: 85b33530a70ea8bb63388a18d26e2e80282bb7c9 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
33int quick_int_allocs, quick_neg_int_allocs;
34#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
49#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
51 return get_small_int((sdigit)ival); \
52 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055maybe_small_long(PyLongObject *v)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (v && ABS(Py_SIZE(v)) <= 1) {
58 sdigit ival = MEDIUM_VALUE(v);
59 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
75 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
76 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000097#define SIGCHECK(PyTryBlock) \
98 do { \
99 if (PyErr_CheckSignals()) PyTryBlock \
100 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
116 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyLongObject *result;
129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
140 size*sizeof(digit));
141 if (!result) {
142 PyErr_NoMemory();
143 return NULL;
144 }
145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyLongObject *result;
152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 assert(src != NULL);
155 i = Py_SIZE(src);
156 if (i < 0)
157 i = -(i);
158 if (i < 2) {
159 sdigit ival = src->ob_digit[0];
160 if (Py_SIZE(src) < 0)
161 ival = -ival;
162 CHECK_SMALL_INT(ival);
163 }
164 result = _PyLong_New(i);
165 if (result != NULL) {
166 Py_SIZE(result) = Py_SIZE(src);
167 while (--i >= 0)
168 result->ob_digit[i] = src->ob_digit[i];
169 }
170 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000171}
172
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000173/* Create a new long int object from a C long int */
174
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000176PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 PyLongObject *v;
179 unsigned long abs_ival;
180 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
181 int ndigits = 0;
182 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (ival < 0) {
187 /* negate: can't write this as abs_ival = -ival since that
188 invokes undefined behaviour when ival is LONG_MIN */
189 abs_ival = 0U-(unsigned long)ival;
190 sign = -1;
191 }
192 else {
193 abs_ival = (unsigned long)ival;
194 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Fast path for single-digit ints */
197 if (!(abs_ival >> PyLong_SHIFT)) {
198 v = _PyLong_New(1);
199 if (v) {
200 Py_SIZE(v) = sign;
201 v->ob_digit[0] = Py_SAFE_DOWNCAST(
202 abs_ival, unsigned long, digit);
203 }
204 return (PyObject*)v;
205 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000206
Mark Dickinson249b8982009-04-27 19:41:00 +0000207#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* 2 digits */
209 if (!(abs_ival >> 2*PyLong_SHIFT)) {
210 v = _PyLong_New(2);
211 if (v) {
212 Py_SIZE(v) = 2*sign;
213 v->ob_digit[0] = Py_SAFE_DOWNCAST(
214 abs_ival & PyLong_MASK, unsigned long, digit);
215 v->ob_digit[1] = Py_SAFE_DOWNCAST(
216 abs_ival >> PyLong_SHIFT, unsigned long, digit);
217 }
218 return (PyObject*)v;
219 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000220#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 /* Larger numbers: loop to determine number of digits */
223 t = abs_ival;
224 while (t) {
225 ++ndigits;
226 t >>= PyLong_SHIFT;
227 }
228 v = _PyLong_New(ndigits);
229 if (v != NULL) {
230 digit *p = v->ob_digit;
231 Py_SIZE(v) = ndigits*sign;
232 t = abs_ival;
233 while (t) {
234 *p++ = Py_SAFE_DOWNCAST(
235 t & PyLong_MASK, unsigned long, digit);
236 t >>= PyLong_SHIFT;
237 }
238 }
239 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000240}
241
Guido van Rossum53756b11997-01-03 17:14:46 +0000242/* Create a new long int object from a C unsigned long int */
243
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000245PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyLongObject *v;
248 unsigned long t;
249 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 if (ival < PyLong_BASE)
252 return PyLong_FromLong(ival);
253 /* Count the number of Python digits. */
254 t = (unsigned long)ival;
255 while (t) {
256 ++ndigits;
257 t >>= PyLong_SHIFT;
258 }
259 v = _PyLong_New(ndigits);
260 if (v != NULL) {
261 digit *p = v->ob_digit;
262 Py_SIZE(v) = ndigits;
263 while (ival) {
264 *p++ = (digit)(ival & PyLong_MASK);
265 ival >>= PyLong_SHIFT;
266 }
267 }
268 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000269}
270
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000271/* Create a new long int object from a C double */
272
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000273PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 PyLongObject *v;
277 double frac;
278 int i, ndig, expo, neg;
279 neg = 0;
280 if (Py_IS_INFINITY(dval)) {
281 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000282 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return NULL;
284 }
285 if (Py_IS_NAN(dval)) {
286 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000287 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 return NULL;
289 }
290 if (dval < 0.0) {
291 neg = 1;
292 dval = -dval;
293 }
294 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
295 if (expo <= 0)
296 return PyLong_FromLong(0L);
297 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
298 v = _PyLong_New(ndig);
299 if (v == NULL)
300 return NULL;
301 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
302 for (i = ndig; --i >= 0; ) {
303 digit bits = (digit)frac;
304 v->ob_digit[i] = bits;
305 frac = frac - (double)bits;
306 frac = ldexp(frac, PyLong_SHIFT);
307 }
308 if (neg)
309 Py_SIZE(v) = -(Py_SIZE(v));
310 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000311}
312
Thomas Wouters89f507f2006-12-13 04:49:30 +0000313/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
314 * anything about what happens when a signed integer operation overflows,
315 * and some compilers think they're doing you a favor by being "clever"
316 * then. The bit pattern for the largest postive signed long is
317 * (unsigned long)LONG_MAX, and for the smallest negative signed long
318 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
319 * However, some other compilers warn about applying unary minus to an
320 * unsigned operand. Hence the weird "0-".
321 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
323#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000324
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000325/* Get a C long int from a long int object.
326 Returns -1 and sets an error condition if overflow occurs. */
327
328long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000329PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 /* This version by Tim Peters */
332 register PyLongObject *v;
333 unsigned long x, prev;
334 long res;
335 Py_ssize_t i;
336 int sign;
337 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 *overflow = 0;
340 if (vv == NULL) {
341 PyErr_BadInternalCall();
342 return -1;
343 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 if (!PyLong_Check(vv)) {
346 PyNumberMethods *nb;
347 nb = vv->ob_type->tp_as_number;
348 if (nb == NULL || nb->nb_int == NULL) {
349 PyErr_SetString(PyExc_TypeError,
350 "an integer is required");
351 return -1;
352 }
353 vv = (*nb->nb_int) (vv);
354 if (vv == NULL)
355 return -1;
356 do_decref = 1;
357 if (!PyLong_Check(vv)) {
358 Py_DECREF(vv);
359 PyErr_SetString(PyExc_TypeError,
360 "nb_int should return int object");
361 return -1;
362 }
363 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 res = -1;
366 v = (PyLongObject *)vv;
367 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 switch (i) {
370 case -1:
371 res = -(sdigit)v->ob_digit[0];
372 break;
373 case 0:
374 res = 0;
375 break;
376 case 1:
377 res = v->ob_digit[0];
378 break;
379 default:
380 sign = 1;
381 x = 0;
382 if (i < 0) {
383 sign = -1;
384 i = -(i);
385 }
386 while (--i >= 0) {
387 prev = x;
388 x = (x << PyLong_SHIFT) | v->ob_digit[i];
389 if ((x >> PyLong_SHIFT) != prev) {
390 *overflow = sign;
391 goto exit;
392 }
393 }
394 /* Haven't lost any bits, but casting to long requires extra
395 * care (see comment above).
396 */
397 if (x <= (unsigned long)LONG_MAX) {
398 res = (long)x * sign;
399 }
400 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
401 res = LONG_MIN;
402 }
403 else {
404 *overflow = sign;
405 /* res is already set to -1 */
406 }
407 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000408 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (do_decref) {
410 Py_DECREF(vv);
411 }
412 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000413}
414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000416PyLong_AsLong(PyObject *obj)
417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 int overflow;
419 long result = PyLong_AsLongAndOverflow(obj, &overflow);
420 if (overflow) {
421 /* XXX: could be cute and give a different
422 message for overflow == -1 */
423 PyErr_SetString(PyExc_OverflowError,
424 "Python int too large to convert to C long");
425 }
426 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000427}
428
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000429/* Get a Py_ssize_t from a long int object.
430 Returns -1 and sets an error condition if overflow occurs. */
431
432Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000433PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 register PyLongObject *v;
435 size_t x, prev;
436 Py_ssize_t i;
437 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (vv == NULL) {
440 PyErr_BadInternalCall();
441 return -1;
442 }
443 if (!PyLong_Check(vv)) {
444 PyErr_SetString(PyExc_TypeError, "an integer is required");
445 return -1;
446 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 v = (PyLongObject *)vv;
449 i = Py_SIZE(v);
450 switch (i) {
451 case -1: return -(sdigit)v->ob_digit[0];
452 case 0: return 0;
453 case 1: return v->ob_digit[0];
454 }
455 sign = 1;
456 x = 0;
457 if (i < 0) {
458 sign = -1;
459 i = -(i);
460 }
461 while (--i >= 0) {
462 prev = x;
463 x = (x << PyLong_SHIFT) | v->ob_digit[i];
464 if ((x >> PyLong_SHIFT) != prev)
465 goto overflow;
466 }
467 /* Haven't lost any bits, but casting to a signed type requires
468 * extra care (see comment above).
469 */
470 if (x <= (size_t)PY_SSIZE_T_MAX) {
471 return (Py_ssize_t)x * sign;
472 }
473 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
474 return PY_SSIZE_T_MIN;
475 }
476 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000477
Mark Dickinson22b20182010-05-10 21:27:53 +0000478 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyErr_SetString(PyExc_OverflowError,
480 "Python int too large to convert to C ssize_t");
481 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000482}
483
Guido van Rossumd8c80482002-08-13 00:24:58 +0000484/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000485 Returns -1 and sets an error condition if overflow occurs. */
486
487unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000488PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 register PyLongObject *v;
491 unsigned long x, prev;
492 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (vv == NULL) {
495 PyErr_BadInternalCall();
496 return (unsigned long)-1;
497 }
498 if (!PyLong_Check(vv)) {
499 PyErr_SetString(PyExc_TypeError, "an integer is required");
500 return (unsigned long)-1;
501 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 v = (PyLongObject *)vv;
504 i = Py_SIZE(v);
505 x = 0;
506 if (i < 0) {
507 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000508 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 return (unsigned long) -1;
510 }
511 switch (i) {
512 case 0: return 0;
513 case 1: return v->ob_digit[0];
514 }
515 while (--i >= 0) {
516 prev = x;
517 x = (x << PyLong_SHIFT) | v->ob_digit[i];
518 if ((x >> PyLong_SHIFT) != prev) {
519 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000520 "python int too large to convert "
521 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 return (unsigned long) -1;
523 }
524 }
525 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000526}
527
Stefan Krahb77c6c62011-09-12 16:22:47 +0200528/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
529 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000530
531size_t
532PyLong_AsSize_t(PyObject *vv)
533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 register PyLongObject *v;
535 size_t x, prev;
536 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (vv == NULL) {
539 PyErr_BadInternalCall();
540 return (size_t) -1;
541 }
542 if (!PyLong_Check(vv)) {
543 PyErr_SetString(PyExc_TypeError, "an integer is required");
544 return (size_t)-1;
545 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 v = (PyLongObject *)vv;
548 i = Py_SIZE(v);
549 x = 0;
550 if (i < 0) {
551 PyErr_SetString(PyExc_OverflowError,
552 "can't convert negative value to size_t");
553 return (size_t) -1;
554 }
555 switch (i) {
556 case 0: return 0;
557 case 1: return v->ob_digit[0];
558 }
559 while (--i >= 0) {
560 prev = x;
561 x = (x << PyLong_SHIFT) | v->ob_digit[i];
562 if ((x >> PyLong_SHIFT) != prev) {
563 PyErr_SetString(PyExc_OverflowError,
564 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200565 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 }
567 }
568 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000569}
570
Thomas Hellera4ea6032003-04-17 18:55:45 +0000571/* Get a C unsigned long int from a long int object, ignoring the high bits.
572 Returns -1 and sets an error condition if an error occurs. */
573
Guido van Rossumddefaf32007-01-14 03:31:43 +0000574static unsigned long
575_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 register PyLongObject *v;
578 unsigned long x;
579 Py_ssize_t i;
580 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 if (vv == NULL || !PyLong_Check(vv)) {
583 PyErr_BadInternalCall();
584 return (unsigned long) -1;
585 }
586 v = (PyLongObject *)vv;
587 i = Py_SIZE(v);
588 switch (i) {
589 case 0: return 0;
590 case 1: return v->ob_digit[0];
591 }
592 sign = 1;
593 x = 0;
594 if (i < 0) {
595 sign = -1;
596 i = -i;
597 }
598 while (--i >= 0) {
599 x = (x << PyLong_SHIFT) | v->ob_digit[i];
600 }
601 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000602}
603
Guido van Rossumddefaf32007-01-14 03:31:43 +0000604unsigned long
605PyLong_AsUnsignedLongMask(register PyObject *op)
606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyNumberMethods *nb;
608 PyLongObject *lo;
609 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (op && PyLong_Check(op))
612 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
615 nb->nb_int == NULL) {
616 PyErr_SetString(PyExc_TypeError, "an integer is required");
617 return (unsigned long)-1;
618 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 lo = (PyLongObject*) (*nb->nb_int) (op);
621 if (lo == NULL)
622 return (unsigned long)-1;
623 if (PyLong_Check(lo)) {
624 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
625 Py_DECREF(lo);
626 if (PyErr_Occurred())
627 return (unsigned long)-1;
628 return val;
629 }
630 else
631 {
632 Py_DECREF(lo);
633 PyErr_SetString(PyExc_TypeError,
634 "nb_int should return int object");
635 return (unsigned long)-1;
636 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000637}
638
Tim Peters5b8132f2003-01-31 15:52:05 +0000639int
640_PyLong_Sign(PyObject *vv)
641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 assert(v != NULL);
645 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000648}
649
Tim Petersbaefd9e2003-01-28 20:37:45 +0000650size_t
651_PyLong_NumBits(PyObject *vv)
652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 PyLongObject *v = (PyLongObject *)vv;
654 size_t result = 0;
655 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 assert(v != NULL);
658 assert(PyLong_Check(v));
659 ndigits = ABS(Py_SIZE(v));
660 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
661 if (ndigits > 0) {
662 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 result = (ndigits - 1) * PyLong_SHIFT;
665 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
666 goto Overflow;
667 do {
668 ++result;
669 if (result == 0)
670 goto Overflow;
671 msd >>= 1;
672 } while (msd);
673 }
674 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000675
Mark Dickinson22b20182010-05-10 21:27:53 +0000676 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
678 "to express in a platform size_t");
679 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000680}
681
Tim Peters2a9b3672001-06-11 21:23:58 +0000682PyObject *
683_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000685{
Mark Dickinson22b20182010-05-10 21:27:53 +0000686 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 int incr; /* direction to move pstartbyte */
688 const unsigned char* pendbyte; /* MSB of bytes */
689 size_t numsignificantbytes; /* number of bytes that matter */
690 Py_ssize_t ndigits; /* number of Python long digits */
691 PyLongObject* v; /* result */
692 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (n == 0)
695 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (little_endian) {
698 pstartbyte = bytes;
699 pendbyte = bytes + n - 1;
700 incr = 1;
701 }
702 else {
703 pstartbyte = bytes + n - 1;
704 pendbyte = bytes;
705 incr = -1;
706 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (is_signed)
709 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200712 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 is positive, and leading 0xff bytes if negative. */
714 {
715 size_t i;
716 const unsigned char* p = pendbyte;
717 const int pincr = -incr; /* search MSB to LSB */
718 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 for (i = 0; i < n; ++i, p += pincr) {
721 if (*p != insignficant)
722 break;
723 }
724 numsignificantbytes = n - i;
725 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
726 actually has 2 significant bytes. OTOH, 0xff0001 ==
727 -0x00ffff, so we wouldn't *need* to bump it there; but we
728 do for 0xffff = -0x0001. To be safe without bothering to
729 check every case, bump it regardless. */
730 if (is_signed && numsignificantbytes < n)
731 ++numsignificantbytes;
732 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 /* How many Python long digits do we need? We have
735 8*numsignificantbytes bits, and each Python long digit has
736 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
737 /* catch overflow before it happens */
738 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
739 PyErr_SetString(PyExc_OverflowError,
740 "byte array too long to convert to int");
741 return NULL;
742 }
743 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
744 v = _PyLong_New(ndigits);
745 if (v == NULL)
746 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 /* Copy the bits over. The tricky parts are computing 2's-comp on
749 the fly for signed numbers, and dealing with the mismatch between
750 8-bit bytes and (probably) 15-bit Python digits.*/
751 {
752 size_t i;
753 twodigits carry = 1; /* for 2's-comp calculation */
754 twodigits accum = 0; /* sliding register */
755 unsigned int accumbits = 0; /* number of bits in accum */
756 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
759 twodigits thisbyte = *p;
760 /* Compute correction for 2's comp, if needed. */
761 if (is_signed) {
762 thisbyte = (0xff ^ thisbyte) + carry;
763 carry = thisbyte >> 8;
764 thisbyte &= 0xff;
765 }
766 /* Because we're going LSB to MSB, thisbyte is
767 more significant than what's already in accum,
768 so needs to be prepended to accum. */
769 accum |= (twodigits)thisbyte << accumbits;
770 accumbits += 8;
771 if (accumbits >= PyLong_SHIFT) {
772 /* There's enough to fill a Python digit. */
773 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000774 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 ++idigit;
776 accum >>= PyLong_SHIFT;
777 accumbits -= PyLong_SHIFT;
778 assert(accumbits < PyLong_SHIFT);
779 }
780 }
781 assert(accumbits < PyLong_SHIFT);
782 if (accumbits) {
783 assert(idigit < ndigits);
784 v->ob_digit[idigit] = (digit)accum;
785 ++idigit;
786 }
787 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 Py_SIZE(v) = is_signed ? -idigit : idigit;
790 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000791}
792
793int
794_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 unsigned char* bytes, size_t n,
796 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000799 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000801 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
803 digit carry; /* for computing 2's-comp */
804 size_t j; /* # bytes filled */
805 unsigned char* p; /* pointer to next byte in bytes */
806 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (Py_SIZE(v) < 0) {
811 ndigits = -(Py_SIZE(v));
812 if (!is_signed) {
813 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000814 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 return -1;
816 }
817 do_twos_comp = 1;
818 }
819 else {
820 ndigits = Py_SIZE(v);
821 do_twos_comp = 0;
822 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (little_endian) {
825 p = bytes;
826 pincr = 1;
827 }
828 else {
829 p = bytes + n - 1;
830 pincr = -1;
831 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 /* Copy over all the Python digits.
834 It's crucial that every Python digit except for the MSD contribute
835 exactly PyLong_SHIFT bits to the total, so first assert that the long is
836 normalized. */
837 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
838 j = 0;
839 accum = 0;
840 accumbits = 0;
841 carry = do_twos_comp ? 1 : 0;
842 for (i = 0; i < ndigits; ++i) {
843 digit thisdigit = v->ob_digit[i];
844 if (do_twos_comp) {
845 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
846 carry = thisdigit >> PyLong_SHIFT;
847 thisdigit &= PyLong_MASK;
848 }
849 /* Because we're going LSB to MSB, thisdigit is more
850 significant than what's already in accum, so needs to be
851 prepended to accum. */
852 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 /* The most-significant digit may be (probably is) at least
855 partly empty. */
856 if (i == ndigits - 1) {
857 /* Count # of sign bits -- they needn't be stored,
858 * although for signed conversion we need later to
859 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000860 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 while (s != 0) {
862 s >>= 1;
863 accumbits++;
864 }
865 }
866 else
867 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 /* Store as many bytes as possible. */
870 while (accumbits >= 8) {
871 if (j >= n)
872 goto Overflow;
873 ++j;
874 *p = (unsigned char)(accum & 0xff);
875 p += pincr;
876 accumbits -= 8;
877 accum >>= 8;
878 }
879 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 /* Store the straggler (if any). */
882 assert(accumbits < 8);
883 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
884 if (accumbits > 0) {
885 if (j >= n)
886 goto Overflow;
887 ++j;
888 if (do_twos_comp) {
889 /* Fill leading bits of the byte with sign bits
890 (appropriately pretending that the long had an
891 infinite supply of sign bits). */
892 accum |= (~(twodigits)0) << accumbits;
893 }
894 *p = (unsigned char)(accum & 0xff);
895 p += pincr;
896 }
897 else if (j == n && n > 0 && is_signed) {
898 /* The main loop filled the byte array exactly, so the code
899 just above didn't get to ensure there's a sign bit, and the
900 loop below wouldn't add one either. Make sure a sign bit
901 exists. */
902 unsigned char msb = *(p - pincr);
903 int sign_bit_set = msb >= 0x80;
904 assert(accumbits == 0);
905 if (sign_bit_set == do_twos_comp)
906 return 0;
907 else
908 goto Overflow;
909 }
Tim Peters05607ad2001-06-13 21:01:27 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 /* Fill remaining bytes with copies of the sign bit. */
912 {
913 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
914 for ( ; j < n; ++j, p += pincr)
915 *p = signbyte;
916 }
Tim Peters05607ad2001-06-13 21:01:27 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000919
Mark Dickinson22b20182010-05-10 21:27:53 +0000920 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
922 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000923
Tim Peters2a9b3672001-06-11 21:23:58 +0000924}
925
Guido van Rossum78694d91998-09-18 14:14:13 +0000926/* Create a new long (or int) object from a C pointer */
927
928PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000929PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000930{
Tim Peters70128a12001-06-16 08:48:40 +0000931#ifndef HAVE_LONG_LONG
932# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
933#endif
934#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000935# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000936#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* special-case null pointer */
938 if (!p)
939 return PyLong_FromLong(0);
940 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000941
Guido van Rossum78694d91998-09-18 14:14:13 +0000942}
943
944/* Get a C pointer from a long object (or an int object in some cases) */
945
946void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000947PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* This function will allow int or long objects. If vv is neither,
950 then the PyLong_AsLong*() functions will raise the exception:
951 PyExc_SystemError, "bad argument to internal function"
952 */
Tim Peters70128a12001-06-16 08:48:40 +0000953#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
957 x = PyLong_AsLong(vv);
958 else
959 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000960#else
Tim Peters70128a12001-06-16 08:48:40 +0000961
962#ifndef HAVE_LONG_LONG
963# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
964#endif
965#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000966# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000967#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
971 x = PyLong_AsLongLong(vv);
972 else
973 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000974
975#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (x == -1 && PyErr_Occurred())
978 return NULL;
979 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000980}
981
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000982#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000983
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000984/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000985 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000986 */
987
Tim Peterscf37dfc2001-06-14 18:42:50 +0000988#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000989#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000990
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000991/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000992
993PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000994PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 PyLongObject *v;
997 unsigned PY_LONG_LONG abs_ival;
998 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
999 int ndigits = 0;
1000 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 CHECK_SMALL_INT(ival);
1003 if (ival < 0) {
1004 /* avoid signed overflow on negation; see comments
1005 in PyLong_FromLong above. */
1006 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1007 negative = 1;
1008 }
1009 else {
1010 abs_ival = (unsigned PY_LONG_LONG)ival;
1011 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 /* Count the number of Python digits.
1014 We used to pick 5 ("big enough for anything"), but that's a
1015 waste of time and space given that 5*15 = 75 bits are rarely
1016 needed. */
1017 t = abs_ival;
1018 while (t) {
1019 ++ndigits;
1020 t >>= PyLong_SHIFT;
1021 }
1022 v = _PyLong_New(ndigits);
1023 if (v != NULL) {
1024 digit *p = v->ob_digit;
1025 Py_SIZE(v) = negative ? -ndigits : ndigits;
1026 t = abs_ival;
1027 while (t) {
1028 *p++ = (digit)(t & PyLong_MASK);
1029 t >>= PyLong_SHIFT;
1030 }
1031 }
1032 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001033}
1034
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001035/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001036
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001037PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001038PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyLongObject *v;
1041 unsigned PY_LONG_LONG t;
1042 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (ival < PyLong_BASE)
1045 return PyLong_FromLong((long)ival);
1046 /* Count the number of Python digits. */
1047 t = (unsigned PY_LONG_LONG)ival;
1048 while (t) {
1049 ++ndigits;
1050 t >>= PyLong_SHIFT;
1051 }
1052 v = _PyLong_New(ndigits);
1053 if (v != NULL) {
1054 digit *p = v->ob_digit;
1055 Py_SIZE(v) = ndigits;
1056 while (ival) {
1057 *p++ = (digit)(ival & PyLong_MASK);
1058 ival >>= PyLong_SHIFT;
1059 }
1060 }
1061 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001062}
1063
Martin v. Löwis18e16552006-02-15 17:27:45 +00001064/* Create a new long int object from a C Py_ssize_t. */
1065
1066PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001067PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyLongObject *v;
1070 size_t abs_ival;
1071 size_t t; /* unsigned so >> doesn't propagate sign bit */
1072 int ndigits = 0;
1073 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 CHECK_SMALL_INT(ival);
1076 if (ival < 0) {
1077 /* avoid signed overflow when ival = SIZE_T_MIN */
1078 abs_ival = (size_t)(-1-ival)+1;
1079 negative = 1;
1080 }
1081 else {
1082 abs_ival = (size_t)ival;
1083 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* Count the number of Python digits. */
1086 t = abs_ival;
1087 while (t) {
1088 ++ndigits;
1089 t >>= PyLong_SHIFT;
1090 }
1091 v = _PyLong_New(ndigits);
1092 if (v != NULL) {
1093 digit *p = v->ob_digit;
1094 Py_SIZE(v) = negative ? -ndigits : ndigits;
1095 t = abs_ival;
1096 while (t) {
1097 *p++ = (digit)(t & PyLong_MASK);
1098 t >>= PyLong_SHIFT;
1099 }
1100 }
1101 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001102}
1103
1104/* Create a new long int object from a C size_t. */
1105
1106PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001107PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyLongObject *v;
1110 size_t t;
1111 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 if (ival < PyLong_BASE)
1114 return PyLong_FromLong((long)ival);
1115 /* Count the number of Python digits. */
1116 t = ival;
1117 while (t) {
1118 ++ndigits;
1119 t >>= PyLong_SHIFT;
1120 }
1121 v = _PyLong_New(ndigits);
1122 if (v != NULL) {
1123 digit *p = v->ob_digit;
1124 Py_SIZE(v) = ndigits;
1125 while (ival) {
1126 *p++ = (digit)(ival & PyLong_MASK);
1127 ival >>= PyLong_SHIFT;
1128 }
1129 }
1130 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001131}
1132
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001133/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001134 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001135
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001136PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001137PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 PyLongObject *v;
1140 PY_LONG_LONG bytes;
1141 int one = 1;
1142 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (vv == NULL) {
1145 PyErr_BadInternalCall();
1146 return -1;
1147 }
1148 if (!PyLong_Check(vv)) {
1149 PyNumberMethods *nb;
1150 PyObject *io;
1151 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1152 nb->nb_int == NULL) {
1153 PyErr_SetString(PyExc_TypeError, "an integer is required");
1154 return -1;
1155 }
1156 io = (*nb->nb_int) (vv);
1157 if (io == NULL)
1158 return -1;
1159 if (PyLong_Check(io)) {
1160 bytes = PyLong_AsLongLong(io);
1161 Py_DECREF(io);
1162 return bytes;
1163 }
1164 Py_DECREF(io);
1165 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1166 return -1;
1167 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 v = (PyLongObject*)vv;
1170 switch(Py_SIZE(v)) {
1171 case -1: return -(sdigit)v->ob_digit[0];
1172 case 0: return 0;
1173 case 1: return v->ob_digit[0];
1174 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001175 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1176 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1179 if (res < 0)
1180 return (PY_LONG_LONG)-1;
1181 else
1182 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001183}
1184
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001185/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001186 Return -1 and set an error if overflow occurs. */
1187
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001188unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001189PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 PyLongObject *v;
1192 unsigned PY_LONG_LONG bytes;
1193 int one = 1;
1194 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001195
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001196 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyErr_BadInternalCall();
1198 return (unsigned PY_LONG_LONG)-1;
1199 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001200 if (!PyLong_Check(vv)) {
1201 PyErr_SetString(PyExc_TypeError, "an integer is required");
1202 return (unsigned PY_LONG_LONG)-1;
1203 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 v = (PyLongObject*)vv;
1206 switch(Py_SIZE(v)) {
1207 case 0: return 0;
1208 case 1: return v->ob_digit[0];
1209 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001210
Mark Dickinson22b20182010-05-10 21:27:53 +00001211 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1212 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1215 if (res < 0)
1216 return (unsigned PY_LONG_LONG)res;
1217 else
1218 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001219}
Tim Petersd1a7da62001-06-13 00:35:57 +00001220
Thomas Hellera4ea6032003-04-17 18:55:45 +00001221/* Get a C unsigned long int from a long int object, ignoring the high bits.
1222 Returns -1 and sets an error condition if an error occurs. */
1223
Guido van Rossumddefaf32007-01-14 03:31:43 +00001224static unsigned PY_LONG_LONG
1225_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 register PyLongObject *v;
1228 unsigned PY_LONG_LONG x;
1229 Py_ssize_t i;
1230 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (vv == NULL || !PyLong_Check(vv)) {
1233 PyErr_BadInternalCall();
1234 return (unsigned long) -1;
1235 }
1236 v = (PyLongObject *)vv;
1237 switch(Py_SIZE(v)) {
1238 case 0: return 0;
1239 case 1: return v->ob_digit[0];
1240 }
1241 i = Py_SIZE(v);
1242 sign = 1;
1243 x = 0;
1244 if (i < 0) {
1245 sign = -1;
1246 i = -i;
1247 }
1248 while (--i >= 0) {
1249 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1250 }
1251 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001252}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001253
1254unsigned PY_LONG_LONG
1255PyLong_AsUnsignedLongLongMask(register PyObject *op)
1256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 PyNumberMethods *nb;
1258 PyLongObject *lo;
1259 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (op && PyLong_Check(op))
1262 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1265 nb->nb_int == NULL) {
1266 PyErr_SetString(PyExc_TypeError, "an integer is required");
1267 return (unsigned PY_LONG_LONG)-1;
1268 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 lo = (PyLongObject*) (*nb->nb_int) (op);
1271 if (lo == NULL)
1272 return (unsigned PY_LONG_LONG)-1;
1273 if (PyLong_Check(lo)) {
1274 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1275 Py_DECREF(lo);
1276 if (PyErr_Occurred())
1277 return (unsigned PY_LONG_LONG)-1;
1278 return val;
1279 }
1280 else
1281 {
1282 Py_DECREF(lo);
1283 PyErr_SetString(PyExc_TypeError,
1284 "nb_int should return int object");
1285 return (unsigned PY_LONG_LONG)-1;
1286 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001287}
Tim Petersd1a7da62001-06-13 00:35:57 +00001288#undef IS_LITTLE_ENDIAN
1289
Mark Dickinson93f562c2010-01-30 10:30:15 +00001290/* Get a C long long int from a Python long or Python int object.
1291 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1292 on the sign of the result. Otherwise *overflow is 0.
1293
1294 For other errors (e.g., type error), returns -1 and sets an error
1295 condition.
1296*/
1297
1298PY_LONG_LONG
1299PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 /* This version by Tim Peters */
1302 register PyLongObject *v;
1303 unsigned PY_LONG_LONG x, prev;
1304 PY_LONG_LONG res;
1305 Py_ssize_t i;
1306 int sign;
1307 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 *overflow = 0;
1310 if (vv == NULL) {
1311 PyErr_BadInternalCall();
1312 return -1;
1313 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 if (!PyLong_Check(vv)) {
1316 PyNumberMethods *nb;
1317 nb = vv->ob_type->tp_as_number;
1318 if (nb == NULL || nb->nb_int == NULL) {
1319 PyErr_SetString(PyExc_TypeError,
1320 "an integer is required");
1321 return -1;
1322 }
1323 vv = (*nb->nb_int) (vv);
1324 if (vv == NULL)
1325 return -1;
1326 do_decref = 1;
1327 if (!PyLong_Check(vv)) {
1328 Py_DECREF(vv);
1329 PyErr_SetString(PyExc_TypeError,
1330 "nb_int should return int object");
1331 return -1;
1332 }
1333 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 res = -1;
1336 v = (PyLongObject *)vv;
1337 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 switch (i) {
1340 case -1:
1341 res = -(sdigit)v->ob_digit[0];
1342 break;
1343 case 0:
1344 res = 0;
1345 break;
1346 case 1:
1347 res = v->ob_digit[0];
1348 break;
1349 default:
1350 sign = 1;
1351 x = 0;
1352 if (i < 0) {
1353 sign = -1;
1354 i = -(i);
1355 }
1356 while (--i >= 0) {
1357 prev = x;
1358 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1359 if ((x >> PyLong_SHIFT) != prev) {
1360 *overflow = sign;
1361 goto exit;
1362 }
1363 }
1364 /* Haven't lost any bits, but casting to long requires extra
1365 * care (see comment above).
1366 */
1367 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1368 res = (PY_LONG_LONG)x * sign;
1369 }
1370 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1371 res = PY_LLONG_MIN;
1372 }
1373 else {
1374 *overflow = sign;
1375 /* res is already set to -1 */
1376 }
1377 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001378 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (do_decref) {
1380 Py_DECREF(vv);
1381 }
1382 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001383}
1384
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001385#endif /* HAVE_LONG_LONG */
1386
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001387#define CHECK_BINOP(v,w) \
1388 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001389 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1390 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001391 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001392
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001393/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1394 2**k if d is nonzero, else 0. */
1395
1396static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1398 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001399};
1400
1401static int
1402bits_in_digit(digit d)
1403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 int d_bits = 0;
1405 while (d >= 32) {
1406 d_bits += 6;
1407 d >>= 6;
1408 }
1409 d_bits += (int)BitLengthTable[d];
1410 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001411}
1412
Tim Peters877a2122002-08-12 05:09:36 +00001413/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1414 * is modified in place, by adding y to it. Carries are propagated as far as
1415 * x[m-1], and the remaining carry (0 or 1) is returned.
1416 */
1417static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001418v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 Py_ssize_t i;
1421 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 assert(m >= n);
1424 for (i = 0; i < n; ++i) {
1425 carry += x[i] + y[i];
1426 x[i] = carry & PyLong_MASK;
1427 carry >>= PyLong_SHIFT;
1428 assert((carry & 1) == carry);
1429 }
1430 for (; carry && i < m; ++i) {
1431 carry += x[i];
1432 x[i] = carry & PyLong_MASK;
1433 carry >>= PyLong_SHIFT;
1434 assert((carry & 1) == carry);
1435 }
1436 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001437}
1438
1439/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1440 * is modified in place, by subtracting y from it. Borrows are propagated as
1441 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1442 */
1443static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001444v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 Py_ssize_t i;
1447 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 assert(m >= n);
1450 for (i = 0; i < n; ++i) {
1451 borrow = x[i] - y[i] - borrow;
1452 x[i] = borrow & PyLong_MASK;
1453 borrow >>= PyLong_SHIFT;
1454 borrow &= 1; /* keep only 1 sign bit */
1455 }
1456 for (; borrow && i < m; ++i) {
1457 borrow = x[i] - borrow;
1458 x[i] = borrow & PyLong_MASK;
1459 borrow >>= PyLong_SHIFT;
1460 borrow &= 1;
1461 }
1462 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001463}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001464
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001465/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1466 * result in z[0:m], and return the d bits shifted out of the top.
1467 */
1468static digit
1469v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 Py_ssize_t i;
1472 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 assert(0 <= d && d < PyLong_SHIFT);
1475 for (i=0; i < m; i++) {
1476 twodigits acc = (twodigits)a[i] << d | carry;
1477 z[i] = (digit)acc & PyLong_MASK;
1478 carry = (digit)(acc >> PyLong_SHIFT);
1479 }
1480 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001481}
1482
1483/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1484 * result in z[0:m], and return the d bits shifted out of the bottom.
1485 */
1486static digit
1487v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 Py_ssize_t i;
1490 digit carry = 0;
1491 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 assert(0 <= d && d < PyLong_SHIFT);
1494 for (i=m; i-- > 0;) {
1495 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1496 carry = (digit)acc & mask;
1497 z[i] = (digit)(acc >> d);
1498 }
1499 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001500}
1501
Tim Peters212e6142001-07-14 12:23:19 +00001502/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1503 in pout, and returning the remainder. pin and pout point at the LSD.
1504 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001505 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001506 immutable. */
1507
1508static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001509inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 assert(n > 0 && n <= PyLong_MASK);
1514 pin += size;
1515 pout += size;
1516 while (--size >= 0) {
1517 digit hi;
1518 rem = (rem << PyLong_SHIFT) | *--pin;
1519 *--pout = hi = (digit)(rem / n);
1520 rem -= (twodigits)hi * n;
1521 }
1522 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001523}
1524
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001525/* Divide a long integer by a digit, returning both the quotient
1526 (as function result) and the remainder (through *prem).
1527 The sign of a is ignored; n should not be zero. */
1528
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001529static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001530divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 const Py_ssize_t size = ABS(Py_SIZE(a));
1533 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 assert(n > 0 && n <= PyLong_MASK);
1536 z = _PyLong_New(size);
1537 if (z == NULL)
1538 return NULL;
1539 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1540 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001541}
1542
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001543/* Convert a long integer to a base 10 string. Returns a new non-shared
1544 string. (Return value is non-shared so that callers can modify the
1545 returned value if necessary.) */
1546
1547static PyObject *
1548long_to_decimal_string(PyObject *aa)
1549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 PyLongObject *scratch, *a;
1551 PyObject *str;
1552 Py_ssize_t size, strlen, size_a, i, j;
1553 digit *pout, *pin, rem, tenpow;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001554 unsigned char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 a = (PyLongObject *)aa;
1558 if (a == NULL || !PyLong_Check(a)) {
1559 PyErr_BadInternalCall();
1560 return NULL;
1561 }
1562 size_a = ABS(Py_SIZE(a));
1563 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 /* quick and dirty upper bound for the number of digits
1566 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 But log2(a) < size_a * PyLong_SHIFT, and
1571 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1572 > 3 * _PyLong_DECIMAL_SHIFT
1573 */
1574 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1575 PyErr_SetString(PyExc_OverflowError,
1576 "long is too large to format");
1577 return NULL;
1578 }
1579 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1580 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1581 scratch = _PyLong_New(size);
1582 if (scratch == NULL)
1583 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 /* convert array of base _PyLong_BASE digits in pin to an array of
1586 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1587 Volume 2 (3rd edn), section 4.4, Method 1b). */
1588 pin = a->ob_digit;
1589 pout = scratch->ob_digit;
1590 size = 0;
1591 for (i = size_a; --i >= 0; ) {
1592 digit hi = pin[i];
1593 for (j = 0; j < size; j++) {
1594 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1595 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1596 pout[j] = (digit)(z - (twodigits)hi *
1597 _PyLong_DECIMAL_BASE);
1598 }
1599 while (hi) {
1600 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1601 hi /= _PyLong_DECIMAL_BASE;
1602 }
1603 /* check for keyboard interrupt */
1604 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001605 Py_DECREF(scratch);
1606 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001607 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 }
1609 /* pout should have at least one digit, so that the case when a = 0
1610 works correctly */
1611 if (size == 0)
1612 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 /* calculate exact length of output string, and allocate */
1615 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1616 tenpow = 10;
1617 rem = pout[size-1];
1618 while (rem >= tenpow) {
1619 tenpow *= 10;
1620 strlen++;
1621 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001622 str = PyUnicode_New(strlen, '9');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (str == NULL) {
1624 Py_DECREF(scratch);
1625 return NULL;
1626 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 /* fill the string right-to-left */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001629 assert(PyUnicode_KIND(str) == PyUnicode_1BYTE_KIND);
1630 p = PyUnicode_1BYTE_DATA(str) + strlen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 *p = '\0';
1632 /* pout[0] through pout[size-2] contribute exactly
1633 _PyLong_DECIMAL_SHIFT digits each */
1634 for (i=0; i < size - 1; i++) {
1635 rem = pout[i];
1636 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1637 *--p = '0' + rem % 10;
1638 rem /= 10;
1639 }
1640 }
1641 /* pout[size-1]: always produce at least one decimal digit */
1642 rem = pout[i];
1643 do {
1644 *--p = '0' + rem % 10;
1645 rem /= 10;
1646 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 /* and sign */
1649 if (negative)
1650 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 /* check we've counted correctly */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001653 assert(p == PyUnicode_1BYTE_DATA(str));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 Py_DECREF(scratch);
1655 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001656}
1657
Mark Dickinsoncd068122009-09-18 14:53:08 +00001658/* Convert a long int object to a string, using a given conversion base,
1659 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001660 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001661
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001662PyObject *
1663_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001666 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 Py_ssize_t i, sz;
1668 Py_ssize_t size_a;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 char *p;
1670 char sign = '\0';
1671 char *buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 assert(base == 2 || base == 8 || base == 10 || base == 16);
1675 if (base == 10)
1676 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (a == NULL || !PyLong_Check(a)) {
1679 PyErr_BadInternalCall();
1680 return NULL;
1681 }
1682 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 /* Compute a rough upper bound for the length of the string */
1685 switch (base) {
1686 case 16:
1687 bits = 4;
1688 break;
1689 case 8:
1690 bits = 3;
1691 break;
1692 case 2:
1693 bits = 1;
1694 break;
1695 default:
1696 assert(0); /* shouldn't ever get here */
1697 bits = 0; /* to silence gcc warning */
1698 }
1699 /* compute length of output string: allow 2 characters for prefix and
1700 1 for possible '-' sign. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001701 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT / sizeof(Py_UCS4)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 PyErr_SetString(PyExc_OverflowError,
1703 "int is too large to format");
1704 return NULL;
1705 }
1706 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1707 is safe from overflow */
1708 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
1709 assert(sz >= 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 buffer = PyMem_Malloc(sz);
1711 if (buffer == NULL) {
1712 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001714 }
1715 p = &buffer[sz];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 if (Py_SIZE(a) < 0)
1717 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 if (Py_SIZE(a) == 0) {
1720 *--p = '0';
1721 }
1722 else {
1723 /* JRH: special case for power-of-2 bases */
1724 twodigits accum = 0;
1725 int accumbits = 0; /* # of bits in accum */
1726 for (i = 0; i < size_a; ++i) {
1727 accum |= (twodigits)a->ob_digit[i] << accumbits;
1728 accumbits += PyLong_SHIFT;
1729 assert(accumbits >= bits);
1730 do {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001731 char cdigit;
1732 cdigit = (char)(accum & (base - 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 assert(p > buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 *--p = cdigit;
1736 accumbits -= bits;
1737 accum >>= bits;
1738 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1739 }
1740 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 if (base == 16)
1743 *--p = 'x';
1744 else if (base == 8)
1745 *--p = 'o';
1746 else /* (base == 2) */
1747 *--p = 'b';
1748 *--p = '0';
1749 if (sign)
1750 *--p = sign;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001751 v = PyUnicode_DecodeASCII(p, &buffer[sz] - p, NULL);
1752 PyMem_Free(buffer);
1753 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001754}
1755
Thomas Wouters477c8d52006-05-27 19:21:47 +00001756/* Table of digit values for 8-bit string -> integer conversion.
1757 * '0' maps to 0, ..., '9' maps to 9.
1758 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1759 * All other indices map to 37.
1760 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001761 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001762 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001763unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1765 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1766 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1767 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1768 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1769 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1770 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1771 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1772 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1773 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1774 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1775 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1776 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1777 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1778 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1779 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001780};
1781
1782/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001783 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1784 * non-digit (which may be *str!). A normalized long is returned.
1785 * The point to this routine is that it takes time linear in the number of
1786 * string characters.
1787 */
1788static PyLongObject *
1789long_from_binary_base(char **str, int base)
1790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 char *p = *str;
1792 char *start = p;
1793 int bits_per_char;
1794 Py_ssize_t n;
1795 PyLongObject *z;
1796 twodigits accum;
1797 int bits_in_accum;
1798 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1801 n = base;
1802 for (bits_per_char = -1; n; ++bits_per_char)
1803 n >>= 1;
1804 /* n <- total # of bits needed, while setting p to end-of-string */
1805 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1806 ++p;
1807 *str = p;
1808 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1809 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1810 if (n / bits_per_char < p - start) {
1811 PyErr_SetString(PyExc_ValueError,
1812 "int string too large to convert");
1813 return NULL;
1814 }
1815 n = n / PyLong_SHIFT;
1816 z = _PyLong_New(n);
1817 if (z == NULL)
1818 return NULL;
1819 /* Read string from right, and fill in long from left; i.e.,
1820 * from least to most significant in both.
1821 */
1822 accum = 0;
1823 bits_in_accum = 0;
1824 pdigit = z->ob_digit;
1825 while (--p >= start) {
1826 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1827 assert(k >= 0 && k < base);
1828 accum |= (twodigits)k << bits_in_accum;
1829 bits_in_accum += bits_per_char;
1830 if (bits_in_accum >= PyLong_SHIFT) {
1831 *pdigit++ = (digit)(accum & PyLong_MASK);
1832 assert(pdigit - z->ob_digit <= n);
1833 accum >>= PyLong_SHIFT;
1834 bits_in_accum -= PyLong_SHIFT;
1835 assert(bits_in_accum < PyLong_SHIFT);
1836 }
1837 }
1838 if (bits_in_accum) {
1839 assert(bits_in_accum <= PyLong_SHIFT);
1840 *pdigit++ = (digit)accum;
1841 assert(pdigit - z->ob_digit <= n);
1842 }
1843 while (pdigit - z->ob_digit < n)
1844 *pdigit++ = 0;
1845 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001846}
1847
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001848PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001849PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 int sign = 1, error_if_nonzero = 0;
1852 char *start, *orig_str = str;
1853 PyLongObject *z = NULL;
1854 PyObject *strobj;
1855 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 if ((base != 0 && base < 2) || base > 36) {
1858 PyErr_SetString(PyExc_ValueError,
1859 "int() arg 2 must be >= 2 and <= 36");
1860 return NULL;
1861 }
1862 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1863 str++;
1864 if (*str == '+')
1865 ++str;
1866 else if (*str == '-') {
1867 ++str;
1868 sign = -1;
1869 }
1870 if (base == 0) {
1871 if (str[0] != '0')
1872 base = 10;
1873 else if (str[1] == 'x' || str[1] == 'X')
1874 base = 16;
1875 else if (str[1] == 'o' || str[1] == 'O')
1876 base = 8;
1877 else if (str[1] == 'b' || str[1] == 'B')
1878 base = 2;
1879 else {
1880 /* "old" (C-style) octal literal, now invalid.
1881 it might still be zero though */
1882 error_if_nonzero = 1;
1883 base = 10;
1884 }
1885 }
1886 if (str[0] == '0' &&
1887 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1888 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1889 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1890 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 start = str;
1893 if ((base & (base - 1)) == 0)
1894 z = long_from_binary_base(&str, base);
1895 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001896/***
1897Binary bases can be converted in time linear in the number of digits, because
1898Python's representation base is binary. Other bases (including decimal!) use
1899the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001900
Thomas Wouters477c8d52006-05-27 19:21:47 +00001901First some math: the largest integer that can be expressed in N base-B digits
1902is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1903case number of Python digits needed to hold it is the smallest integer n s.t.
1904
1905 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1906 BASE**n >= B**N [taking logs to base BASE]
1907 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1908
1909The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1910this quickly. A Python long with that much space is reserved near the start,
1911and the result is computed into it.
1912
1913The input string is actually treated as being in base base**i (i.e., i digits
1914are processed at a time), where two more static arrays hold:
1915
1916 convwidth_base[base] = the largest integer i such that base**i <= BASE
1917 convmultmax_base[base] = base ** convwidth_base[base]
1918
1919The first of these is the largest i such that i consecutive input digits
1920must fit in a single Python digit. The second is effectively the input
1921base we're really using.
1922
1923Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1924convmultmax_base[base], the result is "simply"
1925
1926 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1927
1928where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001929
1930Error analysis: as above, the number of Python digits `n` needed is worst-
1931case
1932
1933 n >= N * log(B)/log(BASE)
1934
1935where `N` is the number of input digits in base `B`. This is computed via
1936
1937 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1938
1939below. Two numeric concerns are how much space this can waste, and whether
1940the computed result can be too small. To be concrete, assume BASE = 2**15,
1941which is the default (and it's unlikely anyone changes that).
1942
1943Waste isn't a problem: provided the first input digit isn't 0, the difference
1944between the worst-case input with N digits and the smallest input with N
1945digits is about a factor of B, but B is small compared to BASE so at most
1946one allocated Python digit can remain unused on that count. If
1947N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1948and adding 1 returns a result 1 larger than necessary. However, that can't
1949happen: whenever B is a power of 2, long_from_binary_base() is called
1950instead, and it's impossible for B**i to be an integer power of 2**15 when
1951B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1952an exact integer when B is not a power of 2, since B**i has a prime factor
1953other than 2 in that case, but (2**15)**j's only prime factor is 2).
1954
1955The computed result can be too small if the true value of N*log(B)/log(BASE)
1956is a little bit larger than an exact integer, but due to roundoff errors (in
1957computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1958yields a numeric result a little less than that integer. Unfortunately, "how
1959close can a transcendental function get to an integer over some range?"
1960questions are generally theoretically intractable. Computer analysis via
1961continued fractions is practical: expand log(B)/log(BASE) via continued
1962fractions, giving a sequence i/j of "the best" rational approximations. Then
1963j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1964we can get very close to being in trouble, but very rarely. For example,
196576573 is a denominator in one of the continued-fraction approximations to
1966log(10)/log(2**15), and indeed:
1967
1968 >>> log(10)/log(2**15)*76573
1969 16958.000000654003
1970
1971is very close to an integer. If we were working with IEEE single-precision,
1972rounding errors could kill us. Finding worst cases in IEEE double-precision
1973requires better-than-double-precision log() functions, and Tim didn't bother.
1974Instead the code checks to see whether the allocated space is enough as each
1975new Python digit is added, and copies the whole thing to a larger long if not.
1976This should happen extremely rarely, and in fact I don't have a test case
1977that triggers it(!). Instead the code was tested by artificially allocating
1978just 1 digit at the start, so that the copying code was exercised for every
1979digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001980***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 register twodigits c; /* current input character */
1982 Py_ssize_t size_z;
1983 int i;
1984 int convwidth;
1985 twodigits convmultmax, convmult;
1986 digit *pz, *pzstop;
1987 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 static double log_base_BASE[37] = {0.0e0,};
1990 static int convwidth_base[37] = {0,};
1991 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 if (log_base_BASE[base] == 0.0) {
1994 twodigits convmax = base;
1995 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001996
Mark Dickinson22b20182010-05-10 21:27:53 +00001997 log_base_BASE[base] = (log((double)base) /
1998 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 for (;;) {
2000 twodigits next = convmax * base;
2001 if (next > PyLong_BASE)
2002 break;
2003 convmax = next;
2004 ++i;
2005 }
2006 convmultmax_base[base] = convmax;
2007 assert(i > 0);
2008 convwidth_base[base] = i;
2009 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 /* Find length of the string of numeric characters. */
2012 scan = str;
2013 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2014 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 /* Create a long object that can contain the largest possible
2017 * integer with this base and length. Note that there's no
2018 * need to initialize z->ob_digit -- no slot is read up before
2019 * being stored into.
2020 */
2021 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2022 /* Uncomment next line to test exceedingly rare copy code */
2023 /* size_z = 1; */
2024 assert(size_z > 0);
2025 z = _PyLong_New(size_z);
2026 if (z == NULL)
2027 return NULL;
2028 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* `convwidth` consecutive input digits are treated as a single
2031 * digit in base `convmultmax`.
2032 */
2033 convwidth = convwidth_base[base];
2034 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 /* Work ;-) */
2037 while (str < scan) {
2038 /* grab up to convwidth digits from the input string */
2039 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2040 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2041 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002042 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 assert(c < PyLong_BASE);
2044 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 convmult = convmultmax;
2047 /* Calculate the shift only if we couldn't get
2048 * convwidth digits.
2049 */
2050 if (i != convwidth) {
2051 convmult = base;
2052 for ( ; i > 1; --i)
2053 convmult *= base;
2054 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 /* Multiply z by convmult, and add c. */
2057 pz = z->ob_digit;
2058 pzstop = pz + Py_SIZE(z);
2059 for (; pz < pzstop; ++pz) {
2060 c += (twodigits)*pz * convmult;
2061 *pz = (digit)(c & PyLong_MASK);
2062 c >>= PyLong_SHIFT;
2063 }
2064 /* carry off the current end? */
2065 if (c) {
2066 assert(c < PyLong_BASE);
2067 if (Py_SIZE(z) < size_z) {
2068 *pz = (digit)c;
2069 ++Py_SIZE(z);
2070 }
2071 else {
2072 PyLongObject *tmp;
2073 /* Extremely rare. Get more space. */
2074 assert(Py_SIZE(z) == size_z);
2075 tmp = _PyLong_New(size_z + 1);
2076 if (tmp == NULL) {
2077 Py_DECREF(z);
2078 return NULL;
2079 }
2080 memcpy(tmp->ob_digit,
2081 z->ob_digit,
2082 sizeof(digit) * size_z);
2083 Py_DECREF(z);
2084 z = tmp;
2085 z->ob_digit[size_z] = (digit)c;
2086 ++size_z;
2087 }
2088 }
2089 }
2090 }
2091 if (z == NULL)
2092 return NULL;
2093 if (error_if_nonzero) {
2094 /* reset the base to 0, else the exception message
2095 doesn't make too much sense */
2096 base = 0;
2097 if (Py_SIZE(z) != 0)
2098 goto onError;
2099 /* there might still be other problems, therefore base
2100 remains zero here for the same reason */
2101 }
2102 if (str == start)
2103 goto onError;
2104 if (sign < 0)
2105 Py_SIZE(z) = -(Py_SIZE(z));
2106 while (*str && isspace(Py_CHARMASK(*str)))
2107 str++;
2108 if (*str != '\0')
2109 goto onError;
2110 if (pend)
2111 *pend = str;
2112 long_normalize(z);
2113 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002114
Mark Dickinson22b20182010-05-10 21:27:53 +00002115 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 Py_XDECREF(z);
2117 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2118 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2119 if (strobj == NULL)
2120 return NULL;
2121 PyErr_Format(PyExc_ValueError,
2122 "invalid literal for int() with base %d: %R",
2123 base, strobj);
2124 Py_DECREF(strobj);
2125 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002126}
2127
2128PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002129PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002130{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002131 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2132 if (unicode == NULL)
2133 return NULL;
2134 v = PyLong_FromUnicodeObject(unicode, base);
2135 Py_DECREF(unicode);
2136 return v;
2137}
2138
2139PyObject *
2140PyLong_FromUnicodeObject(PyObject *u, int base)
2141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002143 PyObject *asciidig;
2144 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002145 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002147 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002148 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002150 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002151 if (buffer == NULL) {
2152 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 return NULL;
2154 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002155 result = PyLong_FromString(buffer, &end, base);
2156 if (result != NULL && end != buffer + buflen) {
2157 PyErr_SetString(PyExc_ValueError,
2158 "null byte in argument for int()");
2159 Py_DECREF(result);
2160 result = NULL;
2161 }
2162 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002164}
2165
Tim Peters9f688bf2000-07-07 15:53:28 +00002166/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002167static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002169static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002170
2171/* Long division with remainder, top-level routine */
2172
Guido van Rossume32e0141992-01-19 16:31:05 +00002173static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002174long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2178 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 if (size_b == 0) {
2181 PyErr_SetString(PyExc_ZeroDivisionError,
2182 "integer division or modulo by zero");
2183 return -1;
2184 }
2185 if (size_a < size_b ||
2186 (size_a == size_b &&
2187 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2188 /* |a| < |b|. */
2189 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2190 if (*pdiv == NULL)
2191 return -1;
2192 Py_INCREF(a);
2193 *prem = (PyLongObject *) a;
2194 return 0;
2195 }
2196 if (size_b == 1) {
2197 digit rem = 0;
2198 z = divrem1(a, b->ob_digit[0], &rem);
2199 if (z == NULL)
2200 return -1;
2201 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2202 if (*prem == NULL) {
2203 Py_DECREF(z);
2204 return -1;
2205 }
2206 }
2207 else {
2208 z = x_divrem(a, b, prem);
2209 if (z == NULL)
2210 return -1;
2211 }
2212 /* Set the signs.
2213 The quotient z has the sign of a*b;
2214 the remainder r has the sign of a,
2215 so a = b*z + r. */
2216 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2217 NEGATE(z);
2218 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2219 NEGATE(*prem);
2220 *pdiv = maybe_small_long(z);
2221 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002222}
2223
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002224/* Unsigned long division with remainder -- the algorithm. The arguments v1
2225 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002226
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002227static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002228x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 PyLongObject *v, *w, *a;
2231 Py_ssize_t i, k, size_v, size_w;
2232 int d;
2233 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2234 twodigits vv;
2235 sdigit zhi;
2236 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2239 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2240 handle the special case when the initial estimate q for a quotient
2241 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2242 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* allocate space; w will also be used to hold the final remainder */
2245 size_v = ABS(Py_SIZE(v1));
2246 size_w = ABS(Py_SIZE(w1));
2247 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2248 v = _PyLong_New(size_v+1);
2249 if (v == NULL) {
2250 *prem = NULL;
2251 return NULL;
2252 }
2253 w = _PyLong_New(size_w);
2254 if (w == NULL) {
2255 Py_DECREF(v);
2256 *prem = NULL;
2257 return NULL;
2258 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2261 shift v1 left by the same amount. Results go into w and v. */
2262 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2263 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2264 assert(carry == 0);
2265 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2266 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2267 v->ob_digit[size_v] = carry;
2268 size_v++;
2269 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2272 at most (and usually exactly) k = size_v - size_w digits. */
2273 k = size_v - size_w;
2274 assert(k >= 0);
2275 a = _PyLong_New(k);
2276 if (a == NULL) {
2277 Py_DECREF(w);
2278 Py_DECREF(v);
2279 *prem = NULL;
2280 return NULL;
2281 }
2282 v0 = v->ob_digit;
2283 w0 = w->ob_digit;
2284 wm1 = w0[size_w-1];
2285 wm2 = w0[size_w-2];
2286 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2287 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2288 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002291 Py_DECREF(a);
2292 Py_DECREF(w);
2293 Py_DECREF(v);
2294 *prem = NULL;
2295 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002296 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 /* estimate quotient digit q; may overestimate by 1 (rare) */
2299 vtop = vk[size_w];
2300 assert(vtop <= wm1);
2301 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2302 q = (digit)(vv / wm1);
2303 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2304 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2305 | vk[size_w-2])) {
2306 --q;
2307 r += wm1;
2308 if (r >= PyLong_BASE)
2309 break;
2310 }
2311 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2314 zhi = 0;
2315 for (i = 0; i < size_w; ++i) {
2316 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2317 -PyLong_BASE * q <= z < PyLong_BASE */
2318 z = (sdigit)vk[i] + zhi -
2319 (stwodigits)q * (stwodigits)w0[i];
2320 vk[i] = (digit)z & PyLong_MASK;
2321 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002322 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* add w back if q was too large (this branch taken rarely) */
2326 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2327 if ((sdigit)vtop + zhi < 0) {
2328 carry = 0;
2329 for (i = 0; i < size_w; ++i) {
2330 carry += vk[i] + w0[i];
2331 vk[i] = carry & PyLong_MASK;
2332 carry >>= PyLong_SHIFT;
2333 }
2334 --q;
2335 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* store quotient digit */
2338 assert(q < PyLong_BASE);
2339 *--ak = q;
2340 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* unshift remainder; we reuse w to store the result */
2343 carry = v_rshift(w0, v0, size_w, d);
2344 assert(carry==0);
2345 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 *prem = long_normalize(w);
2348 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002349}
2350
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002351/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2352 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2353 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2354 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2355 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2356 -1.0. */
2357
2358/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2359#if DBL_MANT_DIG == 53
2360#define EXP2_DBL_MANT_DIG 9007199254740992.0
2361#else
2362#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2363#endif
2364
2365double
2366_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2369 /* See below for why x_digits is always large enough. */
2370 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2371 double dx;
2372 /* Correction term for round-half-to-even rounding. For a digit x,
2373 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2374 multiple of 4, rounding ties to a multiple of 8. */
2375 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 a_size = ABS(Py_SIZE(a));
2378 if (a_size == 0) {
2379 /* Special case for 0: significand 0.0, exponent 0. */
2380 *e = 0;
2381 return 0.0;
2382 }
2383 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2384 /* The following is an overflow-free version of the check
2385 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2386 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2387 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2388 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002389 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2393 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 Number of digits needed for result: write // for floor division.
2396 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2405 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2408 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2409 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 in both cases.
2416 */
2417 if (a_bits <= DBL_MANT_DIG + 2) {
2418 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2419 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2420 x_size = 0;
2421 while (x_size < shift_digits)
2422 x_digits[x_size++] = 0;
2423 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2424 (int)shift_bits);
2425 x_size += a_size;
2426 x_digits[x_size++] = rem;
2427 }
2428 else {
2429 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2430 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2431 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2432 a_size - shift_digits, (int)shift_bits);
2433 x_size = a_size - shift_digits;
2434 /* For correct rounding below, we need the least significant
2435 bit of x to be 'sticky' for this shift: if any of the bits
2436 shifted out was nonzero, we set the least significant bit
2437 of x. */
2438 if (rem)
2439 x_digits[0] |= 1;
2440 else
2441 while (shift_digits > 0)
2442 if (a->ob_digit[--shift_digits]) {
2443 x_digits[0] |= 1;
2444 break;
2445 }
2446 }
Mark Dickinson22b20182010-05-10 21:27:53 +00002447 assert(1 <= x_size &&
2448 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 /* Round, and convert to double. */
2451 x_digits[0] += half_even_correction[x_digits[0] & 7];
2452 dx = x_digits[--x_size];
2453 while (x_size > 0)
2454 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 /* Rescale; make correction if result is 1.0. */
2457 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2458 if (dx == 1.0) {
2459 if (a_bits == PY_SSIZE_T_MAX)
2460 goto overflow;
2461 dx = 0.5;
2462 a_bits += 1;
2463 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 *e = a_bits;
2466 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002467
2468 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 /* exponent > PY_SSIZE_T_MAX */
2470 PyErr_SetString(PyExc_OverflowError,
2471 "huge integer: number of bits overflows a Py_ssize_t");
2472 *e = 0;
2473 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002474}
2475
2476/* Get a C double from a long int object. Rounds to the nearest double,
2477 using the round-half-to-even rule in the case of a tie. */
2478
2479double
2480PyLong_AsDouble(PyObject *v)
2481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 Py_ssize_t exponent;
2483 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002484
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002485 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 PyErr_BadInternalCall();
2487 return -1.0;
2488 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002489 if (!PyLong_Check(v)) {
2490 PyErr_SetString(PyExc_TypeError, "an integer is required");
2491 return -1.0;
2492 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2494 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2495 PyErr_SetString(PyExc_OverflowError,
2496 "long int too large to convert to float");
2497 return -1.0;
2498 }
2499 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002500}
2501
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002502/* Methods */
2503
2504static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002505long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002508}
2509
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002510static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002511long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 if (Py_SIZE(a) != Py_SIZE(b)) {
2516 sign = Py_SIZE(a) - Py_SIZE(b);
2517 }
2518 else {
2519 Py_ssize_t i = ABS(Py_SIZE(a));
2520 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2521 ;
2522 if (i < 0)
2523 sign = 0;
2524 else {
2525 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2526 if (Py_SIZE(a) < 0)
2527 sign = -sign;
2528 }
2529 }
2530 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002531}
2532
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002533#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002535
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002536static PyObject *
2537long_richcompare(PyObject *self, PyObject *other, int op)
2538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 int result;
2540 PyObject *v;
2541 CHECK_BINOP(self, other);
2542 if (self == other)
2543 result = 0;
2544 else
2545 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2546 /* Convert the return value to a Boolean */
2547 switch (op) {
2548 case Py_EQ:
2549 v = TEST_COND(result == 0);
2550 break;
2551 case Py_NE:
2552 v = TEST_COND(result != 0);
2553 break;
2554 case Py_LE:
2555 v = TEST_COND(result <= 0);
2556 break;
2557 case Py_GE:
2558 v = TEST_COND(result >= 0);
2559 break;
2560 case Py_LT:
2561 v = TEST_COND(result == -1);
2562 break;
2563 case Py_GT:
2564 v = TEST_COND(result == 1);
2565 break;
2566 default:
2567 PyErr_BadArgument();
2568 return NULL;
2569 }
2570 Py_INCREF(v);
2571 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002572}
2573
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002574static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002575long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002576{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002577 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 Py_ssize_t i;
2579 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 i = Py_SIZE(v);
2582 switch(i) {
2583 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2584 case 0: return 0;
2585 case 1: return v->ob_digit[0];
2586 }
2587 sign = 1;
2588 x = 0;
2589 if (i < 0) {
2590 sign = -1;
2591 i = -(i);
2592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002594 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2595 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2596 _PyHASH_MODULUS.
2597
2598 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2599 amounts to a rotation of the bits of x. To see this, write
2600
2601 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2602
2603 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2604 PyLong_SHIFT bits of x (those that are shifted out of the
2605 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2606 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2607 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2608 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2609 congruent to y modulo _PyHASH_MODULUS. So
2610
2611 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2612
2613 The right-hand side is just the result of rotating the
2614 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2615 not all _PyHASH_BITS bits of x are 1s, the same is true
2616 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2617 the reduction of x*2**PyLong_SHIFT modulo
2618 _PyHASH_MODULUS. */
2619 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2620 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002622 if (x >= _PyHASH_MODULUS)
2623 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 }
2625 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002626 if (x == (Py_uhash_t)-1)
2627 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002628 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002629}
2630
2631
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002632/* Add the absolute values of two long integers. */
2633
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002634static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002635x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2638 PyLongObject *z;
2639 Py_ssize_t i;
2640 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 /* Ensure a is the larger of the two: */
2643 if (size_a < size_b) {
2644 { PyLongObject *temp = a; a = b; b = temp; }
2645 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002646 size_a = size_b;
2647 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 }
2649 z = _PyLong_New(size_a+1);
2650 if (z == NULL)
2651 return NULL;
2652 for (i = 0; i < size_b; ++i) {
2653 carry += a->ob_digit[i] + b->ob_digit[i];
2654 z->ob_digit[i] = carry & PyLong_MASK;
2655 carry >>= PyLong_SHIFT;
2656 }
2657 for (; i < size_a; ++i) {
2658 carry += a->ob_digit[i];
2659 z->ob_digit[i] = carry & PyLong_MASK;
2660 carry >>= PyLong_SHIFT;
2661 }
2662 z->ob_digit[i] = carry;
2663 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002664}
2665
2666/* Subtract the absolute values of two integers. */
2667
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002668static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002669x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2672 PyLongObject *z;
2673 Py_ssize_t i;
2674 int sign = 1;
2675 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 /* Ensure a is the larger of the two: */
2678 if (size_a < size_b) {
2679 sign = -1;
2680 { PyLongObject *temp = a; a = b; b = temp; }
2681 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002682 size_a = size_b;
2683 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 }
2685 else if (size_a == size_b) {
2686 /* Find highest digit where a and b differ: */
2687 i = size_a;
2688 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2689 ;
2690 if (i < 0)
2691 return (PyLongObject *)PyLong_FromLong(0);
2692 if (a->ob_digit[i] < b->ob_digit[i]) {
2693 sign = -1;
2694 { PyLongObject *temp = a; a = b; b = temp; }
2695 }
2696 size_a = size_b = i+1;
2697 }
2698 z = _PyLong_New(size_a);
2699 if (z == NULL)
2700 return NULL;
2701 for (i = 0; i < size_b; ++i) {
2702 /* The following assumes unsigned arithmetic
2703 works module 2**N for some N>PyLong_SHIFT. */
2704 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2705 z->ob_digit[i] = borrow & PyLong_MASK;
2706 borrow >>= PyLong_SHIFT;
2707 borrow &= 1; /* Keep only one sign bit */
2708 }
2709 for (; i < size_a; ++i) {
2710 borrow = a->ob_digit[i] - borrow;
2711 z->ob_digit[i] = borrow & PyLong_MASK;
2712 borrow >>= PyLong_SHIFT;
2713 borrow &= 1; /* Keep only one sign bit */
2714 }
2715 assert(borrow == 0);
2716 if (sign < 0)
2717 NEGATE(z);
2718 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002719}
2720
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002721static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002722long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2729 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2730 MEDIUM_VALUE(b));
2731 return result;
2732 }
2733 if (Py_SIZE(a) < 0) {
2734 if (Py_SIZE(b) < 0) {
2735 z = x_add(a, b);
2736 if (z != NULL && Py_SIZE(z) != 0)
2737 Py_SIZE(z) = -(Py_SIZE(z));
2738 }
2739 else
2740 z = x_sub(b, a);
2741 }
2742 else {
2743 if (Py_SIZE(b) < 0)
2744 z = x_sub(a, b);
2745 else
2746 z = x_add(a, b);
2747 }
2748 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002749}
2750
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002751static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002752long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2759 PyObject* r;
2760 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2761 return r;
2762 }
2763 if (Py_SIZE(a) < 0) {
2764 if (Py_SIZE(b) < 0)
2765 z = x_sub(a, b);
2766 else
2767 z = x_add(a, b);
2768 if (z != NULL && Py_SIZE(z) != 0)
2769 Py_SIZE(z) = -(Py_SIZE(z));
2770 }
2771 else {
2772 if (Py_SIZE(b) < 0)
2773 z = x_add(a, b);
2774 else
2775 z = x_sub(a, b);
2776 }
2777 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002778}
2779
Tim Peters5af4e6c2002-08-12 02:31:19 +00002780/* Grade school multiplication, ignoring the signs.
2781 * Returns the absolute value of the product, or NULL if error.
2782 */
2783static PyLongObject *
2784x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 PyLongObject *z;
2787 Py_ssize_t size_a = ABS(Py_SIZE(a));
2788 Py_ssize_t size_b = ABS(Py_SIZE(b));
2789 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 z = _PyLong_New(size_a + size_b);
2792 if (z == NULL)
2793 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2796 if (a == b) {
2797 /* Efficient squaring per HAC, Algorithm 14.16:
2798 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2799 * Gives slightly less than a 2x speedup when a == b,
2800 * via exploiting that each entry in the multiplication
2801 * pyramid appears twice (except for the size_a squares).
2802 */
2803 for (i = 0; i < size_a; ++i) {
2804 twodigits carry;
2805 twodigits f = a->ob_digit[i];
2806 digit *pz = z->ob_digit + (i << 1);
2807 digit *pa = a->ob_digit + i + 1;
2808 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002811 Py_DECREF(z);
2812 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002813 });
Tim Peters0973b992004-08-29 22:16:50 +00002814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 carry = *pz + f * f;
2816 *pz++ = (digit)(carry & PyLong_MASK);
2817 carry >>= PyLong_SHIFT;
2818 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 /* Now f is added in twice in each column of the
2821 * pyramid it appears. Same as adding f<<1 once.
2822 */
2823 f <<= 1;
2824 while (pa < paend) {
2825 carry += *pz + *pa++ * f;
2826 *pz++ = (digit)(carry & PyLong_MASK);
2827 carry >>= PyLong_SHIFT;
2828 assert(carry <= (PyLong_MASK << 1));
2829 }
2830 if (carry) {
2831 carry += *pz;
2832 *pz++ = (digit)(carry & PyLong_MASK);
2833 carry >>= PyLong_SHIFT;
2834 }
2835 if (carry)
2836 *pz += (digit)(carry & PyLong_MASK);
2837 assert((carry >> PyLong_SHIFT) == 0);
2838 }
2839 }
2840 else { /* a is not the same as b -- gradeschool long mult */
2841 for (i = 0; i < size_a; ++i) {
2842 twodigits carry = 0;
2843 twodigits f = a->ob_digit[i];
2844 digit *pz = z->ob_digit + i;
2845 digit *pb = b->ob_digit;
2846 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002849 Py_DECREF(z);
2850 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002851 });
Tim Peters0973b992004-08-29 22:16:50 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 while (pb < pbend) {
2854 carry += *pz + *pb++ * f;
2855 *pz++ = (digit)(carry & PyLong_MASK);
2856 carry >>= PyLong_SHIFT;
2857 assert(carry <= PyLong_MASK);
2858 }
2859 if (carry)
2860 *pz += (digit)(carry & PyLong_MASK);
2861 assert((carry >> PyLong_SHIFT) == 0);
2862 }
2863 }
2864 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002865}
2866
2867/* A helper for Karatsuba multiplication (k_mul).
2868 Takes a long "n" and an integer "size" representing the place to
2869 split, and sets low and high such that abs(n) == (high << size) + low,
2870 viewing the shift as being by digits. The sign bit is ignored, and
2871 the return values are >= 0.
2872 Returns 0 on success, -1 on failure.
2873*/
2874static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002875kmul_split(PyLongObject *n,
2876 Py_ssize_t size,
2877 PyLongObject **high,
2878 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 PyLongObject *hi, *lo;
2881 Py_ssize_t size_lo, size_hi;
2882 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 size_lo = MIN(size_n, size);
2885 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 if ((hi = _PyLong_New(size_hi)) == NULL)
2888 return -1;
2889 if ((lo = _PyLong_New(size_lo)) == NULL) {
2890 Py_DECREF(hi);
2891 return -1;
2892 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2895 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 *high = long_normalize(hi);
2898 *low = long_normalize(lo);
2899 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002900}
2901
Tim Peters60004642002-08-12 22:01:34 +00002902static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2903
Tim Peters5af4e6c2002-08-12 02:31:19 +00002904/* Karatsuba multiplication. Ignores the input signs, and returns the
2905 * absolute value of the product (or NULL if error).
2906 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2907 */
2908static PyLongObject *
2909k_mul(PyLongObject *a, PyLongObject *b)
2910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 Py_ssize_t asize = ABS(Py_SIZE(a));
2912 Py_ssize_t bsize = ABS(Py_SIZE(b));
2913 PyLongObject *ah = NULL;
2914 PyLongObject *al = NULL;
2915 PyLongObject *bh = NULL;
2916 PyLongObject *bl = NULL;
2917 PyLongObject *ret = NULL;
2918 PyLongObject *t1, *t2, *t3;
2919 Py_ssize_t shift; /* the number of digits we split off */
2920 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2923 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2924 * Then the original product is
2925 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2926 * By picking X to be a power of 2, "*X" is just shifting, and it's
2927 * been reduced to 3 multiplies on numbers half the size.
2928 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 /* We want to split based on the larger number; fiddle so that b
2931 * is largest.
2932 */
2933 if (asize > bsize) {
2934 t1 = a;
2935 a = b;
2936 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 i = asize;
2939 asize = bsize;
2940 bsize = i;
2941 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 /* Use gradeschool math when either number is too small. */
2944 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2945 if (asize <= i) {
2946 if (asize == 0)
2947 return (PyLongObject *)PyLong_FromLong(0);
2948 else
2949 return x_mul(a, b);
2950 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 /* If a is small compared to b, splitting on b gives a degenerate
2953 * case with ah==0, and Karatsuba may be (even much) less efficient
2954 * than "grade school" then. However, we can still win, by viewing
2955 * b as a string of "big digits", each of width a->ob_size. That
2956 * leads to a sequence of balanced calls to k_mul.
2957 */
2958 if (2 * asize <= bsize)
2959 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 /* Split a & b into hi & lo pieces. */
2962 shift = bsize >> 1;
2963 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2964 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 if (a == b) {
2967 bh = ah;
2968 bl = al;
2969 Py_INCREF(bh);
2970 Py_INCREF(bl);
2971 }
2972 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 /* The plan:
2975 * 1. Allocate result space (asize + bsize digits: that's always
2976 * enough).
2977 * 2. Compute ah*bh, and copy into result at 2*shift.
2978 * 3. Compute al*bl, and copy into result at 0. Note that this
2979 * can't overlap with #2.
2980 * 4. Subtract al*bl from the result, starting at shift. This may
2981 * underflow (borrow out of the high digit), but we don't care:
2982 * we're effectively doing unsigned arithmetic mod
2983 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2984 * borrows and carries out of the high digit can be ignored.
2985 * 5. Subtract ah*bh from the result, starting at shift.
2986 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2987 * at shift.
2988 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 /* 1. Allocate result space. */
2991 ret = _PyLong_New(asize + bsize);
2992 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002993#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 /* Fill with trash, to catch reference to uninitialized digits. */
2995 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002996#endif
Tim Peters44121a62002-08-12 06:17:58 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2999 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3000 assert(Py_SIZE(t1) >= 0);
3001 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3002 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3003 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 /* Zero-out the digits higher than the ah*bh copy. */
3006 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3007 if (i)
3008 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3009 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 /* 3. t2 <- al*bl, and copy into the low digits. */
3012 if ((t2 = k_mul(al, bl)) == NULL) {
3013 Py_DECREF(t1);
3014 goto fail;
3015 }
3016 assert(Py_SIZE(t2) >= 0);
3017 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3018 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 /* Zero out remaining digits. */
3021 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3022 if (i)
3023 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3026 * because it's fresher in cache.
3027 */
3028 i = Py_SIZE(ret) - shift; /* # digits after shift */
3029 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3030 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3033 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3036 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3037 Py_DECREF(ah);
3038 Py_DECREF(al);
3039 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 if (a == b) {
3042 t2 = t1;
3043 Py_INCREF(t2);
3044 }
3045 else if ((t2 = x_add(bh, bl)) == NULL) {
3046 Py_DECREF(t1);
3047 goto fail;
3048 }
3049 Py_DECREF(bh);
3050 Py_DECREF(bl);
3051 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 t3 = k_mul(t1, t2);
3054 Py_DECREF(t1);
3055 Py_DECREF(t2);
3056 if (t3 == NULL) goto fail;
3057 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 /* Add t3. It's not obvious why we can't run out of room here.
3060 * See the (*) comment after this function.
3061 */
3062 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3063 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003066
Mark Dickinson22b20182010-05-10 21:27:53 +00003067 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 Py_XDECREF(ret);
3069 Py_XDECREF(ah);
3070 Py_XDECREF(al);
3071 Py_XDECREF(bh);
3072 Py_XDECREF(bl);
3073 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003074}
3075
Tim Petersd6974a52002-08-13 20:37:51 +00003076/* (*) Why adding t3 can't "run out of room" above.
3077
Tim Petersab86c2b2002-08-15 20:06:00 +00003078Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3079to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003080
Tim Petersab86c2b2002-08-15 20:06:00 +000030811. For any integer i, i = c(i/2) + f(i/2). In particular,
3082 bsize = c(bsize/2) + f(bsize/2).
30832. shift = f(bsize/2)
30843. asize <= bsize
30854. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3086 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003087
Tim Petersab86c2b2002-08-15 20:06:00 +00003088We allocated asize + bsize result digits, and add t3 into them at an offset
3089of shift. This leaves asize+bsize-shift allocated digit positions for t3
3090to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3091asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003092
Tim Petersab86c2b2002-08-15 20:06:00 +00003093bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3094at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003095
Tim Petersab86c2b2002-08-15 20:06:00 +00003096If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3097digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3098most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003099
Tim Petersab86c2b2002-08-15 20:06:00 +00003100The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003101
Tim Petersab86c2b2002-08-15 20:06:00 +00003102 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003103
Tim Petersab86c2b2002-08-15 20:06:00 +00003104and we have asize + c(bsize/2) available digit positions. We need to show
3105this is always enough. An instance of c(bsize/2) cancels out in both, so
3106the question reduces to whether asize digits is enough to hold
3107(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3108then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3109asize 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 +00003110digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003111asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003112c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3113is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3114bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003115
Tim Peters48d52c02002-08-14 17:07:32 +00003116Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3117clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3118ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003119*/
3120
Tim Peters60004642002-08-12 22:01:34 +00003121/* b has at least twice the digits of a, and a is big enough that Karatsuba
3122 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3123 * of slices, each with a->ob_size digits, and multiply the slices by a,
3124 * one at a time. This gives k_mul balanced inputs to work with, and is
3125 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003126 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003127 * single-width slice overlap between successive partial sums).
3128 */
3129static PyLongObject *
3130k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 const Py_ssize_t asize = ABS(Py_SIZE(a));
3133 Py_ssize_t bsize = ABS(Py_SIZE(b));
3134 Py_ssize_t nbdone; /* # of b digits already multiplied */
3135 PyLongObject *ret;
3136 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 assert(asize > KARATSUBA_CUTOFF);
3139 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 /* Allocate result space, and zero it out. */
3142 ret = _PyLong_New(asize + bsize);
3143 if (ret == NULL)
3144 return NULL;
3145 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 /* Successive slices of b are copied into bslice. */
3148 bslice = _PyLong_New(asize);
3149 if (bslice == NULL)
3150 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 nbdone = 0;
3153 while (bsize > 0) {
3154 PyLongObject *product;
3155 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* Multiply the next slice of b by a. */
3158 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3159 nbtouse * sizeof(digit));
3160 Py_SIZE(bslice) = nbtouse;
3161 product = k_mul(a, bslice);
3162 if (product == NULL)
3163 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 /* Add into result. */
3166 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3167 product->ob_digit, Py_SIZE(product));
3168 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 bsize -= nbtouse;
3171 nbdone += nbtouse;
3172 }
Tim Peters60004642002-08-12 22:01:34 +00003173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 Py_DECREF(bslice);
3175 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003176
Mark Dickinson22b20182010-05-10 21:27:53 +00003177 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 Py_DECREF(ret);
3179 Py_XDECREF(bslice);
3180 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003181}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003182
3183static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003184long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 /* fast path for single-digit multiplication */
3191 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3192 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003193#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003195#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 /* if we don't have long long then we're almost certainly
3197 using 15-bit digits, so v will fit in a long. In the
3198 unlikely event that we're using 30-bit digits on a platform
3199 without long long, a large v will just cause us to fall
3200 through to the general multiplication code below. */
3201 if (v >= LONG_MIN && v <= LONG_MAX)
3202 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003203#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 z = k_mul(a, b);
3207 /* Negate if exactly one of the inputs is negative. */
3208 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3209 NEGATE(z);
3210 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003211}
3212
Guido van Rossume32e0141992-01-19 16:31:05 +00003213/* The / and % operators are now defined in terms of divmod().
3214 The expression a mod b has the value a - b*floor(a/b).
3215 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003216 |a| by |b|, with the sign of a. This is also expressed
3217 as a - b*trunc(a/b), if trunc truncates towards zero.
3218 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 a b a rem b a mod b
3220 13 10 3 3
3221 -13 10 -3 7
3222 13 -10 3 -7
3223 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003224 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003225 have different signs. We then subtract one from the 'div'
3226 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003227
Tim Peters47e52ee2004-08-30 02:44:38 +00003228/* Compute
3229 * *pdiv, *pmod = divmod(v, w)
3230 * NULL can be passed for pdiv or pmod, in which case that part of
3231 * the result is simply thrown away. The caller owns a reference to
3232 * each of these it requests (does not pass NULL for).
3233 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003234static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003235l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 if (long_divrem(v, w, &div, &mod) < 0)
3241 return -1;
3242 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3243 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3244 PyLongObject *temp;
3245 PyLongObject *one;
3246 temp = (PyLongObject *) long_add(mod, w);
3247 Py_DECREF(mod);
3248 mod = temp;
3249 if (mod == NULL) {
3250 Py_DECREF(div);
3251 return -1;
3252 }
3253 one = (PyLongObject *) PyLong_FromLong(1L);
3254 if (one == NULL ||
3255 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3256 Py_DECREF(mod);
3257 Py_DECREF(div);
3258 Py_XDECREF(one);
3259 return -1;
3260 }
3261 Py_DECREF(one);
3262 Py_DECREF(div);
3263 div = temp;
3264 }
3265 if (pdiv != NULL)
3266 *pdiv = div;
3267 else
3268 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 if (pmod != NULL)
3271 *pmod = mod;
3272 else
3273 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003276}
3277
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003278static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003279long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 CHECK_BINOP(a, b);
3284 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3285 div = NULL;
3286 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003287}
3288
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003289/* PyLong/PyLong -> float, with correctly rounded result. */
3290
3291#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3292#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3293
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003294static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003295long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 PyLongObject *a, *b, *x;
3298 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3299 digit mask, low;
3300 int inexact, negate, a_is_small, b_is_small;
3301 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 CHECK_BINOP(v, w);
3304 a = (PyLongObject *)v;
3305 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 /*
3308 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3311 1. choose a suitable integer 'shift'
3312 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3313 3. adjust x for correct rounding
3314 4. convert x to a double dx with the same value
3315 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3320 returns either 0.0 or -0.0, depending on the sign of b. For a and
3321 b both nonzero, ignore signs of a and b, and add the sign back in
3322 at the end. Now write a_bits and b_bits for the bit lengths of a
3323 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3324 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3329 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3330 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3331 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 1. The integer 'shift' is chosen so that x has the right number of
3336 bits for a double, plus two or three extra bits that will be used
3337 in the rounding decisions. Writing a_bits and b_bits for the
3338 number of significant bits in a and b respectively, a
3339 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 This is fine in the usual case, but if a/b is smaller than the
3344 smallest normal float then it can lead to double rounding on an
3345 IEEE 754 platform, giving incorrectly rounded results. So we
3346 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 2. The quantity x is computed by first shifting a (left -shift bits
3351 if shift <= 0, right shift bits if shift > 0) and then dividing by
3352 b. For both the shift and the division, we keep track of whether
3353 the result is inexact, in a flag 'inexact'; this information is
3354 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 With the choice of shift above, together with our assumption that
3357 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3358 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3361 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 For float representability, we need x/2**extra_bits <
3366 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3367 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 To round, we just modify the bottom digit of x in-place; this can
3372 end up giving a digit with value > PyLONG_MASK, but that's not a
3373 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 With the original choices for shift above, extra_bits will always
3376 be 2 or 3. Then rounding under the round-half-to-even rule, we
3377 round up iff the most significant of the extra bits is 1, and
3378 either: (a) the computation of x in step 2 had an inexact result,
3379 or (b) at least one other of the extra bits is 1, or (c) the least
3380 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 4. Conversion to a double is straightforward; all floating-point
3383 operations involved in the conversion are exact, so there's no
3384 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3387 The result will always be exactly representable as a double, except
3388 in the case that it overflows. To avoid dependence on the exact
3389 behaviour of ldexp on overflow, we check for overflow before
3390 applying ldexp. The result of ldexp is adjusted for sign before
3391 returning.
3392 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 /* Reduce to case where a and b are both positive. */
3395 a_size = ABS(Py_SIZE(a));
3396 b_size = ABS(Py_SIZE(b));
3397 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3398 if (b_size == 0) {
3399 PyErr_SetString(PyExc_ZeroDivisionError,
3400 "division by zero");
3401 goto error;
3402 }
3403 if (a_size == 0)
3404 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 /* Fast path for a and b small (exactly representable in a double).
3407 Relies on floating-point division being correctly rounded; results
3408 may be subject to double rounding on x86 machines that operate with
3409 the x87 FPU set to 64-bit precision. */
3410 a_is_small = a_size <= MANT_DIG_DIGITS ||
3411 (a_size == MANT_DIG_DIGITS+1 &&
3412 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3413 b_is_small = b_size <= MANT_DIG_DIGITS ||
3414 (b_size == MANT_DIG_DIGITS+1 &&
3415 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3416 if (a_is_small && b_is_small) {
3417 double da, db;
3418 da = a->ob_digit[--a_size];
3419 while (a_size > 0)
3420 da = da * PyLong_BASE + a->ob_digit[--a_size];
3421 db = b->ob_digit[--b_size];
3422 while (b_size > 0)
3423 db = db * PyLong_BASE + b->ob_digit[--b_size];
3424 result = da / db;
3425 goto success;
3426 }
Tim Peterse2a60002001-09-04 06:17:36 +00003427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 /* Catch obvious cases of underflow and overflow */
3429 diff = a_size - b_size;
3430 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3431 /* Extreme overflow */
3432 goto overflow;
3433 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3434 /* Extreme underflow */
3435 goto underflow_or_zero;
3436 /* Next line is now safe from overflowing a Py_ssize_t */
3437 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3438 bits_in_digit(b->ob_digit[b_size - 1]);
3439 /* Now diff = a_bits - b_bits. */
3440 if (diff > DBL_MAX_EXP)
3441 goto overflow;
3442 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3443 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 /* Choose value for shift; see comments for step 1 above. */
3446 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 /* x = abs(a * 2**-shift) */
3451 if (shift <= 0) {
3452 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3453 digit rem;
3454 /* x = a << -shift */
3455 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3456 /* In practice, it's probably impossible to end up
3457 here. Both a and b would have to be enormous,
3458 using close to SIZE_T_MAX bytes of memory each. */
3459 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003460 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 goto error;
3462 }
3463 x = _PyLong_New(a_size + shift_digits + 1);
3464 if (x == NULL)
3465 goto error;
3466 for (i = 0; i < shift_digits; i++)
3467 x->ob_digit[i] = 0;
3468 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3469 a_size, -shift % PyLong_SHIFT);
3470 x->ob_digit[a_size + shift_digits] = rem;
3471 }
3472 else {
3473 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3474 digit rem;
3475 /* x = a >> shift */
3476 assert(a_size >= shift_digits);
3477 x = _PyLong_New(a_size - shift_digits);
3478 if (x == NULL)
3479 goto error;
3480 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3481 a_size - shift_digits, shift % PyLong_SHIFT);
3482 /* set inexact if any of the bits shifted out is nonzero */
3483 if (rem)
3484 inexact = 1;
3485 while (!inexact && shift_digits > 0)
3486 if (a->ob_digit[--shift_digits])
3487 inexact = 1;
3488 }
3489 long_normalize(x);
3490 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3493 reference to x, so it's safe to modify it in-place. */
3494 if (b_size == 1) {
3495 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3496 b->ob_digit[0]);
3497 long_normalize(x);
3498 if (rem)
3499 inexact = 1;
3500 }
3501 else {
3502 PyLongObject *div, *rem;
3503 div = x_divrem(x, b, &rem);
3504 Py_DECREF(x);
3505 x = div;
3506 if (x == NULL)
3507 goto error;
3508 if (Py_SIZE(rem))
3509 inexact = 1;
3510 Py_DECREF(rem);
3511 }
3512 x_size = ABS(Py_SIZE(x));
3513 assert(x_size > 0); /* result of division is never zero */
3514 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 /* The number of extra bits that have to be rounded away. */
3517 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3518 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 /* Round by directly modifying the low digit of x. */
3521 mask = (digit)1 << (extra_bits - 1);
3522 low = x->ob_digit[0] | inexact;
3523 if (low & mask && low & (3*mask-1))
3524 low += mask;
3525 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 /* Convert x to a double dx; the conversion is exact. */
3528 dx = x->ob_digit[--x_size];
3529 while (x_size > 0)
3530 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3531 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 /* Check whether ldexp result will overflow a double. */
3534 if (shift + x_bits >= DBL_MAX_EXP &&
3535 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3536 goto overflow;
3537 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003538
3539 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003541
3542 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003544
3545 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 PyErr_SetString(PyExc_OverflowError,
3547 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003548 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003550}
3551
3552static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003553long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 CHECK_BINOP(a, b);
3558
3559 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3560 mod = NULL;
3561 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003562}
3563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003564static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003565long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 PyLongObject *div, *mod;
3568 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3573 return NULL;
3574 }
3575 z = PyTuple_New(2);
3576 if (z != NULL) {
3577 PyTuple_SetItem(z, 0, (PyObject *) div);
3578 PyTuple_SetItem(z, 1, (PyObject *) mod);
3579 }
3580 else {
3581 Py_DECREF(div);
3582 Py_DECREF(mod);
3583 }
3584 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003585}
3586
Tim Peters47e52ee2004-08-30 02:44:38 +00003587/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003588static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003589long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3592 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 PyLongObject *z = NULL; /* accumulated result */
3595 Py_ssize_t i, j, k; /* counters */
3596 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 /* 5-ary values. If the exponent is large enough, table is
3599 * precomputed so that table[i] == a**i % c for i in range(32).
3600 */
3601 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3602 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 /* a, b, c = v, w, x */
3605 CHECK_BINOP(v, w);
3606 a = (PyLongObject*)v; Py_INCREF(a);
3607 b = (PyLongObject*)w; Py_INCREF(b);
3608 if (PyLong_Check(x)) {
3609 c = (PyLongObject *)x;
3610 Py_INCREF(x);
3611 }
3612 else if (x == Py_None)
3613 c = NULL;
3614 else {
3615 Py_DECREF(a);
3616 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003617 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 }
Tim Peters4c483c42001-09-05 06:24:58 +00003619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3621 if (c) {
3622 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003623 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 goto Error;
3625 }
3626 else {
3627 /* else return a float. This works because we know
3628 that this calls float_pow() which converts its
3629 arguments to double. */
3630 Py_DECREF(a);
3631 Py_DECREF(b);
3632 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3633 }
3634 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 if (c) {
3637 /* if modulus == 0:
3638 raise ValueError() */
3639 if (Py_SIZE(c) == 0) {
3640 PyErr_SetString(PyExc_ValueError,
3641 "pow() 3rd argument cannot be 0");
3642 goto Error;
3643 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 /* if modulus < 0:
3646 negativeOutput = True
3647 modulus = -modulus */
3648 if (Py_SIZE(c) < 0) {
3649 negativeOutput = 1;
3650 temp = (PyLongObject *)_PyLong_Copy(c);
3651 if (temp == NULL)
3652 goto Error;
3653 Py_DECREF(c);
3654 c = temp;
3655 temp = NULL;
3656 NEGATE(c);
3657 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 /* if modulus == 1:
3660 return 0 */
3661 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3662 z = (PyLongObject *)PyLong_FromLong(0L);
3663 goto Done;
3664 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 /* if base < 0:
3667 base = base % modulus
3668 Having the base positive just makes things easier. */
3669 if (Py_SIZE(a) < 0) {
3670 if (l_divmod(a, c, NULL, &temp) < 0)
3671 goto Error;
3672 Py_DECREF(a);
3673 a = temp;
3674 temp = NULL;
3675 }
3676 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 /* At this point a, b, and c are guaranteed non-negative UNLESS
3679 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 z = (PyLongObject *)PyLong_FromLong(1L);
3682 if (z == NULL)
3683 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 /* Perform a modular reduction, X = X % c, but leave X alone if c
3686 * is NULL.
3687 */
3688#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003689 do { \
3690 if (c != NULL) { \
3691 if (l_divmod(X, c, NULL, &temp) < 0) \
3692 goto Error; \
3693 Py_XDECREF(X); \
3694 X = temp; \
3695 temp = NULL; \
3696 } \
3697 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 /* Multiply two values, then reduce the result:
3700 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003701#define MULT(X, Y, result) \
3702 do { \
3703 temp = (PyLongObject *)long_mul(X, Y); \
3704 if (temp == NULL) \
3705 goto Error; \
3706 Py_XDECREF(result); \
3707 result = temp; \
3708 temp = NULL; \
3709 REDUCE(result); \
3710 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3713 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3714 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3715 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3716 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003719 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003721 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 }
3723 }
3724 }
3725 else {
3726 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3727 Py_INCREF(z); /* still holds 1L */
3728 table[0] = z;
3729 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003730 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3733 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3736 const int index = (bi >> j) & 0x1f;
3737 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003738 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003740 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 }
3742 }
3743 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 if (negativeOutput && (Py_SIZE(z) != 0)) {
3746 temp = (PyLongObject *)long_sub(z, c);
3747 if (temp == NULL)
3748 goto Error;
3749 Py_DECREF(z);
3750 z = temp;
3751 temp = NULL;
3752 }
3753 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003754
Mark Dickinson22b20182010-05-10 21:27:53 +00003755 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 if (z != NULL) {
3757 Py_DECREF(z);
3758 z = NULL;
3759 }
3760 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003761 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3763 for (i = 0; i < 32; ++i)
3764 Py_XDECREF(table[i]);
3765 }
3766 Py_DECREF(a);
3767 Py_DECREF(b);
3768 Py_XDECREF(c);
3769 Py_XDECREF(temp);
3770 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003771}
3772
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003773static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003774long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 /* Implement ~x as -(x+1) */
3777 PyLongObject *x;
3778 PyLongObject *w;
3779 if (ABS(Py_SIZE(v)) <=1)
3780 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3781 w = (PyLongObject *)PyLong_FromLong(1L);
3782 if (w == NULL)
3783 return NULL;
3784 x = (PyLongObject *) long_add(v, w);
3785 Py_DECREF(w);
3786 if (x == NULL)
3787 return NULL;
3788 Py_SIZE(x) = -(Py_SIZE(x));
3789 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003790}
3791
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003792static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003793long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 PyLongObject *z;
3796 if (ABS(Py_SIZE(v)) <= 1)
3797 return PyLong_FromLong(-MEDIUM_VALUE(v));
3798 z = (PyLongObject *)_PyLong_Copy(v);
3799 if (z != NULL)
3800 Py_SIZE(z) = -(Py_SIZE(v));
3801 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003802}
3803
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003804static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003805long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 if (Py_SIZE(v) < 0)
3808 return long_neg(v);
3809 else
3810 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003811}
3812
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003813static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003814long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003817}
3818
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003819static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003820long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 PyLongObject *z = NULL;
3823 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3824 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 if (Py_SIZE(a) < 0) {
3829 /* Right shifting negative numbers is harder */
3830 PyLongObject *a1, *a2;
3831 a1 = (PyLongObject *) long_invert(a);
3832 if (a1 == NULL)
3833 goto rshift_error;
3834 a2 = (PyLongObject *) long_rshift(a1, b);
3835 Py_DECREF(a1);
3836 if (a2 == NULL)
3837 goto rshift_error;
3838 z = (PyLongObject *) long_invert(a2);
3839 Py_DECREF(a2);
3840 }
3841 else {
3842 shiftby = PyLong_AsSsize_t((PyObject *)b);
3843 if (shiftby == -1L && PyErr_Occurred())
3844 goto rshift_error;
3845 if (shiftby < 0) {
3846 PyErr_SetString(PyExc_ValueError,
3847 "negative shift count");
3848 goto rshift_error;
3849 }
3850 wordshift = shiftby / PyLong_SHIFT;
3851 newsize = ABS(Py_SIZE(a)) - wordshift;
3852 if (newsize <= 0)
3853 return PyLong_FromLong(0);
3854 loshift = shiftby % PyLong_SHIFT;
3855 hishift = PyLong_SHIFT - loshift;
3856 lomask = ((digit)1 << hishift) - 1;
3857 himask = PyLong_MASK ^ lomask;
3858 z = _PyLong_New(newsize);
3859 if (z == NULL)
3860 goto rshift_error;
3861 if (Py_SIZE(a) < 0)
3862 Py_SIZE(z) = -(Py_SIZE(z));
3863 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3864 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3865 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003866 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 }
3868 z = long_normalize(z);
3869 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003870 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003872
Guido van Rossumc6913e71991-11-19 20:26:46 +00003873}
3874
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003875static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003876long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 /* This version due to Tim Peters */
3879 PyLongObject *a = (PyLongObject*)v;
3880 PyLongObject *b = (PyLongObject*)w;
3881 PyLongObject *z = NULL;
3882 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3883 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 shiftby = PyLong_AsSsize_t((PyObject *)b);
3888 if (shiftby == -1L && PyErr_Occurred())
3889 goto lshift_error;
3890 if (shiftby < 0) {
3891 PyErr_SetString(PyExc_ValueError, "negative shift count");
3892 goto lshift_error;
3893 }
3894 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3895 wordshift = shiftby / PyLong_SHIFT;
3896 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 oldsize = ABS(Py_SIZE(a));
3899 newsize = oldsize + wordshift;
3900 if (remshift)
3901 ++newsize;
3902 z = _PyLong_New(newsize);
3903 if (z == NULL)
3904 goto lshift_error;
3905 if (Py_SIZE(a) < 0)
3906 NEGATE(z);
3907 for (i = 0; i < wordshift; i++)
3908 z->ob_digit[i] = 0;
3909 accum = 0;
3910 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3911 accum |= (twodigits)a->ob_digit[j] << remshift;
3912 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3913 accum >>= PyLong_SHIFT;
3914 }
3915 if (remshift)
3916 z->ob_digit[newsize-1] = (digit)accum;
3917 else
3918 assert(!accum);
3919 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003920 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003922}
3923
Mark Dickinson27a87a22009-10-25 20:43:34 +00003924/* Compute two's complement of digit vector a[0:m], writing result to
3925 z[0:m]. The digit vector a need not be normalized, but should not
3926 be entirely zero. a and z may point to the same digit vector. */
3927
3928static void
3929v_complement(digit *z, digit *a, Py_ssize_t m)
3930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 Py_ssize_t i;
3932 digit carry = 1;
3933 for (i = 0; i < m; ++i) {
3934 carry += a[i] ^ PyLong_MASK;
3935 z[i] = carry & PyLong_MASK;
3936 carry >>= PyLong_SHIFT;
3937 }
3938 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003939}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003940
3941/* Bitwise and/xor/or operations */
3942
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003943static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003944long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003946 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 int nega, negb, negz;
3949 Py_ssize_t size_a, size_b, size_z, i;
3950 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 /* Bitwise operations for negative numbers operate as though
3953 on a two's complement representation. So convert arguments
3954 from sign-magnitude to two's complement, and convert the
3955 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 /* If a is negative, replace it by its two's complement. */
3958 size_a = ABS(Py_SIZE(a));
3959 nega = Py_SIZE(a) < 0;
3960 if (nega) {
3961 z = _PyLong_New(size_a);
3962 if (z == NULL)
3963 return NULL;
3964 v_complement(z->ob_digit, a->ob_digit, size_a);
3965 a = z;
3966 }
3967 else
3968 /* Keep reference count consistent. */
3969 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 /* Same for b. */
3972 size_b = ABS(Py_SIZE(b));
3973 negb = Py_SIZE(b) < 0;
3974 if (negb) {
3975 z = _PyLong_New(size_b);
3976 if (z == NULL) {
3977 Py_DECREF(a);
3978 return NULL;
3979 }
3980 v_complement(z->ob_digit, b->ob_digit, size_b);
3981 b = z;
3982 }
3983 else
3984 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 /* Swap a and b if necessary to ensure size_a >= size_b. */
3987 if (size_a < size_b) {
3988 z = a; a = b; b = z;
3989 size_z = size_a; size_a = size_b; size_b = size_z;
3990 negz = nega; nega = negb; negb = negz;
3991 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 /* JRH: The original logic here was to allocate the result value (z)
3994 as the longer of the two operands. However, there are some cases
3995 where the result is guaranteed to be shorter than that: AND of two
3996 positives, OR of two negatives: use the shorter number. AND with
3997 mixed signs: use the positive number. OR with mixed signs: use the
3998 negative number.
3999 */
4000 switch (op) {
4001 case '^':
4002 negz = nega ^ negb;
4003 size_z = size_a;
4004 break;
4005 case '&':
4006 negz = nega & negb;
4007 size_z = negb ? size_a : size_b;
4008 break;
4009 case '|':
4010 negz = nega | negb;
4011 size_z = negb ? size_b : size_a;
4012 break;
4013 default:
4014 PyErr_BadArgument();
4015 return NULL;
4016 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 /* We allow an extra digit if z is negative, to make sure that
4019 the final two's complement of z doesn't overflow. */
4020 z = _PyLong_New(size_z + negz);
4021 if (z == NULL) {
4022 Py_DECREF(a);
4023 Py_DECREF(b);
4024 return NULL;
4025 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 /* Compute digits for overlap of a and b. */
4028 switch(op) {
4029 case '&':
4030 for (i = 0; i < size_b; ++i)
4031 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4032 break;
4033 case '|':
4034 for (i = 0; i < size_b; ++i)
4035 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4036 break;
4037 case '^':
4038 for (i = 0; i < size_b; ++i)
4039 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4040 break;
4041 default:
4042 PyErr_BadArgument();
4043 return NULL;
4044 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 /* Copy any remaining digits of a, inverting if necessary. */
4047 if (op == '^' && negb)
4048 for (; i < size_z; ++i)
4049 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4050 else if (i < size_z)
4051 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4052 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 /* Complement result if negative. */
4055 if (negz) {
4056 Py_SIZE(z) = -(Py_SIZE(z));
4057 z->ob_digit[size_z] = PyLong_MASK;
4058 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4059 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 Py_DECREF(a);
4062 Py_DECREF(b);
4063 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004064}
4065
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004066static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004067long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 PyObject *c;
4070 CHECK_BINOP(a, b);
4071 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4072 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004073}
4074
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004075static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004076long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 PyObject *c;
4079 CHECK_BINOP(a, b);
4080 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4081 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004082}
4083
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004084static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004085long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 PyObject *c;
4088 CHECK_BINOP(a, b);
4089 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4090 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004091}
4092
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004093static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004094long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 if (PyLong_CheckExact(v))
4097 Py_INCREF(v);
4098 else
4099 v = _PyLong_Copy((PyLongObject *)v);
4100 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004101}
4102
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004103static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004104long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 double result;
4107 result = PyLong_AsDouble(v);
4108 if (result == -1.0 && PyErr_Occurred())
4109 return NULL;
4110 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004111}
4112
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004113static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004114long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004115
Tim Peters6d6c1a32001-08-02 04:15:00 +00004116static PyObject *
4117long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4118{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004119 PyObject *obase = NULL, *x = NULL;
4120 long base;
4121 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 if (type != &PyLong_Type)
4125 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004126 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4127 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 return NULL;
4129 if (x == NULL)
4130 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004131 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004133
4134 base = PyLong_AsLongAndOverflow(obase, &overflow);
4135 if (base == -1 && PyErr_Occurred())
4136 return NULL;
4137 if (overflow || (base != 0 && base < 2) || base > 36) {
4138 PyErr_SetString(PyExc_ValueError,
4139 "int() arg 2 must be >= 2 and <= 36");
4140 return NULL;
4141 }
4142
4143 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004144 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4146 /* Since PyLong_FromString doesn't have a length parameter,
4147 * check here for possible NULs in the string. */
4148 char *string;
4149 Py_ssize_t size = Py_SIZE(x);
4150 if (PyByteArray_Check(x))
4151 string = PyByteArray_AS_STRING(x);
4152 else
4153 string = PyBytes_AS_STRING(x);
4154 if (strlen(string) != (size_t)size) {
4155 /* We only see this if there's a null byte in x,
4156 x is a bytes or buffer, *and* a base is given. */
4157 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004158 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004159 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 return NULL;
4161 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004162 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 }
4164 else {
4165 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004166 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 return NULL;
4168 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004169}
4170
Guido van Rossumbef14172001-08-29 15:47:46 +00004171/* Wimpy, slow approach to tp_new calls for subtypes of long:
4172 first create a regular long from whatever arguments we got,
4173 then allocate a subtype instance and initialize it from
4174 the regular long. The regular long is then thrown away.
4175*/
4176static PyObject *
4177long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 PyLongObject *tmp, *newobj;
4180 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 assert(PyType_IsSubtype(type, &PyLong_Type));
4183 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4184 if (tmp == NULL)
4185 return NULL;
4186 assert(PyLong_CheckExact(tmp));
4187 n = Py_SIZE(tmp);
4188 if (n < 0)
4189 n = -n;
4190 newobj = (PyLongObject *)type->tp_alloc(type, n);
4191 if (newobj == NULL) {
4192 Py_DECREF(tmp);
4193 return NULL;
4194 }
4195 assert(PyLong_Check(newobj));
4196 Py_SIZE(newobj) = Py_SIZE(tmp);
4197 for (i = 0; i < n; i++)
4198 newobj->ob_digit[i] = tmp->ob_digit[i];
4199 Py_DECREF(tmp);
4200 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004201}
4202
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004203static PyObject *
4204long_getnewargs(PyLongObject *v)
4205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004207}
4208
Guido van Rossumb43daf72007-08-01 18:08:08 +00004209static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004210long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004212}
4213
4214static PyObject *
4215long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004217}
4218
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004219static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004220long__format__(PyObject *self, PyObject *args)
4221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4225 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004226 return _PyLong_FormatAdvanced(self, format_spec, 0,
4227 PyUnicode_GET_LENGTH(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004228}
4229
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004230/* Return a pair (q, r) such that a = b * q + r, and
4231 abs(r) <= abs(b)/2, with equality possible only if q is even.
4232 In other words, q == a / b, rounded to the nearest integer using
4233 round-half-to-even. */
4234
4235PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004236_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004237{
4238 PyLongObject *quo = NULL, *rem = NULL;
4239 PyObject *one = NULL, *twice_rem, *result, *temp;
4240 int cmp, quo_is_odd, quo_is_neg;
4241
4242 /* Equivalent Python code:
4243
4244 def divmod_near(a, b):
4245 q, r = divmod(a, b)
4246 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4247 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4248 # positive, 2 * r < b if b negative.
4249 greater_than_half = 2*r > b if b > 0 else 2*r < b
4250 exactly_half = 2*r == b
4251 if greater_than_half or exactly_half and q % 2 == 1:
4252 q += 1
4253 r -= b
4254 return q, r
4255
4256 */
4257 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4258 PyErr_SetString(PyExc_TypeError,
4259 "non-integer arguments in division");
4260 return NULL;
4261 }
4262
4263 /* Do a and b have different signs? If so, quotient is negative. */
4264 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4265
4266 one = PyLong_FromLong(1L);
4267 if (one == NULL)
4268 return NULL;
4269
4270 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4271 goto error;
4272
4273 /* compare twice the remainder with the divisor, to see
4274 if we need to adjust the quotient and remainder */
4275 twice_rem = long_lshift((PyObject *)rem, one);
4276 if (twice_rem == NULL)
4277 goto error;
4278 if (quo_is_neg) {
4279 temp = long_neg((PyLongObject*)twice_rem);
4280 Py_DECREF(twice_rem);
4281 twice_rem = temp;
4282 if (twice_rem == NULL)
4283 goto error;
4284 }
4285 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4286 Py_DECREF(twice_rem);
4287
4288 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4289 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4290 /* fix up quotient */
4291 if (quo_is_neg)
4292 temp = long_sub(quo, (PyLongObject *)one);
4293 else
4294 temp = long_add(quo, (PyLongObject *)one);
4295 Py_DECREF(quo);
4296 quo = (PyLongObject *)temp;
4297 if (quo == NULL)
4298 goto error;
4299 /* and remainder */
4300 if (quo_is_neg)
4301 temp = long_add(rem, (PyLongObject *)b);
4302 else
4303 temp = long_sub(rem, (PyLongObject *)b);
4304 Py_DECREF(rem);
4305 rem = (PyLongObject *)temp;
4306 if (rem == NULL)
4307 goto error;
4308 }
4309
4310 result = PyTuple_New(2);
4311 if (result == NULL)
4312 goto error;
4313
4314 /* PyTuple_SET_ITEM steals references */
4315 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4316 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4317 Py_DECREF(one);
4318 return result;
4319
4320 error:
4321 Py_XDECREF(quo);
4322 Py_XDECREF(rem);
4323 Py_XDECREF(one);
4324 return NULL;
4325}
4326
Eric Smith8c663262007-08-25 02:26:07 +00004327static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004328long_round(PyObject *self, PyObject *args)
4329{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004330 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004331
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004332 /* To round an integer m to the nearest 10**n (n positive), we make use of
4333 * the divmod_near operation, defined by:
4334 *
4335 * divmod_near(a, b) = (q, r)
4336 *
4337 * where q is the nearest integer to the quotient a / b (the
4338 * nearest even integer in the case of a tie) and r == a - q * b.
4339 * Hence q * b = a - r is the nearest multiple of b to a,
4340 * preferring even multiples in the case of a tie.
4341 *
4342 * So the nearest multiple of 10**n to m is:
4343 *
4344 * m - divmod_near(m, 10**n)[1].
4345 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4347 return NULL;
4348 if (o_ndigits == NULL)
4349 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004350
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004351 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 if (ndigits == NULL)
4353 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004354
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004355 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 if (Py_SIZE(ndigits) >= 0) {
4357 Py_DECREF(ndigits);
4358 return long_long(self);
4359 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004360
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004361 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4362 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004364 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004366 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004367
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004368 result = PyLong_FromLong(10L);
4369 if (result == NULL) {
4370 Py_DECREF(ndigits);
4371 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004373
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004374 temp = long_pow(result, ndigits, Py_None);
4375 Py_DECREF(ndigits);
4376 Py_DECREF(result);
4377 result = temp;
4378 if (result == NULL)
4379 return NULL;
4380
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004381 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004382 Py_DECREF(result);
4383 result = temp;
4384 if (result == NULL)
4385 return NULL;
4386
4387 temp = long_sub((PyLongObject *)self,
4388 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4389 Py_DECREF(result);
4390 result = temp;
4391
4392 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004393}
4394
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004395static PyObject *
4396long_sizeof(PyLongObject *v)
4397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4401 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004402}
4403
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004404static PyObject *
4405long_bit_length(PyLongObject *v)
4406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 PyLongObject *result, *x, *y;
4408 Py_ssize_t ndigits, msd_bits = 0;
4409 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 assert(v != NULL);
4412 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 ndigits = ABS(Py_SIZE(v));
4415 if (ndigits == 0)
4416 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 msd = v->ob_digit[ndigits-1];
4419 while (msd >= 32) {
4420 msd_bits += 6;
4421 msd >>= 6;
4422 }
4423 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4426 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 /* expression above may overflow; use Python integers instead */
4429 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4430 if (result == NULL)
4431 return NULL;
4432 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4433 if (x == NULL)
4434 goto error;
4435 y = (PyLongObject *)long_mul(result, x);
4436 Py_DECREF(x);
4437 if (y == NULL)
4438 goto error;
4439 Py_DECREF(result);
4440 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4443 if (x == NULL)
4444 goto error;
4445 y = (PyLongObject *)long_add(result, x);
4446 Py_DECREF(x);
4447 if (y == NULL)
4448 goto error;
4449 Py_DECREF(result);
4450 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004453
Mark Dickinson22b20182010-05-10 21:27:53 +00004454 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 Py_DECREF(result);
4456 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004457}
4458
4459PyDoc_STRVAR(long_bit_length_doc,
4460"int.bit_length() -> int\n\
4461\n\
4462Number of bits necessary to represent self in binary.\n\
4463>>> bin(37)\n\
4464'0b100101'\n\
4465>>> (37).bit_length()\n\
44666");
4467
Christian Heimes53876d92008-04-19 00:31:39 +00004468#if 0
4469static PyObject *
4470long_is_finite(PyObject *v)
4471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004473}
4474#endif
4475
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004476
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004477static PyObject *
4478long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 PyObject *byteorder_str;
4481 PyObject *is_signed_obj = NULL;
4482 Py_ssize_t length;
4483 int little_endian;
4484 int is_signed;
4485 PyObject *bytes;
4486 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004488 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4489 &length, &byteorder_str,
4490 &is_signed_obj))
4491 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 if (args != NULL && Py_SIZE(args) > 2) {
4494 PyErr_SetString(PyExc_TypeError,
4495 "'signed' is a keyword-only argument");
4496 return NULL;
4497 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4500 little_endian = 1;
4501 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4502 little_endian = 0;
4503 else {
4504 PyErr_SetString(PyExc_ValueError,
4505 "byteorder must be either 'little' or 'big'");
4506 return NULL;
4507 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 if (is_signed_obj != NULL) {
4510 int cmp = PyObject_IsTrue(is_signed_obj);
4511 if (cmp < 0)
4512 return NULL;
4513 is_signed = cmp ? 1 : 0;
4514 }
4515 else {
4516 /* If the signed argument was omitted, use False as the
4517 default. */
4518 is_signed = 0;
4519 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 if (length < 0) {
4522 PyErr_SetString(PyExc_ValueError,
4523 "length argument must be non-negative");
4524 return NULL;
4525 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004527 bytes = PyBytes_FromStringAndSize(NULL, length);
4528 if (bytes == NULL)
4529 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4532 length, little_endian, is_signed) < 0) {
4533 Py_DECREF(bytes);
4534 return NULL;
4535 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004538}
4539
Mark Dickinson078c2532010-01-30 18:06:17 +00004540PyDoc_STRVAR(long_to_bytes_doc,
4541"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004542\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004543Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004544\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004546raised if the integer is not representable with the given number of\n\
4547bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004548\n\
4549The byteorder argument determines the byte order used to represent the\n\
4550integer. If byteorder is 'big', the most significant byte is at the\n\
4551beginning of the byte array. If byteorder is 'little', the most\n\
4552significant byte is at the end of the byte array. To request the native\n\
4553byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4554\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004555The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004557is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004558
4559static PyObject *
4560long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 PyObject *byteorder_str;
4563 PyObject *is_signed_obj = NULL;
4564 int little_endian;
4565 int is_signed;
4566 PyObject *obj;
4567 PyObject *bytes;
4568 PyObject *long_obj;
4569 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4572 &obj, &byteorder_str,
4573 &is_signed_obj))
4574 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 if (args != NULL && Py_SIZE(args) > 2) {
4577 PyErr_SetString(PyExc_TypeError,
4578 "'signed' is a keyword-only argument");
4579 return NULL;
4580 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4583 little_endian = 1;
4584 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4585 little_endian = 0;
4586 else {
4587 PyErr_SetString(PyExc_ValueError,
4588 "byteorder must be either 'little' or 'big'");
4589 return NULL;
4590 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 if (is_signed_obj != NULL) {
4593 int cmp = PyObject_IsTrue(is_signed_obj);
4594 if (cmp < 0)
4595 return NULL;
4596 is_signed = cmp ? 1 : 0;
4597 }
4598 else {
4599 /* If the signed argument was omitted, use False as the
4600 default. */
4601 is_signed = 0;
4602 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 bytes = PyObject_Bytes(obj);
4605 if (bytes == NULL)
4606 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004608 long_obj = _PyLong_FromByteArray(
4609 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4610 little_endian, is_signed);
4611 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 /* If from_bytes() was used on subclass, allocate new subclass
4614 * instance, initialize it with decoded long value and return it.
4615 */
4616 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4617 PyLongObject *newobj;
4618 int i;
4619 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 newobj = (PyLongObject *)type->tp_alloc(type, n);
4622 if (newobj == NULL) {
4623 Py_DECREF(long_obj);
4624 return NULL;
4625 }
4626 assert(PyLong_Check(newobj));
4627 Py_SIZE(newobj) = Py_SIZE(long_obj);
4628 for (i = 0; i < n; i++) {
4629 newobj->ob_digit[i] =
4630 ((PyLongObject *)long_obj)->ob_digit[i];
4631 }
4632 Py_DECREF(long_obj);
4633 return (PyObject *)newobj;
4634 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004637}
4638
Mark Dickinson078c2532010-01-30 18:06:17 +00004639PyDoc_STRVAR(long_from_bytes_doc,
4640"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4641\n\
4642Return the integer represented by the given array of bytes.\n\
4643\n\
4644The bytes argument must either support the buffer protocol or be an\n\
4645iterable object producing bytes. Bytes and bytearray are examples of\n\
4646built-in objects that support the buffer protocol.\n\
4647\n\
4648The byteorder argument determines the byte order used to represent the\n\
4649integer. If byteorder is 'big', the most significant byte is at the\n\
4650beginning of the byte array. If byteorder is 'little', the most\n\
4651significant byte is at the end of the byte array. To request the native\n\
4652byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4653\n\
4654The signed keyword-only argument indicates whether two's complement is\n\
4655used to represent the integer.");
4656
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004657static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4659 "Returns self, the complex conjugate of any int."},
4660 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4661 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004662#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4664 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004665#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 {"to_bytes", (PyCFunction)long_to_bytes,
4667 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4668 {"from_bytes", (PyCFunction)long_from_bytes,
4669 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4670 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4671 "Truncating an Integral returns itself."},
4672 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4673 "Flooring an Integral returns itself."},
4674 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4675 "Ceiling of an Integral returns itself."},
4676 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4677 "Rounding an Integral returns itself.\n"
4678 "Rounding with an ndigits argument also returns an integer."},
4679 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4680 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4681 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4682 "Returns size in memory, in bytes"},
4683 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004684};
4685
Guido van Rossumb43daf72007-08-01 18:08:08 +00004686static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004687 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004688 (getter)long_long, (setter)NULL,
4689 "the real part of a complex number",
4690 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004691 {"imag",
4692 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004693 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004694 NULL},
4695 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004696 (getter)long_long, (setter)NULL,
4697 "the numerator of a rational number in lowest terms",
4698 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004699 {"denominator",
4700 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004701 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004702 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004703 {NULL} /* Sentinel */
4704};
4705
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004706PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004707"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004708\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004709Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004710point argument will be truncated towards zero (this does not include a\n\
4711string representation of a floating point number!) When converting a\n\
4712string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004713converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004714
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004715static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004716 (binaryfunc)long_add, /*nb_add*/
4717 (binaryfunc)long_sub, /*nb_subtract*/
4718 (binaryfunc)long_mul, /*nb_multiply*/
4719 long_mod, /*nb_remainder*/
4720 long_divmod, /*nb_divmod*/
4721 long_pow, /*nb_power*/
4722 (unaryfunc)long_neg, /*nb_negative*/
4723 (unaryfunc)long_long, /*tp_positive*/
4724 (unaryfunc)long_abs, /*tp_absolute*/
4725 (inquiry)long_bool, /*tp_bool*/
4726 (unaryfunc)long_invert, /*nb_invert*/
4727 long_lshift, /*nb_lshift*/
4728 (binaryfunc)long_rshift, /*nb_rshift*/
4729 long_and, /*nb_and*/
4730 long_xor, /*nb_xor*/
4731 long_or, /*nb_or*/
4732 long_long, /*nb_int*/
4733 0, /*nb_reserved*/
4734 long_float, /*nb_float*/
4735 0, /* nb_inplace_add */
4736 0, /* nb_inplace_subtract */
4737 0, /* nb_inplace_multiply */
4738 0, /* nb_inplace_remainder */
4739 0, /* nb_inplace_power */
4740 0, /* nb_inplace_lshift */
4741 0, /* nb_inplace_rshift */
4742 0, /* nb_inplace_and */
4743 0, /* nb_inplace_xor */
4744 0, /* nb_inplace_or */
4745 long_div, /* nb_floor_divide */
4746 long_true_divide, /* nb_true_divide */
4747 0, /* nb_inplace_floor_divide */
4748 0, /* nb_inplace_true_divide */
4749 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004750};
4751
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004752PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004753 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4754 "int", /* tp_name */
4755 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4756 sizeof(digit), /* tp_itemsize */
4757 long_dealloc, /* tp_dealloc */
4758 0, /* tp_print */
4759 0, /* tp_getattr */
4760 0, /* tp_setattr */
4761 0, /* tp_reserved */
4762 long_to_decimal_string, /* tp_repr */
4763 &long_as_number, /* tp_as_number */
4764 0, /* tp_as_sequence */
4765 0, /* tp_as_mapping */
4766 (hashfunc)long_hash, /* tp_hash */
4767 0, /* tp_call */
4768 long_to_decimal_string, /* tp_str */
4769 PyObject_GenericGetAttr, /* tp_getattro */
4770 0, /* tp_setattro */
4771 0, /* tp_as_buffer */
4772 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4773 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4774 long_doc, /* tp_doc */
4775 0, /* tp_traverse */
4776 0, /* tp_clear */
4777 long_richcompare, /* tp_richcompare */
4778 0, /* tp_weaklistoffset */
4779 0, /* tp_iter */
4780 0, /* tp_iternext */
4781 long_methods, /* tp_methods */
4782 0, /* tp_members */
4783 long_getset, /* tp_getset */
4784 0, /* tp_base */
4785 0, /* tp_dict */
4786 0, /* tp_descr_get */
4787 0, /* tp_descr_set */
4788 0, /* tp_dictoffset */
4789 0, /* tp_init */
4790 0, /* tp_alloc */
4791 long_new, /* tp_new */
4792 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004793};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004794
Mark Dickinsonbd792642009-03-18 20:06:12 +00004795static PyTypeObject Int_InfoType;
4796
4797PyDoc_STRVAR(int_info__doc__,
4798"sys.int_info\n\
4799\n\
4800A struct sequence that holds information about Python's\n\
4801internal representation of integers. The attributes are read only.");
4802
4803static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004805 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004807};
4808
4809static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 "sys.int_info", /* name */
4811 int_info__doc__, /* doc */
4812 int_info_fields, /* fields */
4813 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004814};
4815
4816PyObject *
4817PyLong_GetInfo(void)
4818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004819 PyObject* int_info;
4820 int field = 0;
4821 int_info = PyStructSequence_New(&Int_InfoType);
4822 if (int_info == NULL)
4823 return NULL;
4824 PyStructSequence_SET_ITEM(int_info, field++,
4825 PyLong_FromLong(PyLong_SHIFT));
4826 PyStructSequence_SET_ITEM(int_info, field++,
4827 PyLong_FromLong(sizeof(digit)));
4828 if (PyErr_Occurred()) {
4829 Py_CLEAR(int_info);
4830 return NULL;
4831 }
4832 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004833}
4834
Guido van Rossumddefaf32007-01-14 03:31:43 +00004835int
4836_PyLong_Init(void)
4837{
4838#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 int ival, size;
4840 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4843 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4844 if (Py_TYPE(v) == &PyLong_Type) {
4845 /* The element is already initialized, most likely
4846 * the Python interpreter was initialized before.
4847 */
4848 Py_ssize_t refcnt;
4849 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4852 _Py_NewReference(op);
4853 /* _Py_NewReference sets the ref count to 1 but
4854 * the ref count might be larger. Set the refcnt
4855 * to the original refcnt + 1 */
4856 Py_REFCNT(op) = refcnt + 1;
4857 assert(Py_SIZE(op) == size);
4858 assert(v->ob_digit[0] == abs(ival));
4859 }
4860 else {
4861 PyObject_INIT(v, &PyLong_Type);
4862 }
4863 Py_SIZE(v) = size;
4864 v->ob_digit[0] = abs(ival);
4865 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004866#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004867 /* initialize int_info */
4868 if (Int_InfoType.tp_name == 0)
4869 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004871 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004872}
4873
4874void
4875PyLong_Fini(void)
4876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 /* Integers are currently statically allocated. Py_DECREF is not
4878 needed, but Python must forget about the reference or multiple
4879 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004880#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004881 int i;
4882 PyLongObject *v = small_ints;
4883 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4884 _Py_DEC_REFTOTAL;
4885 _Py_ForgetReference((PyObject*)v);
4886 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004887#endif
4888}