blob: dbedadb5bafdf46a8caa98a5dcf817a7dbd67eb2 [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
Mark Dickinsonc286e582012-09-20 21:29:28 +010033Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#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
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000092#define SIGCHECK(PyTryBlock) \
93 do { \
94 if (PyErr_CheckSignals()) PyTryBlock \
95 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000096
Guido van Rossumedcc38a1991-05-05 20:09:44 +000097/* Normalize (remove leading zeros from) a long int object.
98 Doesn't attempt to free the storage--in most cases, due to the nature
99 of the algorithms used, this could save at most be one word anyway. */
100
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000101static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000102long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 Py_ssize_t j = ABS(Py_SIZE(v));
105 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 while (i > 0 && v->ob_digit[i-1] == 0)
108 --i;
109 if (i != j)
110 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
111 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000112}
113
114/* Allocate a new long int object with size digits.
115 Return NULL and set exception if we run out of memory. */
116
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000117#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000119
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000120PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000121_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 PyLongObject *result;
124 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
125 sizeof(digit)*size. Previous incarnations of this code used
126 sizeof(PyVarObject) instead of the offsetof, but this risks being
127 incorrect in the presence of padding between the PyVarObject header
128 and the digits. */
129 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
130 PyErr_SetString(PyExc_OverflowError,
131 "too many digits in integer");
132 return NULL;
133 }
134 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
135 size*sizeof(digit));
136 if (!result) {
137 PyErr_NoMemory();
138 return NULL;
139 }
140 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000141}
142
Tim Peters64b5ce32001-09-10 20:52:51 +0000143PyObject *
144_PyLong_Copy(PyLongObject *src)
145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 PyLongObject *result;
147 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 assert(src != NULL);
150 i = Py_SIZE(src);
151 if (i < 0)
152 i = -(i);
153 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100154 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 CHECK_SMALL_INT(ival);
156 }
157 result = _PyLong_New(i);
158 if (result != NULL) {
159 Py_SIZE(result) = Py_SIZE(src);
160 while (--i >= 0)
161 result->ob_digit[i] = src->ob_digit[i];
162 }
163 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000164}
165
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000166/* Create a new long int object from a C long int */
167
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000169PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 PyLongObject *v;
172 unsigned long abs_ival;
173 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
174 int ndigits = 0;
175 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (ival < 0) {
180 /* negate: can't write this as abs_ival = -ival since that
181 invokes undefined behaviour when ival is LONG_MIN */
182 abs_ival = 0U-(unsigned long)ival;
183 sign = -1;
184 }
185 else {
186 abs_ival = (unsigned long)ival;
187 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 /* Fast path for single-digit ints */
190 if (!(abs_ival >> PyLong_SHIFT)) {
191 v = _PyLong_New(1);
192 if (v) {
193 Py_SIZE(v) = sign;
194 v->ob_digit[0] = Py_SAFE_DOWNCAST(
195 abs_ival, unsigned long, digit);
196 }
197 return (PyObject*)v;
198 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000199
Mark Dickinson249b8982009-04-27 19:41:00 +0000200#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 /* 2 digits */
202 if (!(abs_ival >> 2*PyLong_SHIFT)) {
203 v = _PyLong_New(2);
204 if (v) {
205 Py_SIZE(v) = 2*sign;
206 v->ob_digit[0] = Py_SAFE_DOWNCAST(
207 abs_ival & PyLong_MASK, unsigned long, digit);
208 v->ob_digit[1] = Py_SAFE_DOWNCAST(
209 abs_ival >> PyLong_SHIFT, unsigned long, digit);
210 }
211 return (PyObject*)v;
212 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000213#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 /* Larger numbers: loop to determine number of digits */
216 t = abs_ival;
217 while (t) {
218 ++ndigits;
219 t >>= PyLong_SHIFT;
220 }
221 v = _PyLong_New(ndigits);
222 if (v != NULL) {
223 digit *p = v->ob_digit;
224 Py_SIZE(v) = ndigits*sign;
225 t = abs_ival;
226 while (t) {
227 *p++ = Py_SAFE_DOWNCAST(
228 t & PyLong_MASK, unsigned long, digit);
229 t >>= PyLong_SHIFT;
230 }
231 }
232 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000233}
234
Guido van Rossum53756b11997-01-03 17:14:46 +0000235/* Create a new long int object from a C unsigned long int */
236
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000237PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000238PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 PyLongObject *v;
241 unsigned long t;
242 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (ival < PyLong_BASE)
245 return PyLong_FromLong(ival);
246 /* Count the number of Python digits. */
247 t = (unsigned long)ival;
248 while (t) {
249 ++ndigits;
250 t >>= PyLong_SHIFT;
251 }
252 v = _PyLong_New(ndigits);
253 if (v != NULL) {
254 digit *p = v->ob_digit;
255 Py_SIZE(v) = ndigits;
256 while (ival) {
257 *p++ = (digit)(ival & PyLong_MASK);
258 ival >>= PyLong_SHIFT;
259 }
260 }
261 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000262}
263
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000264/* Create a new long int object from a C double */
265
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000266PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000267PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 PyLongObject *v;
270 double frac;
271 int i, ndig, expo, neg;
272 neg = 0;
273 if (Py_IS_INFINITY(dval)) {
274 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000275 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 return NULL;
277 }
278 if (Py_IS_NAN(dval)) {
279 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000280 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return NULL;
282 }
283 if (dval < 0.0) {
284 neg = 1;
285 dval = -dval;
286 }
287 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
288 if (expo <= 0)
289 return PyLong_FromLong(0L);
290 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
291 v = _PyLong_New(ndig);
292 if (v == NULL)
293 return NULL;
294 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
295 for (i = ndig; --i >= 0; ) {
296 digit bits = (digit)frac;
297 v->ob_digit[i] = bits;
298 frac = frac - (double)bits;
299 frac = ldexp(frac, PyLong_SHIFT);
300 }
301 if (neg)
302 Py_SIZE(v) = -(Py_SIZE(v));
303 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000304}
305
Thomas Wouters89f507f2006-12-13 04:49:30 +0000306/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
307 * anything about what happens when a signed integer operation overflows,
308 * and some compilers think they're doing you a favor by being "clever"
309 * then. The bit pattern for the largest postive signed long is
310 * (unsigned long)LONG_MAX, and for the smallest negative signed long
311 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
312 * However, some other compilers warn about applying unary minus to an
313 * unsigned operand. Hence the weird "0-".
314 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
316#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000317
Mark Dickinson8d48b432011-10-23 20:47:14 +0100318/* Get a C long int from a long int object or any object that has an __int__
319 method.
320
321 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
322 the result. Otherwise *overflow is 0.
323
324 For other errors (e.g., TypeError), return -1 and set an error condition.
325 In this case *overflow will be 0.
326*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000327
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
Mark Dickinson8d48b432011-10-23 20:47:14 +0100415/* Get a C long int from a long int object or any object that has an __int__
416 method. Return -1 and set an error if overflow occurs. */
417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000419PyLong_AsLong(PyObject *obj)
420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 int overflow;
422 long result = PyLong_AsLongAndOverflow(obj, &overflow);
423 if (overflow) {
424 /* XXX: could be cute and give a different
425 message for overflow == -1 */
426 PyErr_SetString(PyExc_OverflowError,
427 "Python int too large to convert to C long");
428 }
429 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000430}
431
Serhiy Storchaka78980432013-01-15 01:12:17 +0200432/* Get a C int from a long int object or any object that has an __int__
433 method. Return -1 and set an error if overflow occurs. */
434
435int
436_PyLong_AsInt(PyObject *obj)
437{
438 int overflow;
439 long result = PyLong_AsLongAndOverflow(obj, &overflow);
440 if (overflow || result > INT_MAX || result < INT_MIN) {
441 /* XXX: could be cute and give a different
442 message for overflow == -1 */
443 PyErr_SetString(PyExc_OverflowError,
444 "Python int too large to convert to C int");
445 return -1;
446 }
447 return (int)result;
448}
449
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000450/* Get a Py_ssize_t from a long int object.
451 Returns -1 and sets an error condition if overflow occurs. */
452
453Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000454PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 register PyLongObject *v;
456 size_t x, prev;
457 Py_ssize_t i;
458 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (vv == NULL) {
461 PyErr_BadInternalCall();
462 return -1;
463 }
464 if (!PyLong_Check(vv)) {
465 PyErr_SetString(PyExc_TypeError, "an integer is required");
466 return -1;
467 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 v = (PyLongObject *)vv;
470 i = Py_SIZE(v);
471 switch (i) {
472 case -1: return -(sdigit)v->ob_digit[0];
473 case 0: return 0;
474 case 1: return v->ob_digit[0];
475 }
476 sign = 1;
477 x = 0;
478 if (i < 0) {
479 sign = -1;
480 i = -(i);
481 }
482 while (--i >= 0) {
483 prev = x;
484 x = (x << PyLong_SHIFT) | v->ob_digit[i];
485 if ((x >> PyLong_SHIFT) != prev)
486 goto overflow;
487 }
488 /* Haven't lost any bits, but casting to a signed type requires
489 * extra care (see comment above).
490 */
491 if (x <= (size_t)PY_SSIZE_T_MAX) {
492 return (Py_ssize_t)x * sign;
493 }
494 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
495 return PY_SSIZE_T_MIN;
496 }
497 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000498
Mark Dickinson22b20182010-05-10 21:27:53 +0000499 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 PyErr_SetString(PyExc_OverflowError,
501 "Python int too large to convert to C ssize_t");
502 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000503}
504
Guido van Rossumd8c80482002-08-13 00:24:58 +0000505/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000506 Returns -1 and sets an error condition if overflow occurs. */
507
508unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000509PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 register PyLongObject *v;
512 unsigned long x, prev;
513 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (vv == NULL) {
516 PyErr_BadInternalCall();
517 return (unsigned long)-1;
518 }
519 if (!PyLong_Check(vv)) {
520 PyErr_SetString(PyExc_TypeError, "an integer is required");
521 return (unsigned long)-1;
522 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 v = (PyLongObject *)vv;
525 i = Py_SIZE(v);
526 x = 0;
527 if (i < 0) {
528 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000529 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return (unsigned long) -1;
531 }
532 switch (i) {
533 case 0: return 0;
534 case 1: return v->ob_digit[0];
535 }
536 while (--i >= 0) {
537 prev = x;
538 x = (x << PyLong_SHIFT) | v->ob_digit[i];
539 if ((x >> PyLong_SHIFT) != prev) {
540 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000541 "python int too large to convert "
542 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 return (unsigned long) -1;
544 }
545 }
546 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000547}
548
Stefan Krahb77c6c62011-09-12 16:22:47 +0200549/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
550 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000551
552size_t
553PyLong_AsSize_t(PyObject *vv)
554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 register PyLongObject *v;
556 size_t x, prev;
557 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (vv == NULL) {
560 PyErr_BadInternalCall();
561 return (size_t) -1;
562 }
563 if (!PyLong_Check(vv)) {
564 PyErr_SetString(PyExc_TypeError, "an integer is required");
565 return (size_t)-1;
566 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 v = (PyLongObject *)vv;
569 i = Py_SIZE(v);
570 x = 0;
571 if (i < 0) {
572 PyErr_SetString(PyExc_OverflowError,
573 "can't convert negative value to size_t");
574 return (size_t) -1;
575 }
576 switch (i) {
577 case 0: return 0;
578 case 1: return v->ob_digit[0];
579 }
580 while (--i >= 0) {
581 prev = x;
582 x = (x << PyLong_SHIFT) | v->ob_digit[i];
583 if ((x >> PyLong_SHIFT) != prev) {
584 PyErr_SetString(PyExc_OverflowError,
585 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200586 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 }
588 }
589 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000590}
591
Thomas Hellera4ea6032003-04-17 18:55:45 +0000592/* Get a C unsigned long int from a long int object, ignoring the high bits.
593 Returns -1 and sets an error condition if an error occurs. */
594
Guido van Rossumddefaf32007-01-14 03:31:43 +0000595static unsigned long
596_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 register PyLongObject *v;
599 unsigned long x;
600 Py_ssize_t i;
601 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (vv == NULL || !PyLong_Check(vv)) {
604 PyErr_BadInternalCall();
605 return (unsigned long) -1;
606 }
607 v = (PyLongObject *)vv;
608 i = Py_SIZE(v);
609 switch (i) {
610 case 0: return 0;
611 case 1: return v->ob_digit[0];
612 }
613 sign = 1;
614 x = 0;
615 if (i < 0) {
616 sign = -1;
617 i = -i;
618 }
619 while (--i >= 0) {
620 x = (x << PyLong_SHIFT) | v->ob_digit[i];
621 }
622 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000623}
624
Guido van Rossumddefaf32007-01-14 03:31:43 +0000625unsigned long
626PyLong_AsUnsignedLongMask(register PyObject *op)
627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 PyNumberMethods *nb;
629 PyLongObject *lo;
630 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (op && PyLong_Check(op))
633 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
636 nb->nb_int == NULL) {
637 PyErr_SetString(PyExc_TypeError, "an integer is required");
638 return (unsigned long)-1;
639 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 lo = (PyLongObject*) (*nb->nb_int) (op);
642 if (lo == NULL)
643 return (unsigned long)-1;
644 if (PyLong_Check(lo)) {
645 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
646 Py_DECREF(lo);
647 if (PyErr_Occurred())
648 return (unsigned long)-1;
649 return val;
650 }
651 else
652 {
653 Py_DECREF(lo);
654 PyErr_SetString(PyExc_TypeError,
655 "nb_int should return int object");
656 return (unsigned long)-1;
657 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000658}
659
Tim Peters5b8132f2003-01-31 15:52:05 +0000660int
661_PyLong_Sign(PyObject *vv)
662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 assert(v != NULL);
666 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000669}
670
Tim Petersbaefd9e2003-01-28 20:37:45 +0000671size_t
672_PyLong_NumBits(PyObject *vv)
673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyLongObject *v = (PyLongObject *)vv;
675 size_t result = 0;
676 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 assert(v != NULL);
679 assert(PyLong_Check(v));
680 ndigits = ABS(Py_SIZE(v));
681 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
682 if (ndigits > 0) {
683 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100684 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100686 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 do {
688 ++result;
689 if (result == 0)
690 goto Overflow;
691 msd >>= 1;
692 } while (msd);
693 }
694 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000695
Mark Dickinson22b20182010-05-10 21:27:53 +0000696 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
698 "to express in a platform size_t");
699 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000700}
701
Tim Peters2a9b3672001-06-11 21:23:58 +0000702PyObject *
703_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000705{
Mark Dickinson22b20182010-05-10 21:27:53 +0000706 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 int incr; /* direction to move pstartbyte */
708 const unsigned char* pendbyte; /* MSB of bytes */
709 size_t numsignificantbytes; /* number of bytes that matter */
710 Py_ssize_t ndigits; /* number of Python long digits */
711 PyLongObject* v; /* result */
712 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (n == 0)
715 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 if (little_endian) {
718 pstartbyte = bytes;
719 pendbyte = bytes + n - 1;
720 incr = 1;
721 }
722 else {
723 pstartbyte = bytes + n - 1;
724 pendbyte = bytes;
725 incr = -1;
726 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (is_signed)
729 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200732 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 is positive, and leading 0xff bytes if negative. */
734 {
735 size_t i;
736 const unsigned char* p = pendbyte;
737 const int pincr = -incr; /* search MSB to LSB */
738 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 for (i = 0; i < n; ++i, p += pincr) {
741 if (*p != insignficant)
742 break;
743 }
744 numsignificantbytes = n - i;
745 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
746 actually has 2 significant bytes. OTOH, 0xff0001 ==
747 -0x00ffff, so we wouldn't *need* to bump it there; but we
748 do for 0xffff = -0x0001. To be safe without bothering to
749 check every case, bump it regardless. */
750 if (is_signed && numsignificantbytes < n)
751 ++numsignificantbytes;
752 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 /* How many Python long digits do we need? We have
755 8*numsignificantbytes bits, and each Python long digit has
756 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
757 /* catch overflow before it happens */
758 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
759 PyErr_SetString(PyExc_OverflowError,
760 "byte array too long to convert to int");
761 return NULL;
762 }
763 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
764 v = _PyLong_New(ndigits);
765 if (v == NULL)
766 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 /* Copy the bits over. The tricky parts are computing 2's-comp on
769 the fly for signed numbers, and dealing with the mismatch between
770 8-bit bytes and (probably) 15-bit Python digits.*/
771 {
772 size_t i;
773 twodigits carry = 1; /* for 2's-comp calculation */
774 twodigits accum = 0; /* sliding register */
775 unsigned int accumbits = 0; /* number of bits in accum */
776 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
779 twodigits thisbyte = *p;
780 /* Compute correction for 2's comp, if needed. */
781 if (is_signed) {
782 thisbyte = (0xff ^ thisbyte) + carry;
783 carry = thisbyte >> 8;
784 thisbyte &= 0xff;
785 }
786 /* Because we're going LSB to MSB, thisbyte is
787 more significant than what's already in accum,
788 so needs to be prepended to accum. */
789 accum |= (twodigits)thisbyte << accumbits;
790 accumbits += 8;
791 if (accumbits >= PyLong_SHIFT) {
792 /* There's enough to fill a Python digit. */
793 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000794 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 ++idigit;
796 accum >>= PyLong_SHIFT;
797 accumbits -= PyLong_SHIFT;
798 assert(accumbits < PyLong_SHIFT);
799 }
800 }
801 assert(accumbits < PyLong_SHIFT);
802 if (accumbits) {
803 assert(idigit < ndigits);
804 v->ob_digit[idigit] = (digit)accum;
805 ++idigit;
806 }
807 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 Py_SIZE(v) = is_signed ? -idigit : idigit;
810 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000811}
812
813int
814_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 unsigned char* bytes, size_t n,
816 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000819 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000821 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
823 digit carry; /* for computing 2's-comp */
824 size_t j; /* # bytes filled */
825 unsigned char* p; /* pointer to next byte in bytes */
826 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (Py_SIZE(v) < 0) {
831 ndigits = -(Py_SIZE(v));
832 if (!is_signed) {
833 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000834 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return -1;
836 }
837 do_twos_comp = 1;
838 }
839 else {
840 ndigits = Py_SIZE(v);
841 do_twos_comp = 0;
842 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (little_endian) {
845 p = bytes;
846 pincr = 1;
847 }
848 else {
849 p = bytes + n - 1;
850 pincr = -1;
851 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 /* Copy over all the Python digits.
854 It's crucial that every Python digit except for the MSD contribute
855 exactly PyLong_SHIFT bits to the total, so first assert that the long is
856 normalized. */
857 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
858 j = 0;
859 accum = 0;
860 accumbits = 0;
861 carry = do_twos_comp ? 1 : 0;
862 for (i = 0; i < ndigits; ++i) {
863 digit thisdigit = v->ob_digit[i];
864 if (do_twos_comp) {
865 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
866 carry = thisdigit >> PyLong_SHIFT;
867 thisdigit &= PyLong_MASK;
868 }
869 /* Because we're going LSB to MSB, thisdigit is more
870 significant than what's already in accum, so needs to be
871 prepended to accum. */
872 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 /* The most-significant digit may be (probably is) at least
875 partly empty. */
876 if (i == ndigits - 1) {
877 /* Count # of sign bits -- they needn't be stored,
878 * although for signed conversion we need later to
879 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000880 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 while (s != 0) {
882 s >>= 1;
883 accumbits++;
884 }
885 }
886 else
887 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 /* Store as many bytes as possible. */
890 while (accumbits >= 8) {
891 if (j >= n)
892 goto Overflow;
893 ++j;
894 *p = (unsigned char)(accum & 0xff);
895 p += pincr;
896 accumbits -= 8;
897 accum >>= 8;
898 }
899 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 /* Store the straggler (if any). */
902 assert(accumbits < 8);
903 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
904 if (accumbits > 0) {
905 if (j >= n)
906 goto Overflow;
907 ++j;
908 if (do_twos_comp) {
909 /* Fill leading bits of the byte with sign bits
910 (appropriately pretending that the long had an
911 infinite supply of sign bits). */
912 accum |= (~(twodigits)0) << accumbits;
913 }
914 *p = (unsigned char)(accum & 0xff);
915 p += pincr;
916 }
917 else if (j == n && n > 0 && is_signed) {
918 /* The main loop filled the byte array exactly, so the code
919 just above didn't get to ensure there's a sign bit, and the
920 loop below wouldn't add one either. Make sure a sign bit
921 exists. */
922 unsigned char msb = *(p - pincr);
923 int sign_bit_set = msb >= 0x80;
924 assert(accumbits == 0);
925 if (sign_bit_set == do_twos_comp)
926 return 0;
927 else
928 goto Overflow;
929 }
Tim Peters05607ad2001-06-13 21:01:27 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Fill remaining bytes with copies of the sign bit. */
932 {
933 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
934 for ( ; j < n; ++j, p += pincr)
935 *p = signbyte;
936 }
Tim Peters05607ad2001-06-13 21:01:27 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000939
Mark Dickinson22b20182010-05-10 21:27:53 +0000940 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
942 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000943
Tim Peters2a9b3672001-06-11 21:23:58 +0000944}
945
Mark Dickinson8d48b432011-10-23 20:47:14 +0100946/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000947
948PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000949PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000950{
Mark Dickinson91044792012-10-18 19:21:43 +0100951#if SIZEOF_VOID_P <= SIZEOF_LONG
Mark Dickinson91044792012-10-18 19:21:43 +0100952 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
953#else
954
Tim Peters70128a12001-06-16 08:48:40 +0000955#ifndef HAVE_LONG_LONG
956# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
957#endif
958#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000959# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000960#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100962#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000963
Guido van Rossum78694d91998-09-18 14:14:13 +0000964}
965
Mark Dickinson8d48b432011-10-23 20:47:14 +0100966/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000967
968void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000969PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000970{
Tim Peters70128a12001-06-16 08:48:40 +0000971#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
975 x = PyLong_AsLong(vv);
976 else
977 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000978#else
Tim Peters70128a12001-06-16 08:48:40 +0000979
980#ifndef HAVE_LONG_LONG
981# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
982#endif
983#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000984# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000985#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
989 x = PyLong_AsLongLong(vv);
990 else
991 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000992
993#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 if (x == -1 && PyErr_Occurred())
996 return NULL;
997 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000998}
999
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001000#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001001
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001002/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001003 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001004 */
1005
Mark Dickinson22b20182010-05-10 21:27:53 +00001006#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001007
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001008/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001009
1010PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001011PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 PyLongObject *v;
1014 unsigned PY_LONG_LONG abs_ival;
1015 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1016 int ndigits = 0;
1017 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 CHECK_SMALL_INT(ival);
1020 if (ival < 0) {
1021 /* avoid signed overflow on negation; see comments
1022 in PyLong_FromLong above. */
1023 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1024 negative = 1;
1025 }
1026 else {
1027 abs_ival = (unsigned PY_LONG_LONG)ival;
1028 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 /* Count the number of Python digits.
1031 We used to pick 5 ("big enough for anything"), but that's a
1032 waste of time and space given that 5*15 = 75 bits are rarely
1033 needed. */
1034 t = abs_ival;
1035 while (t) {
1036 ++ndigits;
1037 t >>= PyLong_SHIFT;
1038 }
1039 v = _PyLong_New(ndigits);
1040 if (v != NULL) {
1041 digit *p = v->ob_digit;
1042 Py_SIZE(v) = negative ? -ndigits : ndigits;
1043 t = abs_ival;
1044 while (t) {
1045 *p++ = (digit)(t & PyLong_MASK);
1046 t >>= PyLong_SHIFT;
1047 }
1048 }
1049 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001050}
1051
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001052/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001053
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001054PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001055PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 PyLongObject *v;
1058 unsigned PY_LONG_LONG t;
1059 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 if (ival < PyLong_BASE)
1062 return PyLong_FromLong((long)ival);
1063 /* Count the number of Python digits. */
1064 t = (unsigned PY_LONG_LONG)ival;
1065 while (t) {
1066 ++ndigits;
1067 t >>= PyLong_SHIFT;
1068 }
1069 v = _PyLong_New(ndigits);
1070 if (v != NULL) {
1071 digit *p = v->ob_digit;
1072 Py_SIZE(v) = ndigits;
1073 while (ival) {
1074 *p++ = (digit)(ival & PyLong_MASK);
1075 ival >>= PyLong_SHIFT;
1076 }
1077 }
1078 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001079}
1080
Martin v. Löwis18e16552006-02-15 17:27:45 +00001081/* Create a new long int object from a C Py_ssize_t. */
1082
1083PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001084PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 PyLongObject *v;
1087 size_t abs_ival;
1088 size_t t; /* unsigned so >> doesn't propagate sign bit */
1089 int ndigits = 0;
1090 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 CHECK_SMALL_INT(ival);
1093 if (ival < 0) {
1094 /* avoid signed overflow when ival = SIZE_T_MIN */
1095 abs_ival = (size_t)(-1-ival)+1;
1096 negative = 1;
1097 }
1098 else {
1099 abs_ival = (size_t)ival;
1100 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 /* Count the number of Python digits. */
1103 t = abs_ival;
1104 while (t) {
1105 ++ndigits;
1106 t >>= PyLong_SHIFT;
1107 }
1108 v = _PyLong_New(ndigits);
1109 if (v != NULL) {
1110 digit *p = v->ob_digit;
1111 Py_SIZE(v) = negative ? -ndigits : ndigits;
1112 t = abs_ival;
1113 while (t) {
1114 *p++ = (digit)(t & PyLong_MASK);
1115 t >>= PyLong_SHIFT;
1116 }
1117 }
1118 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001119}
1120
1121/* Create a new long int object from a C size_t. */
1122
1123PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001124PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 PyLongObject *v;
1127 size_t t;
1128 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (ival < PyLong_BASE)
1131 return PyLong_FromLong((long)ival);
1132 /* Count the number of Python digits. */
1133 t = ival;
1134 while (t) {
1135 ++ndigits;
1136 t >>= PyLong_SHIFT;
1137 }
1138 v = _PyLong_New(ndigits);
1139 if (v != NULL) {
1140 digit *p = v->ob_digit;
1141 Py_SIZE(v) = ndigits;
1142 while (ival) {
1143 *p++ = (digit)(ival & PyLong_MASK);
1144 ival >>= PyLong_SHIFT;
1145 }
1146 }
1147 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001148}
1149
Mark Dickinson8d48b432011-10-23 20:47:14 +01001150/* Get a C long long int from a long int object or any object that has an
1151 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001152
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001153PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001154PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 PyLongObject *v;
1157 PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (vv == NULL) {
1161 PyErr_BadInternalCall();
1162 return -1;
1163 }
1164 if (!PyLong_Check(vv)) {
1165 PyNumberMethods *nb;
1166 PyObject *io;
1167 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1168 nb->nb_int == NULL) {
1169 PyErr_SetString(PyExc_TypeError, "an integer is required");
1170 return -1;
1171 }
1172 io = (*nb->nb_int) (vv);
1173 if (io == NULL)
1174 return -1;
1175 if (PyLong_Check(io)) {
1176 bytes = PyLong_AsLongLong(io);
1177 Py_DECREF(io);
1178 return bytes;
1179 }
1180 Py_DECREF(io);
1181 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1182 return -1;
1183 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 v = (PyLongObject*)vv;
1186 switch(Py_SIZE(v)) {
1187 case -1: return -(sdigit)v->ob_digit[0];
1188 case 0: return 0;
1189 case 1: return v->ob_digit[0];
1190 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001191 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001192 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1195 if (res < 0)
1196 return (PY_LONG_LONG)-1;
1197 else
1198 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001199}
1200
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001201/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001202 Return -1 and set an error if overflow occurs. */
1203
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001204unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001205PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 PyLongObject *v;
1208 unsigned PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001210
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001211 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyErr_BadInternalCall();
1213 return (unsigned PY_LONG_LONG)-1;
1214 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001215 if (!PyLong_Check(vv)) {
1216 PyErr_SetString(PyExc_TypeError, "an integer is required");
1217 return (unsigned PY_LONG_LONG)-1;
1218 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 v = (PyLongObject*)vv;
1221 switch(Py_SIZE(v)) {
1222 case 0: return 0;
1223 case 1: return v->ob_digit[0];
1224 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001225
Mark Dickinson22b20182010-05-10 21:27:53 +00001226 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001227 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1230 if (res < 0)
1231 return (unsigned PY_LONG_LONG)res;
1232 else
1233 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001234}
Tim Petersd1a7da62001-06-13 00:35:57 +00001235
Thomas Hellera4ea6032003-04-17 18:55:45 +00001236/* Get a C unsigned long int from a long int object, ignoring the high bits.
1237 Returns -1 and sets an error condition if an error occurs. */
1238
Guido van Rossumddefaf32007-01-14 03:31:43 +00001239static unsigned PY_LONG_LONG
1240_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 register PyLongObject *v;
1243 unsigned PY_LONG_LONG x;
1244 Py_ssize_t i;
1245 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 if (vv == NULL || !PyLong_Check(vv)) {
1248 PyErr_BadInternalCall();
1249 return (unsigned long) -1;
1250 }
1251 v = (PyLongObject *)vv;
1252 switch(Py_SIZE(v)) {
1253 case 0: return 0;
1254 case 1: return v->ob_digit[0];
1255 }
1256 i = Py_SIZE(v);
1257 sign = 1;
1258 x = 0;
1259 if (i < 0) {
1260 sign = -1;
1261 i = -i;
1262 }
1263 while (--i >= 0) {
1264 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1265 }
1266 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001267}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001268
1269unsigned PY_LONG_LONG
1270PyLong_AsUnsignedLongLongMask(register PyObject *op)
1271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyNumberMethods *nb;
1273 PyLongObject *lo;
1274 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 if (op && PyLong_Check(op))
1277 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1280 nb->nb_int == NULL) {
1281 PyErr_SetString(PyExc_TypeError, "an integer is required");
1282 return (unsigned PY_LONG_LONG)-1;
1283 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 lo = (PyLongObject*) (*nb->nb_int) (op);
1286 if (lo == NULL)
1287 return (unsigned PY_LONG_LONG)-1;
1288 if (PyLong_Check(lo)) {
1289 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1290 Py_DECREF(lo);
1291 if (PyErr_Occurred())
1292 return (unsigned PY_LONG_LONG)-1;
1293 return val;
1294 }
1295 else
1296 {
1297 Py_DECREF(lo);
1298 PyErr_SetString(PyExc_TypeError,
1299 "nb_int should return int object");
1300 return (unsigned PY_LONG_LONG)-1;
1301 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001302}
Tim Petersd1a7da62001-06-13 00:35:57 +00001303
Mark Dickinson8d48b432011-10-23 20:47:14 +01001304/* Get a C long long int from a long int object or any object that has an
1305 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001306
Mark Dickinson8d48b432011-10-23 20:47:14 +01001307 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1308 the result. Otherwise *overflow is 0.
1309
1310 For other errors (e.g., TypeError), return -1 and set an error condition.
1311 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001312*/
1313
1314PY_LONG_LONG
1315PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 /* This version by Tim Peters */
1318 register PyLongObject *v;
1319 unsigned PY_LONG_LONG x, prev;
1320 PY_LONG_LONG res;
1321 Py_ssize_t i;
1322 int sign;
1323 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 *overflow = 0;
1326 if (vv == NULL) {
1327 PyErr_BadInternalCall();
1328 return -1;
1329 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 if (!PyLong_Check(vv)) {
1332 PyNumberMethods *nb;
1333 nb = vv->ob_type->tp_as_number;
1334 if (nb == NULL || nb->nb_int == NULL) {
1335 PyErr_SetString(PyExc_TypeError,
1336 "an integer is required");
1337 return -1;
1338 }
1339 vv = (*nb->nb_int) (vv);
1340 if (vv == NULL)
1341 return -1;
1342 do_decref = 1;
1343 if (!PyLong_Check(vv)) {
1344 Py_DECREF(vv);
1345 PyErr_SetString(PyExc_TypeError,
1346 "nb_int should return int object");
1347 return -1;
1348 }
1349 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 res = -1;
1352 v = (PyLongObject *)vv;
1353 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 switch (i) {
1356 case -1:
1357 res = -(sdigit)v->ob_digit[0];
1358 break;
1359 case 0:
1360 res = 0;
1361 break;
1362 case 1:
1363 res = v->ob_digit[0];
1364 break;
1365 default:
1366 sign = 1;
1367 x = 0;
1368 if (i < 0) {
1369 sign = -1;
1370 i = -(i);
1371 }
1372 while (--i >= 0) {
1373 prev = x;
1374 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1375 if ((x >> PyLong_SHIFT) != prev) {
1376 *overflow = sign;
1377 goto exit;
1378 }
1379 }
1380 /* Haven't lost any bits, but casting to long requires extra
1381 * care (see comment above).
1382 */
1383 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1384 res = (PY_LONG_LONG)x * sign;
1385 }
1386 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1387 res = PY_LLONG_MIN;
1388 }
1389 else {
1390 *overflow = sign;
1391 /* res is already set to -1 */
1392 }
1393 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001394 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 if (do_decref) {
1396 Py_DECREF(vv);
1397 }
1398 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001399}
1400
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001401#endif /* HAVE_LONG_LONG */
1402
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001403#define CHECK_BINOP(v,w) \
1404 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001405 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1406 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001407 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001408
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001409/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1410 2**k if d is nonzero, else 0. */
1411
1412static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1414 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001415};
1416
1417static int
1418bits_in_digit(digit d)
1419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 int d_bits = 0;
1421 while (d >= 32) {
1422 d_bits += 6;
1423 d >>= 6;
1424 }
1425 d_bits += (int)BitLengthTable[d];
1426 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001427}
1428
Tim Peters877a2122002-08-12 05:09:36 +00001429/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1430 * is modified in place, by adding y to it. Carries are propagated as far as
1431 * x[m-1], and the remaining carry (0 or 1) is returned.
1432 */
1433static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001434v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 Py_ssize_t i;
1437 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 assert(m >= n);
1440 for (i = 0; i < n; ++i) {
1441 carry += x[i] + y[i];
1442 x[i] = carry & PyLong_MASK;
1443 carry >>= PyLong_SHIFT;
1444 assert((carry & 1) == carry);
1445 }
1446 for (; carry && i < m; ++i) {
1447 carry += x[i];
1448 x[i] = carry & PyLong_MASK;
1449 carry >>= PyLong_SHIFT;
1450 assert((carry & 1) == carry);
1451 }
1452 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001453}
1454
1455/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1456 * is modified in place, by subtracting y from it. Borrows are propagated as
1457 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1458 */
1459static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001460v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 Py_ssize_t i;
1463 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 assert(m >= n);
1466 for (i = 0; i < n; ++i) {
1467 borrow = x[i] - y[i] - borrow;
1468 x[i] = borrow & PyLong_MASK;
1469 borrow >>= PyLong_SHIFT;
1470 borrow &= 1; /* keep only 1 sign bit */
1471 }
1472 for (; borrow && i < m; ++i) {
1473 borrow = x[i] - borrow;
1474 x[i] = borrow & PyLong_MASK;
1475 borrow >>= PyLong_SHIFT;
1476 borrow &= 1;
1477 }
1478 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001479}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001480
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001481/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1482 * result in z[0:m], and return the d bits shifted out of the top.
1483 */
1484static digit
1485v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 Py_ssize_t i;
1488 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 assert(0 <= d && d < PyLong_SHIFT);
1491 for (i=0; i < m; i++) {
1492 twodigits acc = (twodigits)a[i] << d | carry;
1493 z[i] = (digit)acc & PyLong_MASK;
1494 carry = (digit)(acc >> PyLong_SHIFT);
1495 }
1496 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001497}
1498
1499/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1500 * result in z[0:m], and return the d bits shifted out of the bottom.
1501 */
1502static digit
1503v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 Py_ssize_t i;
1506 digit carry = 0;
1507 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 assert(0 <= d && d < PyLong_SHIFT);
1510 for (i=m; i-- > 0;) {
1511 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1512 carry = (digit)acc & mask;
1513 z[i] = (digit)(acc >> d);
1514 }
1515 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001516}
1517
Tim Peters212e6142001-07-14 12:23:19 +00001518/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1519 in pout, and returning the remainder. pin and pout point at the LSD.
1520 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001521 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001522 immutable. */
1523
1524static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001525inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 assert(n > 0 && n <= PyLong_MASK);
1530 pin += size;
1531 pout += size;
1532 while (--size >= 0) {
1533 digit hi;
1534 rem = (rem << PyLong_SHIFT) | *--pin;
1535 *--pout = hi = (digit)(rem / n);
1536 rem -= (twodigits)hi * n;
1537 }
1538 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001539}
1540
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001541/* Divide a long integer by a digit, returning both the quotient
1542 (as function result) and the remainder (through *prem).
1543 The sign of a is ignored; n should not be zero. */
1544
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001545static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001546divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 const Py_ssize_t size = ABS(Py_SIZE(a));
1549 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 assert(n > 0 && n <= PyLong_MASK);
1552 z = _PyLong_New(size);
1553 if (z == NULL)
1554 return NULL;
1555 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1556 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001557}
1558
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001559/* Convert a long integer to a base 10 string. Returns a new non-shared
1560 string. (Return value is non-shared so that callers can modify the
1561 returned value if necessary.) */
1562
Victor Stinnerd3f08822012-05-29 12:57:52 +02001563static int
1564long_to_decimal_string_internal(PyObject *aa,
1565 PyObject **p_output,
1566 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 PyLongObject *scratch, *a;
1569 PyObject *str;
1570 Py_ssize_t size, strlen, size_a, i, j;
1571 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001573 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 a = (PyLongObject *)aa;
1576 if (a == NULL || !PyLong_Check(a)) {
1577 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001578 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 }
1580 size_a = ABS(Py_SIZE(a));
1581 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 /* quick and dirty upper bound for the number of digits
1584 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 But log2(a) < size_a * PyLong_SHIFT, and
1589 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1590 > 3 * _PyLong_DECIMAL_SHIFT
1591 */
1592 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1593 PyErr_SetString(PyExc_OverflowError,
1594 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001595 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 }
1597 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1598 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1599 scratch = _PyLong_New(size);
1600 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001601 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 /* convert array of base _PyLong_BASE digits in pin to an array of
1604 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1605 Volume 2 (3rd edn), section 4.4, Method 1b). */
1606 pin = a->ob_digit;
1607 pout = scratch->ob_digit;
1608 size = 0;
1609 for (i = size_a; --i >= 0; ) {
1610 digit hi = pin[i];
1611 for (j = 0; j < size; j++) {
1612 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1613 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1614 pout[j] = (digit)(z - (twodigits)hi *
1615 _PyLong_DECIMAL_BASE);
1616 }
1617 while (hi) {
1618 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1619 hi /= _PyLong_DECIMAL_BASE;
1620 }
1621 /* check for keyboard interrupt */
1622 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001623 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001624 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001625 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 }
1627 /* pout should have at least one digit, so that the case when a = 0
1628 works correctly */
1629 if (size == 0)
1630 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 /* calculate exact length of output string, and allocate */
1633 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1634 tenpow = 10;
1635 rem = pout[size-1];
1636 while (rem >= tenpow) {
1637 tenpow *= 10;
1638 strlen++;
1639 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001640 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001641 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1642 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001643 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001644 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001645 kind = writer->kind;
1646 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001648 else {
1649 str = PyUnicode_New(strlen, '9');
1650 if (str == NULL) {
1651 Py_DECREF(scratch);
1652 return -1;
1653 }
1654 kind = PyUnicode_KIND(str);
1655 }
1656
1657#define WRITE_DIGITS(TYPE) \
1658 do { \
1659 if (writer) \
1660 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1661 else \
1662 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1663 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001664 /* pout[0] through pout[size-2] contribute exactly \
1665 _PyLong_DECIMAL_SHIFT digits each */ \
1666 for (i=0; i < size - 1; i++) { \
1667 rem = pout[i]; \
1668 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1669 *--p = '0' + rem % 10; \
1670 rem /= 10; \
1671 } \
1672 } \
1673 /* pout[size-1]: always produce at least one decimal digit */ \
1674 rem = pout[i]; \
1675 do { \
1676 *--p = '0' + rem % 10; \
1677 rem /= 10; \
1678 } while (rem != 0); \
1679 \
1680 /* and sign */ \
1681 if (negative) \
1682 *--p = '-'; \
1683 \
1684 /* check we've counted correctly */ \
1685 if (writer) \
1686 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1687 else \
1688 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1689 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001692 if (kind == PyUnicode_1BYTE_KIND) {
1693 Py_UCS1 *p;
1694 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001696 else if (kind == PyUnicode_2BYTE_KIND) {
1697 Py_UCS2 *p;
1698 WRITE_DIGITS(Py_UCS2);
1699 }
1700 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001701 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001702 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001703 WRITE_DIGITS(Py_UCS4);
1704 }
1705#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001708 if (writer) {
1709 writer->pos += strlen;
1710 }
1711 else {
1712 assert(_PyUnicode_CheckConsistency(str, 1));
1713 *p_output = (PyObject *)str;
1714 }
1715 return 0;
1716}
1717
1718static PyObject *
1719long_to_decimal_string(PyObject *aa)
1720{
1721 PyObject *v;
1722 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1723 return NULL;
1724 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001725}
1726
Mark Dickinsoncd068122009-09-18 14:53:08 +00001727/* Convert a long int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001728 which should be one of 2, 8 or 16. Return a string object.
1729 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1730 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001731
Victor Stinnerd3f08822012-05-29 12:57:52 +02001732static int
1733long_format_binary(PyObject *aa, int base, int alternate,
1734 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001737 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001738 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001740 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001741 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001743
Victor Stinnerd3f08822012-05-29 12:57:52 +02001744 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (a == NULL || !PyLong_Check(a)) {
1746 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001747 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 }
1749 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001750 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 /* Compute a rough upper bound for the length of the string */
1753 switch (base) {
1754 case 16:
1755 bits = 4;
1756 break;
1757 case 8:
1758 bits = 3;
1759 break;
1760 case 2:
1761 bits = 1;
1762 break;
1763 default:
1764 assert(0); /* shouldn't ever get here */
1765 bits = 0; /* to silence gcc warning */
1766 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001767
Mark Dickinsone2846542012-04-20 21:21:24 +01001768 /* Compute exact length 'sz' of output string. */
1769 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001770 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001771 }
1772 else {
1773 Py_ssize_t size_a_in_bits;
1774 /* Ensure overflow doesn't occur during computation of sz. */
1775 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1776 PyErr_SetString(PyExc_OverflowError,
1777 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001778 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001779 }
1780 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1781 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001782 /* Allow 1 character for a '-' sign. */
1783 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1784 }
1785 if (alternate) {
1786 /* 2 characters for prefix */
1787 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001788 }
1789
Victor Stinnerd3f08822012-05-29 12:57:52 +02001790 if (writer) {
1791 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1792 return -1;
1793 kind = writer->kind;
1794 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 }
1796 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001797 v = PyUnicode_New(sz, 'x');
1798 if (v == NULL)
1799 return -1;
1800 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001802
Victor Stinnerd3f08822012-05-29 12:57:52 +02001803#define WRITE_DIGITS(TYPE) \
1804 do { \
1805 if (writer) \
1806 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1807 else \
1808 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1809 \
1810 if (size_a == 0) { \
1811 *--p = '0'; \
1812 } \
1813 else { \
1814 /* JRH: special case for power-of-2 bases */ \
1815 twodigits accum = 0; \
1816 int accumbits = 0; /* # of bits in accum */ \
1817 Py_ssize_t i; \
1818 for (i = 0; i < size_a; ++i) { \
1819 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1820 accumbits += PyLong_SHIFT; \
1821 assert(accumbits >= bits); \
1822 do { \
1823 char cdigit; \
1824 cdigit = (char)(accum & (base - 1)); \
1825 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1826 *--p = cdigit; \
1827 accumbits -= bits; \
1828 accum >>= bits; \
1829 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1830 } \
1831 } \
1832 \
1833 if (alternate) { \
1834 if (base == 16) \
1835 *--p = 'x'; \
1836 else if (base == 8) \
1837 *--p = 'o'; \
1838 else /* (base == 2) */ \
1839 *--p = 'b'; \
1840 *--p = '0'; \
1841 } \
1842 if (negative) \
1843 *--p = '-'; \
1844 if (writer) \
1845 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1846 else \
1847 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1848 } while (0)
1849
1850 if (kind == PyUnicode_1BYTE_KIND) {
1851 Py_UCS1 *p;
1852 WRITE_DIGITS(Py_UCS1);
1853 }
1854 else if (kind == PyUnicode_2BYTE_KIND) {
1855 Py_UCS2 *p;
1856 WRITE_DIGITS(Py_UCS2);
1857 }
1858 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001859 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001860 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001861 WRITE_DIGITS(Py_UCS4);
1862 }
1863#undef WRITE_DIGITS
1864
1865 if (writer) {
1866 writer->pos += sz;
1867 }
1868 else {
1869 assert(_PyUnicode_CheckConsistency(v, 1));
1870 *p_output = v;
1871 }
1872 return 0;
1873}
1874
1875PyObject *
1876_PyLong_Format(PyObject *obj, int base)
1877{
1878 PyObject *str;
1879 int err;
1880 if (base == 10)
1881 err = long_to_decimal_string_internal(obj, &str, NULL);
1882 else
1883 err = long_format_binary(obj, base, 1, &str, NULL);
1884 if (err == -1)
1885 return NULL;
1886 return str;
1887}
1888
1889int
1890_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1891 PyObject *obj,
1892 int base, int alternate)
1893{
1894 if (base == 10)
1895 return long_to_decimal_string_internal(obj, NULL, writer);
1896 else
1897 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001898}
1899
Thomas Wouters477c8d52006-05-27 19:21:47 +00001900/* Table of digit values for 8-bit string -> integer conversion.
1901 * '0' maps to 0, ..., '9' maps to 9.
1902 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1903 * All other indices map to 37.
1904 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001905 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001906 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001907unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1909 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1910 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1911 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1912 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1913 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1914 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1915 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1916 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1917 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1918 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1919 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1920 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1921 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1922 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1923 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001924};
1925
1926/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001927 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1928 * non-digit (which may be *str!). A normalized long is returned.
1929 * The point to this routine is that it takes time linear in the number of
1930 * string characters.
1931 */
1932static PyLongObject *
1933long_from_binary_base(char **str, int base)
1934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 char *p = *str;
1936 char *start = p;
1937 int bits_per_char;
1938 Py_ssize_t n;
1939 PyLongObject *z;
1940 twodigits accum;
1941 int bits_in_accum;
1942 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1945 n = base;
1946 for (bits_per_char = -1; n; ++bits_per_char)
1947 n >>= 1;
1948 /* n <- total # of bits needed, while setting p to end-of-string */
1949 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1950 ++p;
1951 *str = p;
1952 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1953 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1954 if (n / bits_per_char < p - start) {
1955 PyErr_SetString(PyExc_ValueError,
1956 "int string too large to convert");
1957 return NULL;
1958 }
1959 n = n / PyLong_SHIFT;
1960 z = _PyLong_New(n);
1961 if (z == NULL)
1962 return NULL;
1963 /* Read string from right, and fill in long from left; i.e.,
1964 * from least to most significant in both.
1965 */
1966 accum = 0;
1967 bits_in_accum = 0;
1968 pdigit = z->ob_digit;
1969 while (--p >= start) {
1970 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1971 assert(k >= 0 && k < base);
1972 accum |= (twodigits)k << bits_in_accum;
1973 bits_in_accum += bits_per_char;
1974 if (bits_in_accum >= PyLong_SHIFT) {
1975 *pdigit++ = (digit)(accum & PyLong_MASK);
1976 assert(pdigit - z->ob_digit <= n);
1977 accum >>= PyLong_SHIFT;
1978 bits_in_accum -= PyLong_SHIFT;
1979 assert(bits_in_accum < PyLong_SHIFT);
1980 }
1981 }
1982 if (bits_in_accum) {
1983 assert(bits_in_accum <= PyLong_SHIFT);
1984 *pdigit++ = (digit)accum;
1985 assert(pdigit - z->ob_digit <= n);
1986 }
1987 while (pdigit - z->ob_digit < n)
1988 *pdigit++ = 0;
1989 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001990}
1991
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001992PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001993PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 int sign = 1, error_if_nonzero = 0;
1996 char *start, *orig_str = str;
1997 PyLongObject *z = NULL;
1998 PyObject *strobj;
1999 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 if ((base != 0 && base < 2) || base > 36) {
2002 PyErr_SetString(PyExc_ValueError,
2003 "int() arg 2 must be >= 2 and <= 36");
2004 return NULL;
2005 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002006 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 str++;
2008 if (*str == '+')
2009 ++str;
2010 else if (*str == '-') {
2011 ++str;
2012 sign = -1;
2013 }
2014 if (base == 0) {
2015 if (str[0] != '0')
2016 base = 10;
2017 else if (str[1] == 'x' || str[1] == 'X')
2018 base = 16;
2019 else if (str[1] == 'o' || str[1] == 'O')
2020 base = 8;
2021 else if (str[1] == 'b' || str[1] == 'B')
2022 base = 2;
2023 else {
2024 /* "old" (C-style) octal literal, now invalid.
2025 it might still be zero though */
2026 error_if_nonzero = 1;
2027 base = 10;
2028 }
2029 }
2030 if (str[0] == '0' &&
2031 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2032 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2033 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2034 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 start = str;
2037 if ((base & (base - 1)) == 0)
2038 z = long_from_binary_base(&str, base);
2039 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002040/***
2041Binary bases can be converted in time linear in the number of digits, because
2042Python's representation base is binary. Other bases (including decimal!) use
2043the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002044
Thomas Wouters477c8d52006-05-27 19:21:47 +00002045First some math: the largest integer that can be expressed in N base-B digits
2046is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2047case number of Python digits needed to hold it is the smallest integer n s.t.
2048
2049 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2050 BASE**n >= B**N [taking logs to base BASE]
2051 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2052
2053The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2054this quickly. A Python long with that much space is reserved near the start,
2055and the result is computed into it.
2056
2057The input string is actually treated as being in base base**i (i.e., i digits
2058are processed at a time), where two more static arrays hold:
2059
2060 convwidth_base[base] = the largest integer i such that base**i <= BASE
2061 convmultmax_base[base] = base ** convwidth_base[base]
2062
2063The first of these is the largest i such that i consecutive input digits
2064must fit in a single Python digit. The second is effectively the input
2065base we're really using.
2066
2067Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2068convmultmax_base[base], the result is "simply"
2069
2070 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2071
2072where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002073
2074Error analysis: as above, the number of Python digits `n` needed is worst-
2075case
2076
2077 n >= N * log(B)/log(BASE)
2078
2079where `N` is the number of input digits in base `B`. This is computed via
2080
2081 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2082
2083below. Two numeric concerns are how much space this can waste, and whether
2084the computed result can be too small. To be concrete, assume BASE = 2**15,
2085which is the default (and it's unlikely anyone changes that).
2086
2087Waste isn't a problem: provided the first input digit isn't 0, the difference
2088between the worst-case input with N digits and the smallest input with N
2089digits is about a factor of B, but B is small compared to BASE so at most
2090one allocated Python digit can remain unused on that count. If
2091N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2092and adding 1 returns a result 1 larger than necessary. However, that can't
2093happen: whenever B is a power of 2, long_from_binary_base() is called
2094instead, and it's impossible for B**i to be an integer power of 2**15 when
2095B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2096an exact integer when B is not a power of 2, since B**i has a prime factor
2097other than 2 in that case, but (2**15)**j's only prime factor is 2).
2098
2099The computed result can be too small if the true value of N*log(B)/log(BASE)
2100is a little bit larger than an exact integer, but due to roundoff errors (in
2101computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2102yields a numeric result a little less than that integer. Unfortunately, "how
2103close can a transcendental function get to an integer over some range?"
2104questions are generally theoretically intractable. Computer analysis via
2105continued fractions is practical: expand log(B)/log(BASE) via continued
2106fractions, giving a sequence i/j of "the best" rational approximations. Then
2107j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2108we can get very close to being in trouble, but very rarely. For example,
210976573 is a denominator in one of the continued-fraction approximations to
2110log(10)/log(2**15), and indeed:
2111
2112 >>> log(10)/log(2**15)*76573
2113 16958.000000654003
2114
2115is very close to an integer. If we were working with IEEE single-precision,
2116rounding errors could kill us. Finding worst cases in IEEE double-precision
2117requires better-than-double-precision log() functions, and Tim didn't bother.
2118Instead the code checks to see whether the allocated space is enough as each
2119new Python digit is added, and copies the whole thing to a larger long if not.
2120This should happen extremely rarely, and in fact I don't have a test case
2121that triggers it(!). Instead the code was tested by artificially allocating
2122just 1 digit at the start, so that the copying code was exercised for every
2123digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002124***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 register twodigits c; /* current input character */
2126 Py_ssize_t size_z;
2127 int i;
2128 int convwidth;
2129 twodigits convmultmax, convmult;
2130 digit *pz, *pzstop;
2131 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 static double log_base_BASE[37] = {0.0e0,};
2134 static int convwidth_base[37] = {0,};
2135 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (log_base_BASE[base] == 0.0) {
2138 twodigits convmax = base;
2139 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002140
Mark Dickinson22b20182010-05-10 21:27:53 +00002141 log_base_BASE[base] = (log((double)base) /
2142 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 for (;;) {
2144 twodigits next = convmax * base;
2145 if (next > PyLong_BASE)
2146 break;
2147 convmax = next;
2148 ++i;
2149 }
2150 convmultmax_base[base] = convmax;
2151 assert(i > 0);
2152 convwidth_base[base] = i;
2153 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 /* Find length of the string of numeric characters. */
2156 scan = str;
2157 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2158 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* Create a long object that can contain the largest possible
2161 * integer with this base and length. Note that there's no
2162 * need to initialize z->ob_digit -- no slot is read up before
2163 * being stored into.
2164 */
2165 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2166 /* Uncomment next line to test exceedingly rare copy code */
2167 /* size_z = 1; */
2168 assert(size_z > 0);
2169 z = _PyLong_New(size_z);
2170 if (z == NULL)
2171 return NULL;
2172 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 /* `convwidth` consecutive input digits are treated as a single
2175 * digit in base `convmultmax`.
2176 */
2177 convwidth = convwidth_base[base];
2178 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 /* Work ;-) */
2181 while (str < scan) {
2182 /* grab up to convwidth digits from the input string */
2183 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2184 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2185 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002186 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 assert(c < PyLong_BASE);
2188 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 convmult = convmultmax;
2191 /* Calculate the shift only if we couldn't get
2192 * convwidth digits.
2193 */
2194 if (i != convwidth) {
2195 convmult = base;
2196 for ( ; i > 1; --i)
2197 convmult *= base;
2198 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 /* Multiply z by convmult, and add c. */
2201 pz = z->ob_digit;
2202 pzstop = pz + Py_SIZE(z);
2203 for (; pz < pzstop; ++pz) {
2204 c += (twodigits)*pz * convmult;
2205 *pz = (digit)(c & PyLong_MASK);
2206 c >>= PyLong_SHIFT;
2207 }
2208 /* carry off the current end? */
2209 if (c) {
2210 assert(c < PyLong_BASE);
2211 if (Py_SIZE(z) < size_z) {
2212 *pz = (digit)c;
2213 ++Py_SIZE(z);
2214 }
2215 else {
2216 PyLongObject *tmp;
2217 /* Extremely rare. Get more space. */
2218 assert(Py_SIZE(z) == size_z);
2219 tmp = _PyLong_New(size_z + 1);
2220 if (tmp == NULL) {
2221 Py_DECREF(z);
2222 return NULL;
2223 }
2224 memcpy(tmp->ob_digit,
2225 z->ob_digit,
2226 sizeof(digit) * size_z);
2227 Py_DECREF(z);
2228 z = tmp;
2229 z->ob_digit[size_z] = (digit)c;
2230 ++size_z;
2231 }
2232 }
2233 }
2234 }
2235 if (z == NULL)
2236 return NULL;
2237 if (error_if_nonzero) {
2238 /* reset the base to 0, else the exception message
2239 doesn't make too much sense */
2240 base = 0;
2241 if (Py_SIZE(z) != 0)
2242 goto onError;
2243 /* there might still be other problems, therefore base
2244 remains zero here for the same reason */
2245 }
2246 if (str == start)
2247 goto onError;
2248 if (sign < 0)
2249 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002250 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 str++;
2252 if (*str != '\0')
2253 goto onError;
2254 if (pend)
2255 *pend = str;
2256 long_normalize(z);
2257 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002258
Mark Dickinson22b20182010-05-10 21:27:53 +00002259 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 Py_XDECREF(z);
2261 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2262 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2263 if (strobj == NULL)
2264 return NULL;
2265 PyErr_Format(PyExc_ValueError,
2266 "invalid literal for int() with base %d: %R",
2267 base, strobj);
2268 Py_DECREF(strobj);
2269 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002270}
2271
2272PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002273PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002274{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002275 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2276 if (unicode == NULL)
2277 return NULL;
2278 v = PyLong_FromUnicodeObject(unicode, base);
2279 Py_DECREF(unicode);
2280 return v;
2281}
2282
2283PyObject *
2284PyLong_FromUnicodeObject(PyObject *u, int base)
2285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002287 PyObject *asciidig;
2288 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002289 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002290
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002291 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002292 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002294 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002295 if (buffer == NULL) {
2296 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 return NULL;
2298 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002299 result = PyLong_FromString(buffer, &end, base);
2300 if (result != NULL && end != buffer + buflen) {
2301 PyErr_SetString(PyExc_ValueError,
2302 "null byte in argument for int()");
2303 Py_DECREF(result);
2304 result = NULL;
2305 }
2306 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002308}
2309
Tim Peters9f688bf2000-07-07 15:53:28 +00002310/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002311static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002313static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002314
2315/* Long division with remainder, top-level routine */
2316
Guido van Rossume32e0141992-01-19 16:31:05 +00002317static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002318long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2322 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 if (size_b == 0) {
2325 PyErr_SetString(PyExc_ZeroDivisionError,
2326 "integer division or modulo by zero");
2327 return -1;
2328 }
2329 if (size_a < size_b ||
2330 (size_a == size_b &&
2331 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2332 /* |a| < |b|. */
2333 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2334 if (*pdiv == NULL)
2335 return -1;
2336 Py_INCREF(a);
2337 *prem = (PyLongObject *) a;
2338 return 0;
2339 }
2340 if (size_b == 1) {
2341 digit rem = 0;
2342 z = divrem1(a, b->ob_digit[0], &rem);
2343 if (z == NULL)
2344 return -1;
2345 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2346 if (*prem == NULL) {
2347 Py_DECREF(z);
2348 return -1;
2349 }
2350 }
2351 else {
2352 z = x_divrem(a, b, prem);
2353 if (z == NULL)
2354 return -1;
2355 }
2356 /* Set the signs.
2357 The quotient z has the sign of a*b;
2358 the remainder r has the sign of a,
2359 so a = b*z + r. */
2360 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2361 NEGATE(z);
2362 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2363 NEGATE(*prem);
2364 *pdiv = maybe_small_long(z);
2365 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002366}
2367
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002368/* Unsigned long division with remainder -- the algorithm. The arguments v1
2369 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002370
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002371static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002372x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 PyLongObject *v, *w, *a;
2375 Py_ssize_t i, k, size_v, size_w;
2376 int d;
2377 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2378 twodigits vv;
2379 sdigit zhi;
2380 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2383 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2384 handle the special case when the initial estimate q for a quotient
2385 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2386 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* allocate space; w will also be used to hold the final remainder */
2389 size_v = ABS(Py_SIZE(v1));
2390 size_w = ABS(Py_SIZE(w1));
2391 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2392 v = _PyLong_New(size_v+1);
2393 if (v == NULL) {
2394 *prem = NULL;
2395 return NULL;
2396 }
2397 w = _PyLong_New(size_w);
2398 if (w == NULL) {
2399 Py_DECREF(v);
2400 *prem = NULL;
2401 return NULL;
2402 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2405 shift v1 left by the same amount. Results go into w and v. */
2406 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2407 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2408 assert(carry == 0);
2409 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2410 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2411 v->ob_digit[size_v] = carry;
2412 size_v++;
2413 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2416 at most (and usually exactly) k = size_v - size_w digits. */
2417 k = size_v - size_w;
2418 assert(k >= 0);
2419 a = _PyLong_New(k);
2420 if (a == NULL) {
2421 Py_DECREF(w);
2422 Py_DECREF(v);
2423 *prem = NULL;
2424 return NULL;
2425 }
2426 v0 = v->ob_digit;
2427 w0 = w->ob_digit;
2428 wm1 = w0[size_w-1];
2429 wm2 = w0[size_w-2];
2430 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2431 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2432 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002435 Py_DECREF(a);
2436 Py_DECREF(w);
2437 Py_DECREF(v);
2438 *prem = NULL;
2439 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002440 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 /* estimate quotient digit q; may overestimate by 1 (rare) */
2443 vtop = vk[size_w];
2444 assert(vtop <= wm1);
2445 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2446 q = (digit)(vv / wm1);
2447 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2448 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2449 | vk[size_w-2])) {
2450 --q;
2451 r += wm1;
2452 if (r >= PyLong_BASE)
2453 break;
2454 }
2455 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2458 zhi = 0;
2459 for (i = 0; i < size_w; ++i) {
2460 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2461 -PyLong_BASE * q <= z < PyLong_BASE */
2462 z = (sdigit)vk[i] + zhi -
2463 (stwodigits)q * (stwodigits)w0[i];
2464 vk[i] = (digit)z & PyLong_MASK;
2465 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002466 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 /* add w back if q was too large (this branch taken rarely) */
2470 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2471 if ((sdigit)vtop + zhi < 0) {
2472 carry = 0;
2473 for (i = 0; i < size_w; ++i) {
2474 carry += vk[i] + w0[i];
2475 vk[i] = carry & PyLong_MASK;
2476 carry >>= PyLong_SHIFT;
2477 }
2478 --q;
2479 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 /* store quotient digit */
2482 assert(q < PyLong_BASE);
2483 *--ak = q;
2484 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 /* unshift remainder; we reuse w to store the result */
2487 carry = v_rshift(w0, v0, size_w, d);
2488 assert(carry==0);
2489 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 *prem = long_normalize(w);
2492 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002493}
2494
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002495/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2496 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2497 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2498 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2499 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2500 -1.0. */
2501
2502/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2503#if DBL_MANT_DIG == 53
2504#define EXP2_DBL_MANT_DIG 9007199254740992.0
2505#else
2506#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2507#endif
2508
2509double
2510_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2513 /* See below for why x_digits is always large enough. */
2514 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2515 double dx;
2516 /* Correction term for round-half-to-even rounding. For a digit x,
2517 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2518 multiple of 4, rounding ties to a multiple of 8. */
2519 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 a_size = ABS(Py_SIZE(a));
2522 if (a_size == 0) {
2523 /* Special case for 0: significand 0.0, exponent 0. */
2524 *e = 0;
2525 return 0.0;
2526 }
2527 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2528 /* The following is an overflow-free version of the check
2529 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2530 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2531 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2532 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002533 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2537 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 Number of digits needed for result: write // for floor division.
2540 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2549 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2552 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2553 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 in both cases.
2560 */
2561 if (a_bits <= DBL_MANT_DIG + 2) {
2562 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2563 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2564 x_size = 0;
2565 while (x_size < shift_digits)
2566 x_digits[x_size++] = 0;
2567 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2568 (int)shift_bits);
2569 x_size += a_size;
2570 x_digits[x_size++] = rem;
2571 }
2572 else {
2573 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2574 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2575 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2576 a_size - shift_digits, (int)shift_bits);
2577 x_size = a_size - shift_digits;
2578 /* For correct rounding below, we need the least significant
2579 bit of x to be 'sticky' for this shift: if any of the bits
2580 shifted out was nonzero, we set the least significant bit
2581 of x. */
2582 if (rem)
2583 x_digits[0] |= 1;
2584 else
2585 while (shift_digits > 0)
2586 if (a->ob_digit[--shift_digits]) {
2587 x_digits[0] |= 1;
2588 break;
2589 }
2590 }
Victor Stinner63941882011-09-29 00:42:28 +02002591 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 /* Round, and convert to double. */
2594 x_digits[0] += half_even_correction[x_digits[0] & 7];
2595 dx = x_digits[--x_size];
2596 while (x_size > 0)
2597 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 /* Rescale; make correction if result is 1.0. */
2600 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2601 if (dx == 1.0) {
2602 if (a_bits == PY_SSIZE_T_MAX)
2603 goto overflow;
2604 dx = 0.5;
2605 a_bits += 1;
2606 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 *e = a_bits;
2609 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002610
2611 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 /* exponent > PY_SSIZE_T_MAX */
2613 PyErr_SetString(PyExc_OverflowError,
2614 "huge integer: number of bits overflows a Py_ssize_t");
2615 *e = 0;
2616 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002617}
2618
2619/* Get a C double from a long int object. Rounds to the nearest double,
2620 using the round-half-to-even rule in the case of a tie. */
2621
2622double
2623PyLong_AsDouble(PyObject *v)
2624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 Py_ssize_t exponent;
2626 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002627
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002628 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 PyErr_BadInternalCall();
2630 return -1.0;
2631 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002632 if (!PyLong_Check(v)) {
2633 PyErr_SetString(PyExc_TypeError, "an integer is required");
2634 return -1.0;
2635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2637 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2638 PyErr_SetString(PyExc_OverflowError,
2639 "long int too large to convert to float");
2640 return -1.0;
2641 }
2642 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002643}
2644
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002645/* Methods */
2646
2647static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002648long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002651}
2652
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002653static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002654long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 if (Py_SIZE(a) != Py_SIZE(b)) {
2659 sign = Py_SIZE(a) - Py_SIZE(b);
2660 }
2661 else {
2662 Py_ssize_t i = ABS(Py_SIZE(a));
2663 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2664 ;
2665 if (i < 0)
2666 sign = 0;
2667 else {
2668 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2669 if (Py_SIZE(a) < 0)
2670 sign = -sign;
2671 }
2672 }
2673 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002674}
2675
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002676#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002678
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002679static PyObject *
2680long_richcompare(PyObject *self, PyObject *other, int op)
2681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 int result;
2683 PyObject *v;
2684 CHECK_BINOP(self, other);
2685 if (self == other)
2686 result = 0;
2687 else
2688 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2689 /* Convert the return value to a Boolean */
2690 switch (op) {
2691 case Py_EQ:
2692 v = TEST_COND(result == 0);
2693 break;
2694 case Py_NE:
2695 v = TEST_COND(result != 0);
2696 break;
2697 case Py_LE:
2698 v = TEST_COND(result <= 0);
2699 break;
2700 case Py_GE:
2701 v = TEST_COND(result >= 0);
2702 break;
2703 case Py_LT:
2704 v = TEST_COND(result == -1);
2705 break;
2706 case Py_GT:
2707 v = TEST_COND(result == 1);
2708 break;
2709 default:
2710 PyErr_BadArgument();
2711 return NULL;
2712 }
2713 Py_INCREF(v);
2714 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002715}
2716
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002717static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002718long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002719{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002720 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 Py_ssize_t i;
2722 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 i = Py_SIZE(v);
2725 switch(i) {
2726 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2727 case 0: return 0;
2728 case 1: return v->ob_digit[0];
2729 }
2730 sign = 1;
2731 x = 0;
2732 if (i < 0) {
2733 sign = -1;
2734 i = -(i);
2735 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002737 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2738 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2739 _PyHASH_MODULUS.
2740
2741 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2742 amounts to a rotation of the bits of x. To see this, write
2743
2744 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2745
2746 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2747 PyLong_SHIFT bits of x (those that are shifted out of the
2748 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2749 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2750 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2751 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2752 congruent to y modulo _PyHASH_MODULUS. So
2753
2754 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2755
2756 The right-hand side is just the result of rotating the
2757 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2758 not all _PyHASH_BITS bits of x are 1s, the same is true
2759 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2760 the reduction of x*2**PyLong_SHIFT modulo
2761 _PyHASH_MODULUS. */
2762 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2763 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002765 if (x >= _PyHASH_MODULUS)
2766 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 }
2768 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002769 if (x == (Py_uhash_t)-1)
2770 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002771 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002772}
2773
2774
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002775/* Add the absolute values of two long integers. */
2776
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002777static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002778x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2781 PyLongObject *z;
2782 Py_ssize_t i;
2783 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 /* Ensure a is the larger of the two: */
2786 if (size_a < size_b) {
2787 { PyLongObject *temp = a; a = b; b = temp; }
2788 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002789 size_a = size_b;
2790 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 }
2792 z = _PyLong_New(size_a+1);
2793 if (z == NULL)
2794 return NULL;
2795 for (i = 0; i < size_b; ++i) {
2796 carry += a->ob_digit[i] + b->ob_digit[i];
2797 z->ob_digit[i] = carry & PyLong_MASK;
2798 carry >>= PyLong_SHIFT;
2799 }
2800 for (; i < size_a; ++i) {
2801 carry += a->ob_digit[i];
2802 z->ob_digit[i] = carry & PyLong_MASK;
2803 carry >>= PyLong_SHIFT;
2804 }
2805 z->ob_digit[i] = carry;
2806 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002807}
2808
2809/* Subtract the absolute values of two integers. */
2810
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002811static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002812x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2815 PyLongObject *z;
2816 Py_ssize_t i;
2817 int sign = 1;
2818 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 /* Ensure a is the larger of the two: */
2821 if (size_a < size_b) {
2822 sign = -1;
2823 { PyLongObject *temp = a; a = b; b = temp; }
2824 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002825 size_a = size_b;
2826 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 }
2828 else if (size_a == size_b) {
2829 /* Find highest digit where a and b differ: */
2830 i = size_a;
2831 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2832 ;
2833 if (i < 0)
2834 return (PyLongObject *)PyLong_FromLong(0);
2835 if (a->ob_digit[i] < b->ob_digit[i]) {
2836 sign = -1;
2837 { PyLongObject *temp = a; a = b; b = temp; }
2838 }
2839 size_a = size_b = i+1;
2840 }
2841 z = _PyLong_New(size_a);
2842 if (z == NULL)
2843 return NULL;
2844 for (i = 0; i < size_b; ++i) {
2845 /* The following assumes unsigned arithmetic
2846 works module 2**N for some N>PyLong_SHIFT. */
2847 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2848 z->ob_digit[i] = borrow & PyLong_MASK;
2849 borrow >>= PyLong_SHIFT;
2850 borrow &= 1; /* Keep only one sign bit */
2851 }
2852 for (; i < size_a; ++i) {
2853 borrow = a->ob_digit[i] - borrow;
2854 z->ob_digit[i] = borrow & PyLong_MASK;
2855 borrow >>= PyLong_SHIFT;
2856 borrow &= 1; /* Keep only one sign bit */
2857 }
2858 assert(borrow == 0);
2859 if (sign < 0)
2860 NEGATE(z);
2861 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002862}
2863
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002864static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002865long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2872 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2873 MEDIUM_VALUE(b));
2874 return result;
2875 }
2876 if (Py_SIZE(a) < 0) {
2877 if (Py_SIZE(b) < 0) {
2878 z = x_add(a, b);
2879 if (z != NULL && Py_SIZE(z) != 0)
2880 Py_SIZE(z) = -(Py_SIZE(z));
2881 }
2882 else
2883 z = x_sub(b, a);
2884 }
2885 else {
2886 if (Py_SIZE(b) < 0)
2887 z = x_sub(a, b);
2888 else
2889 z = x_add(a, b);
2890 }
2891 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002892}
2893
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002894static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002895long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2902 PyObject* r;
2903 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2904 return r;
2905 }
2906 if (Py_SIZE(a) < 0) {
2907 if (Py_SIZE(b) < 0)
2908 z = x_sub(a, b);
2909 else
2910 z = x_add(a, b);
2911 if (z != NULL && Py_SIZE(z) != 0)
2912 Py_SIZE(z) = -(Py_SIZE(z));
2913 }
2914 else {
2915 if (Py_SIZE(b) < 0)
2916 z = x_add(a, b);
2917 else
2918 z = x_sub(a, b);
2919 }
2920 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002921}
2922
Tim Peters5af4e6c2002-08-12 02:31:19 +00002923/* Grade school multiplication, ignoring the signs.
2924 * Returns the absolute value of the product, or NULL if error.
2925 */
2926static PyLongObject *
2927x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 PyLongObject *z;
2930 Py_ssize_t size_a = ABS(Py_SIZE(a));
2931 Py_ssize_t size_b = ABS(Py_SIZE(b));
2932 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 z = _PyLong_New(size_a + size_b);
2935 if (z == NULL)
2936 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2939 if (a == b) {
2940 /* Efficient squaring per HAC, Algorithm 14.16:
2941 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2942 * Gives slightly less than a 2x speedup when a == b,
2943 * via exploiting that each entry in the multiplication
2944 * pyramid appears twice (except for the size_a squares).
2945 */
2946 for (i = 0; i < size_a; ++i) {
2947 twodigits carry;
2948 twodigits f = a->ob_digit[i];
2949 digit *pz = z->ob_digit + (i << 1);
2950 digit *pa = a->ob_digit + i + 1;
2951 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002954 Py_DECREF(z);
2955 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002956 });
Tim Peters0973b992004-08-29 22:16:50 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 carry = *pz + f * f;
2959 *pz++ = (digit)(carry & PyLong_MASK);
2960 carry >>= PyLong_SHIFT;
2961 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 /* Now f is added in twice in each column of the
2964 * pyramid it appears. Same as adding f<<1 once.
2965 */
2966 f <<= 1;
2967 while (pa < paend) {
2968 carry += *pz + *pa++ * f;
2969 *pz++ = (digit)(carry & PyLong_MASK);
2970 carry >>= PyLong_SHIFT;
2971 assert(carry <= (PyLong_MASK << 1));
2972 }
2973 if (carry) {
2974 carry += *pz;
2975 *pz++ = (digit)(carry & PyLong_MASK);
2976 carry >>= PyLong_SHIFT;
2977 }
2978 if (carry)
2979 *pz += (digit)(carry & PyLong_MASK);
2980 assert((carry >> PyLong_SHIFT) == 0);
2981 }
2982 }
2983 else { /* a is not the same as b -- gradeschool long mult */
2984 for (i = 0; i < size_a; ++i) {
2985 twodigits carry = 0;
2986 twodigits f = a->ob_digit[i];
2987 digit *pz = z->ob_digit + i;
2988 digit *pb = b->ob_digit;
2989 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002992 Py_DECREF(z);
2993 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002994 });
Tim Peters0973b992004-08-29 22:16:50 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 while (pb < pbend) {
2997 carry += *pz + *pb++ * f;
2998 *pz++ = (digit)(carry & PyLong_MASK);
2999 carry >>= PyLong_SHIFT;
3000 assert(carry <= PyLong_MASK);
3001 }
3002 if (carry)
3003 *pz += (digit)(carry & PyLong_MASK);
3004 assert((carry >> PyLong_SHIFT) == 0);
3005 }
3006 }
3007 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003008}
3009
3010/* A helper for Karatsuba multiplication (k_mul).
3011 Takes a long "n" and an integer "size" representing the place to
3012 split, and sets low and high such that abs(n) == (high << size) + low,
3013 viewing the shift as being by digits. The sign bit is ignored, and
3014 the return values are >= 0.
3015 Returns 0 on success, -1 on failure.
3016*/
3017static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003018kmul_split(PyLongObject *n,
3019 Py_ssize_t size,
3020 PyLongObject **high,
3021 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 PyLongObject *hi, *lo;
3024 Py_ssize_t size_lo, size_hi;
3025 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003026
Victor Stinner640c35c2013-06-04 23:14:37 +02003027 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 if ((hi = _PyLong_New(size_hi)) == NULL)
3031 return -1;
3032 if ((lo = _PyLong_New(size_lo)) == NULL) {
3033 Py_DECREF(hi);
3034 return -1;
3035 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3038 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 *high = long_normalize(hi);
3041 *low = long_normalize(lo);
3042 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003043}
3044
Tim Peters60004642002-08-12 22:01:34 +00003045static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3046
Tim Peters5af4e6c2002-08-12 02:31:19 +00003047/* Karatsuba multiplication. Ignores the input signs, and returns the
3048 * absolute value of the product (or NULL if error).
3049 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3050 */
3051static PyLongObject *
3052k_mul(PyLongObject *a, PyLongObject *b)
3053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 Py_ssize_t asize = ABS(Py_SIZE(a));
3055 Py_ssize_t bsize = ABS(Py_SIZE(b));
3056 PyLongObject *ah = NULL;
3057 PyLongObject *al = NULL;
3058 PyLongObject *bh = NULL;
3059 PyLongObject *bl = NULL;
3060 PyLongObject *ret = NULL;
3061 PyLongObject *t1, *t2, *t3;
3062 Py_ssize_t shift; /* the number of digits we split off */
3063 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3066 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3067 * Then the original product is
3068 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3069 * By picking X to be a power of 2, "*X" is just shifting, and it's
3070 * been reduced to 3 multiplies on numbers half the size.
3071 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 /* We want to split based on the larger number; fiddle so that b
3074 * is largest.
3075 */
3076 if (asize > bsize) {
3077 t1 = a;
3078 a = b;
3079 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 i = asize;
3082 asize = bsize;
3083 bsize = i;
3084 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 /* Use gradeschool math when either number is too small. */
3087 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3088 if (asize <= i) {
3089 if (asize == 0)
3090 return (PyLongObject *)PyLong_FromLong(0);
3091 else
3092 return x_mul(a, b);
3093 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 /* If a is small compared to b, splitting on b gives a degenerate
3096 * case with ah==0, and Karatsuba may be (even much) less efficient
3097 * than "grade school" then. However, we can still win, by viewing
3098 * b as a string of "big digits", each of width a->ob_size. That
3099 * leads to a sequence of balanced calls to k_mul.
3100 */
3101 if (2 * asize <= bsize)
3102 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 /* Split a & b into hi & lo pieces. */
3105 shift = bsize >> 1;
3106 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3107 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 if (a == b) {
3110 bh = ah;
3111 bl = al;
3112 Py_INCREF(bh);
3113 Py_INCREF(bl);
3114 }
3115 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 /* The plan:
3118 * 1. Allocate result space (asize + bsize digits: that's always
3119 * enough).
3120 * 2. Compute ah*bh, and copy into result at 2*shift.
3121 * 3. Compute al*bl, and copy into result at 0. Note that this
3122 * can't overlap with #2.
3123 * 4. Subtract al*bl from the result, starting at shift. This may
3124 * underflow (borrow out of the high digit), but we don't care:
3125 * we're effectively doing unsigned arithmetic mod
3126 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3127 * borrows and carries out of the high digit can be ignored.
3128 * 5. Subtract ah*bh from the result, starting at shift.
3129 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3130 * at shift.
3131 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 /* 1. Allocate result space. */
3134 ret = _PyLong_New(asize + bsize);
3135 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003136#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 /* Fill with trash, to catch reference to uninitialized digits. */
3138 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003139#endif
Tim Peters44121a62002-08-12 06:17:58 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3142 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3143 assert(Py_SIZE(t1) >= 0);
3144 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3145 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3146 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 /* Zero-out the digits higher than the ah*bh copy. */
3149 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3150 if (i)
3151 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3152 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 /* 3. t2 <- al*bl, and copy into the low digits. */
3155 if ((t2 = k_mul(al, bl)) == NULL) {
3156 Py_DECREF(t1);
3157 goto fail;
3158 }
3159 assert(Py_SIZE(t2) >= 0);
3160 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3161 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 /* Zero out remaining digits. */
3164 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3165 if (i)
3166 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3169 * because it's fresher in cache.
3170 */
3171 i = Py_SIZE(ret) - shift; /* # digits after shift */
3172 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3173 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3176 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3179 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3180 Py_DECREF(ah);
3181 Py_DECREF(al);
3182 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 if (a == b) {
3185 t2 = t1;
3186 Py_INCREF(t2);
3187 }
3188 else if ((t2 = x_add(bh, bl)) == NULL) {
3189 Py_DECREF(t1);
3190 goto fail;
3191 }
3192 Py_DECREF(bh);
3193 Py_DECREF(bl);
3194 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 t3 = k_mul(t1, t2);
3197 Py_DECREF(t1);
3198 Py_DECREF(t2);
3199 if (t3 == NULL) goto fail;
3200 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 /* Add t3. It's not obvious why we can't run out of room here.
3203 * See the (*) comment after this function.
3204 */
3205 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3206 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003209
Mark Dickinson22b20182010-05-10 21:27:53 +00003210 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 Py_XDECREF(ret);
3212 Py_XDECREF(ah);
3213 Py_XDECREF(al);
3214 Py_XDECREF(bh);
3215 Py_XDECREF(bl);
3216 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003217}
3218
Tim Petersd6974a52002-08-13 20:37:51 +00003219/* (*) Why adding t3 can't "run out of room" above.
3220
Tim Petersab86c2b2002-08-15 20:06:00 +00003221Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3222to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003223
Tim Petersab86c2b2002-08-15 20:06:00 +000032241. For any integer i, i = c(i/2) + f(i/2). In particular,
3225 bsize = c(bsize/2) + f(bsize/2).
32262. shift = f(bsize/2)
32273. asize <= bsize
32284. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3229 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003230
Tim Petersab86c2b2002-08-15 20:06:00 +00003231We allocated asize + bsize result digits, and add t3 into them at an offset
3232of shift. This leaves asize+bsize-shift allocated digit positions for t3
3233to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3234asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003235
Tim Petersab86c2b2002-08-15 20:06:00 +00003236bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3237at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003238
Tim Petersab86c2b2002-08-15 20:06:00 +00003239If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3240digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3241most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003242
Tim Petersab86c2b2002-08-15 20:06:00 +00003243The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003244
Tim Petersab86c2b2002-08-15 20:06:00 +00003245 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003246
Tim Petersab86c2b2002-08-15 20:06:00 +00003247and we have asize + c(bsize/2) available digit positions. We need to show
3248this is always enough. An instance of c(bsize/2) cancels out in both, so
3249the question reduces to whether asize digits is enough to hold
3250(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3251then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3252asize 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 +00003253digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003254asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003255c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3256is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3257bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003258
Tim Peters48d52c02002-08-14 17:07:32 +00003259Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3260clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3261ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003262*/
3263
Tim Peters60004642002-08-12 22:01:34 +00003264/* b has at least twice the digits of a, and a is big enough that Karatsuba
3265 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3266 * of slices, each with a->ob_size digits, and multiply the slices by a,
3267 * one at a time. This gives k_mul balanced inputs to work with, and is
3268 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003269 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003270 * single-width slice overlap between successive partial sums).
3271 */
3272static PyLongObject *
3273k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 const Py_ssize_t asize = ABS(Py_SIZE(a));
3276 Py_ssize_t bsize = ABS(Py_SIZE(b));
3277 Py_ssize_t nbdone; /* # of b digits already multiplied */
3278 PyLongObject *ret;
3279 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 assert(asize > KARATSUBA_CUTOFF);
3282 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 /* Allocate result space, and zero it out. */
3285 ret = _PyLong_New(asize + bsize);
3286 if (ret == NULL)
3287 return NULL;
3288 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 /* Successive slices of b are copied into bslice. */
3291 bslice = _PyLong_New(asize);
3292 if (bslice == NULL)
3293 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 nbdone = 0;
3296 while (bsize > 0) {
3297 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003298 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 /* Multiply the next slice of b by a. */
3301 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3302 nbtouse * sizeof(digit));
3303 Py_SIZE(bslice) = nbtouse;
3304 product = k_mul(a, bslice);
3305 if (product == NULL)
3306 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 /* Add into result. */
3309 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3310 product->ob_digit, Py_SIZE(product));
3311 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 bsize -= nbtouse;
3314 nbdone += nbtouse;
3315 }
Tim Peters60004642002-08-12 22:01:34 +00003316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 Py_DECREF(bslice);
3318 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003319
Mark Dickinson22b20182010-05-10 21:27:53 +00003320 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 Py_DECREF(ret);
3322 Py_XDECREF(bslice);
3323 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003324}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003325
3326static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003327long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 /* fast path for single-digit multiplication */
3334 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3335 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003336#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003338#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 /* if we don't have long long then we're almost certainly
3340 using 15-bit digits, so v will fit in a long. In the
3341 unlikely event that we're using 30-bit digits on a platform
3342 without long long, a large v will just cause us to fall
3343 through to the general multiplication code below. */
3344 if (v >= LONG_MIN && v <= LONG_MAX)
3345 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003346#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 z = k_mul(a, b);
3350 /* Negate if exactly one of the inputs is negative. */
3351 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3352 NEGATE(z);
3353 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003354}
3355
Guido van Rossume32e0141992-01-19 16:31:05 +00003356/* The / and % operators are now defined in terms of divmod().
3357 The expression a mod b has the value a - b*floor(a/b).
3358 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003359 |a| by |b|, with the sign of a. This is also expressed
3360 as a - b*trunc(a/b), if trunc truncates towards zero.
3361 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 a b a rem b a mod b
3363 13 10 3 3
3364 -13 10 -3 7
3365 13 -10 3 -7
3366 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003367 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003368 have different signs. We then subtract one from the 'div'
3369 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003370
Tim Peters47e52ee2004-08-30 02:44:38 +00003371/* Compute
3372 * *pdiv, *pmod = divmod(v, w)
3373 * NULL can be passed for pdiv or pmod, in which case that part of
3374 * the result is simply thrown away. The caller owns a reference to
3375 * each of these it requests (does not pass NULL for).
3376 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003377static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003378l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 if (long_divrem(v, w, &div, &mod) < 0)
3384 return -1;
3385 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3386 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3387 PyLongObject *temp;
3388 PyLongObject *one;
3389 temp = (PyLongObject *) long_add(mod, w);
3390 Py_DECREF(mod);
3391 mod = temp;
3392 if (mod == NULL) {
3393 Py_DECREF(div);
3394 return -1;
3395 }
3396 one = (PyLongObject *) PyLong_FromLong(1L);
3397 if (one == NULL ||
3398 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3399 Py_DECREF(mod);
3400 Py_DECREF(div);
3401 Py_XDECREF(one);
3402 return -1;
3403 }
3404 Py_DECREF(one);
3405 Py_DECREF(div);
3406 div = temp;
3407 }
3408 if (pdiv != NULL)
3409 *pdiv = div;
3410 else
3411 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 if (pmod != NULL)
3414 *pmod = mod;
3415 else
3416 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003419}
3420
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003421static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003422long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 CHECK_BINOP(a, b);
3427 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3428 div = NULL;
3429 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003430}
3431
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003432/* PyLong/PyLong -> float, with correctly rounded result. */
3433
3434#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3435#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3436
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003437static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003438long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 PyLongObject *a, *b, *x;
3441 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3442 digit mask, low;
3443 int inexact, negate, a_is_small, b_is_small;
3444 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 CHECK_BINOP(v, w);
3447 a = (PyLongObject *)v;
3448 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 /*
3451 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3454 1. choose a suitable integer 'shift'
3455 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3456 3. adjust x for correct rounding
3457 4. convert x to a double dx with the same value
3458 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3463 returns either 0.0 or -0.0, depending on the sign of b. For a and
3464 b both nonzero, ignore signs of a and b, and add the sign back in
3465 at the end. Now write a_bits and b_bits for the bit lengths of a
3466 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3467 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3472 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3473 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3474 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 1. The integer 'shift' is chosen so that x has the right number of
3479 bits for a double, plus two or three extra bits that will be used
3480 in the rounding decisions. Writing a_bits and b_bits for the
3481 number of significant bits in a and b respectively, a
3482 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 This is fine in the usual case, but if a/b is smaller than the
3487 smallest normal float then it can lead to double rounding on an
3488 IEEE 754 platform, giving incorrectly rounded results. So we
3489 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 2. The quantity x is computed by first shifting a (left -shift bits
3494 if shift <= 0, right shift bits if shift > 0) and then dividing by
3495 b. For both the shift and the division, we keep track of whether
3496 the result is inexact, in a flag 'inexact'; this information is
3497 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 With the choice of shift above, together with our assumption that
3500 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3501 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3504 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 For float representability, we need x/2**extra_bits <
3509 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3510 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 To round, we just modify the bottom digit of x in-place; this can
3515 end up giving a digit with value > PyLONG_MASK, but that's not a
3516 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 With the original choices for shift above, extra_bits will always
3519 be 2 or 3. Then rounding under the round-half-to-even rule, we
3520 round up iff the most significant of the extra bits is 1, and
3521 either: (a) the computation of x in step 2 had an inexact result,
3522 or (b) at least one other of the extra bits is 1, or (c) the least
3523 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 4. Conversion to a double is straightforward; all floating-point
3526 operations involved in the conversion are exact, so there's no
3527 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3530 The result will always be exactly representable as a double, except
3531 in the case that it overflows. To avoid dependence on the exact
3532 behaviour of ldexp on overflow, we check for overflow before
3533 applying ldexp. The result of ldexp is adjusted for sign before
3534 returning.
3535 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 /* Reduce to case where a and b are both positive. */
3538 a_size = ABS(Py_SIZE(a));
3539 b_size = ABS(Py_SIZE(b));
3540 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3541 if (b_size == 0) {
3542 PyErr_SetString(PyExc_ZeroDivisionError,
3543 "division by zero");
3544 goto error;
3545 }
3546 if (a_size == 0)
3547 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 /* Fast path for a and b small (exactly representable in a double).
3550 Relies on floating-point division being correctly rounded; results
3551 may be subject to double rounding on x86 machines that operate with
3552 the x87 FPU set to 64-bit precision. */
3553 a_is_small = a_size <= MANT_DIG_DIGITS ||
3554 (a_size == MANT_DIG_DIGITS+1 &&
3555 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3556 b_is_small = b_size <= MANT_DIG_DIGITS ||
3557 (b_size == MANT_DIG_DIGITS+1 &&
3558 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3559 if (a_is_small && b_is_small) {
3560 double da, db;
3561 da = a->ob_digit[--a_size];
3562 while (a_size > 0)
3563 da = da * PyLong_BASE + a->ob_digit[--a_size];
3564 db = b->ob_digit[--b_size];
3565 while (b_size > 0)
3566 db = db * PyLong_BASE + b->ob_digit[--b_size];
3567 result = da / db;
3568 goto success;
3569 }
Tim Peterse2a60002001-09-04 06:17:36 +00003570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 /* Catch obvious cases of underflow and overflow */
3572 diff = a_size - b_size;
3573 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3574 /* Extreme overflow */
3575 goto overflow;
3576 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3577 /* Extreme underflow */
3578 goto underflow_or_zero;
3579 /* Next line is now safe from overflowing a Py_ssize_t */
3580 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3581 bits_in_digit(b->ob_digit[b_size - 1]);
3582 /* Now diff = a_bits - b_bits. */
3583 if (diff > DBL_MAX_EXP)
3584 goto overflow;
3585 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3586 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003589 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 /* x = abs(a * 2**-shift) */
3594 if (shift <= 0) {
3595 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3596 digit rem;
3597 /* x = a << -shift */
3598 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3599 /* In practice, it's probably impossible to end up
3600 here. Both a and b would have to be enormous,
3601 using close to SIZE_T_MAX bytes of memory each. */
3602 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003603 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 goto error;
3605 }
3606 x = _PyLong_New(a_size + shift_digits + 1);
3607 if (x == NULL)
3608 goto error;
3609 for (i = 0; i < shift_digits; i++)
3610 x->ob_digit[i] = 0;
3611 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3612 a_size, -shift % PyLong_SHIFT);
3613 x->ob_digit[a_size + shift_digits] = rem;
3614 }
3615 else {
3616 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3617 digit rem;
3618 /* x = a >> shift */
3619 assert(a_size >= shift_digits);
3620 x = _PyLong_New(a_size - shift_digits);
3621 if (x == NULL)
3622 goto error;
3623 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3624 a_size - shift_digits, shift % PyLong_SHIFT);
3625 /* set inexact if any of the bits shifted out is nonzero */
3626 if (rem)
3627 inexact = 1;
3628 while (!inexact && shift_digits > 0)
3629 if (a->ob_digit[--shift_digits])
3630 inexact = 1;
3631 }
3632 long_normalize(x);
3633 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3636 reference to x, so it's safe to modify it in-place. */
3637 if (b_size == 1) {
3638 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3639 b->ob_digit[0]);
3640 long_normalize(x);
3641 if (rem)
3642 inexact = 1;
3643 }
3644 else {
3645 PyLongObject *div, *rem;
3646 div = x_divrem(x, b, &rem);
3647 Py_DECREF(x);
3648 x = div;
3649 if (x == NULL)
3650 goto error;
3651 if (Py_SIZE(rem))
3652 inexact = 1;
3653 Py_DECREF(rem);
3654 }
3655 x_size = ABS(Py_SIZE(x));
3656 assert(x_size > 0); /* result of division is never zero */
3657 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003660 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 /* Round by directly modifying the low digit of x. */
3664 mask = (digit)1 << (extra_bits - 1);
3665 low = x->ob_digit[0] | inexact;
3666 if (low & mask && low & (3*mask-1))
3667 low += mask;
3668 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 /* Convert x to a double dx; the conversion is exact. */
3671 dx = x->ob_digit[--x_size];
3672 while (x_size > 0)
3673 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3674 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 /* Check whether ldexp result will overflow a double. */
3677 if (shift + x_bits >= DBL_MAX_EXP &&
3678 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3679 goto overflow;
3680 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003681
3682 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003684
3685 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003687
3688 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 PyErr_SetString(PyExc_OverflowError,
3690 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003691 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003693}
3694
3695static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003696long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 CHECK_BINOP(a, b);
3701
3702 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3703 mod = NULL;
3704 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003705}
3706
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003707static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003708long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 PyLongObject *div, *mod;
3711 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003715 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3716 return NULL;
3717 }
3718 z = PyTuple_New(2);
3719 if (z != NULL) {
3720 PyTuple_SetItem(z, 0, (PyObject *) div);
3721 PyTuple_SetItem(z, 1, (PyObject *) mod);
3722 }
3723 else {
3724 Py_DECREF(div);
3725 Py_DECREF(mod);
3726 }
3727 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003728}
3729
Tim Peters47e52ee2004-08-30 02:44:38 +00003730/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003731static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003732long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3735 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 PyLongObject *z = NULL; /* accumulated result */
3738 Py_ssize_t i, j, k; /* counters */
3739 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 /* 5-ary values. If the exponent is large enough, table is
3742 * precomputed so that table[i] == a**i % c for i in range(32).
3743 */
3744 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3745 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 /* a, b, c = v, w, x */
3748 CHECK_BINOP(v, w);
3749 a = (PyLongObject*)v; Py_INCREF(a);
3750 b = (PyLongObject*)w; Py_INCREF(b);
3751 if (PyLong_Check(x)) {
3752 c = (PyLongObject *)x;
3753 Py_INCREF(x);
3754 }
3755 else if (x == Py_None)
3756 c = NULL;
3757 else {
3758 Py_DECREF(a);
3759 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003760 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 }
Tim Peters4c483c42001-09-05 06:24:58 +00003762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3764 if (c) {
3765 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003766 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 goto Error;
3768 }
3769 else {
3770 /* else return a float. This works because we know
3771 that this calls float_pow() which converts its
3772 arguments to double. */
3773 Py_DECREF(a);
3774 Py_DECREF(b);
3775 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3776 }
3777 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 if (c) {
3780 /* if modulus == 0:
3781 raise ValueError() */
3782 if (Py_SIZE(c) == 0) {
3783 PyErr_SetString(PyExc_ValueError,
3784 "pow() 3rd argument cannot be 0");
3785 goto Error;
3786 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 /* if modulus < 0:
3789 negativeOutput = True
3790 modulus = -modulus */
3791 if (Py_SIZE(c) < 0) {
3792 negativeOutput = 1;
3793 temp = (PyLongObject *)_PyLong_Copy(c);
3794 if (temp == NULL)
3795 goto Error;
3796 Py_DECREF(c);
3797 c = temp;
3798 temp = NULL;
3799 NEGATE(c);
3800 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 /* if modulus == 1:
3803 return 0 */
3804 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3805 z = (PyLongObject *)PyLong_FromLong(0L);
3806 goto Done;
3807 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 /* if base < 0:
3810 base = base % modulus
3811 Having the base positive just makes things easier. */
3812 if (Py_SIZE(a) < 0) {
3813 if (l_divmod(a, c, NULL, &temp) < 0)
3814 goto Error;
3815 Py_DECREF(a);
3816 a = temp;
3817 temp = NULL;
3818 }
3819 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 /* At this point a, b, and c are guaranteed non-negative UNLESS
3822 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 z = (PyLongObject *)PyLong_FromLong(1L);
3825 if (z == NULL)
3826 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 /* Perform a modular reduction, X = X % c, but leave X alone if c
3829 * is NULL.
3830 */
3831#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003832 do { \
3833 if (c != NULL) { \
3834 if (l_divmod(X, c, NULL, &temp) < 0) \
3835 goto Error; \
3836 Py_XDECREF(X); \
3837 X = temp; \
3838 temp = NULL; \
3839 } \
3840 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 /* Multiply two values, then reduce the result:
3843 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003844#define MULT(X, Y, result) \
3845 do { \
3846 temp = (PyLongObject *)long_mul(X, Y); \
3847 if (temp == NULL) \
3848 goto Error; \
3849 Py_XDECREF(result); \
3850 result = temp; \
3851 temp = NULL; \
3852 REDUCE(result); \
3853 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3856 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3857 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3858 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3859 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003862 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003864 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 }
3866 }
3867 }
3868 else {
3869 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3870 Py_INCREF(z); /* still holds 1L */
3871 table[0] = z;
3872 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003873 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3876 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3879 const int index = (bi >> j) & 0x1f;
3880 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003881 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003883 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 }
3885 }
3886 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 if (negativeOutput && (Py_SIZE(z) != 0)) {
3889 temp = (PyLongObject *)long_sub(z, c);
3890 if (temp == NULL)
3891 goto Error;
3892 Py_DECREF(z);
3893 z = temp;
3894 temp = NULL;
3895 }
3896 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003897
Mark Dickinson22b20182010-05-10 21:27:53 +00003898 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 if (z != NULL) {
3900 Py_DECREF(z);
3901 z = NULL;
3902 }
3903 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003904 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3906 for (i = 0; i < 32; ++i)
3907 Py_XDECREF(table[i]);
3908 }
3909 Py_DECREF(a);
3910 Py_DECREF(b);
3911 Py_XDECREF(c);
3912 Py_XDECREF(temp);
3913 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003914}
3915
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003916static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003917long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 /* Implement ~x as -(x+1) */
3920 PyLongObject *x;
3921 PyLongObject *w;
3922 if (ABS(Py_SIZE(v)) <=1)
3923 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3924 w = (PyLongObject *)PyLong_FromLong(1L);
3925 if (w == NULL)
3926 return NULL;
3927 x = (PyLongObject *) long_add(v, w);
3928 Py_DECREF(w);
3929 if (x == NULL)
3930 return NULL;
3931 Py_SIZE(x) = -(Py_SIZE(x));
3932 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003933}
3934
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003935static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003936long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 PyLongObject *z;
3939 if (ABS(Py_SIZE(v)) <= 1)
3940 return PyLong_FromLong(-MEDIUM_VALUE(v));
3941 z = (PyLongObject *)_PyLong_Copy(v);
3942 if (z != NULL)
3943 Py_SIZE(z) = -(Py_SIZE(v));
3944 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003945}
3946
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003947static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003948long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 if (Py_SIZE(v) < 0)
3951 return long_neg(v);
3952 else
3953 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003954}
3955
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003956static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003957long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003960}
3961
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003962static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003963long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 PyLongObject *z = NULL;
3966 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3967 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 if (Py_SIZE(a) < 0) {
3972 /* Right shifting negative numbers is harder */
3973 PyLongObject *a1, *a2;
3974 a1 = (PyLongObject *) long_invert(a);
3975 if (a1 == NULL)
3976 goto rshift_error;
3977 a2 = (PyLongObject *) long_rshift(a1, b);
3978 Py_DECREF(a1);
3979 if (a2 == NULL)
3980 goto rshift_error;
3981 z = (PyLongObject *) long_invert(a2);
3982 Py_DECREF(a2);
3983 }
3984 else {
3985 shiftby = PyLong_AsSsize_t((PyObject *)b);
3986 if (shiftby == -1L && PyErr_Occurred())
3987 goto rshift_error;
3988 if (shiftby < 0) {
3989 PyErr_SetString(PyExc_ValueError,
3990 "negative shift count");
3991 goto rshift_error;
3992 }
3993 wordshift = shiftby / PyLong_SHIFT;
3994 newsize = ABS(Py_SIZE(a)) - wordshift;
3995 if (newsize <= 0)
3996 return PyLong_FromLong(0);
3997 loshift = shiftby % PyLong_SHIFT;
3998 hishift = PyLong_SHIFT - loshift;
3999 lomask = ((digit)1 << hishift) - 1;
4000 himask = PyLong_MASK ^ lomask;
4001 z = _PyLong_New(newsize);
4002 if (z == NULL)
4003 goto rshift_error;
4004 if (Py_SIZE(a) < 0)
4005 Py_SIZE(z) = -(Py_SIZE(z));
4006 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4007 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4008 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004009 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 }
4011 z = long_normalize(z);
4012 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004013 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004015
Guido van Rossumc6913e71991-11-19 20:26:46 +00004016}
4017
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004018static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004019long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 /* This version due to Tim Peters */
4022 PyLongObject *a = (PyLongObject*)v;
4023 PyLongObject *b = (PyLongObject*)w;
4024 PyLongObject *z = NULL;
4025 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4026 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 shiftby = PyLong_AsSsize_t((PyObject *)b);
4031 if (shiftby == -1L && PyErr_Occurred())
4032 goto lshift_error;
4033 if (shiftby < 0) {
4034 PyErr_SetString(PyExc_ValueError, "negative shift count");
4035 goto lshift_error;
4036 }
4037 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4038 wordshift = shiftby / PyLong_SHIFT;
4039 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 oldsize = ABS(Py_SIZE(a));
4042 newsize = oldsize + wordshift;
4043 if (remshift)
4044 ++newsize;
4045 z = _PyLong_New(newsize);
4046 if (z == NULL)
4047 goto lshift_error;
4048 if (Py_SIZE(a) < 0)
4049 NEGATE(z);
4050 for (i = 0; i < wordshift; i++)
4051 z->ob_digit[i] = 0;
4052 accum = 0;
4053 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4054 accum |= (twodigits)a->ob_digit[j] << remshift;
4055 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4056 accum >>= PyLong_SHIFT;
4057 }
4058 if (remshift)
4059 z->ob_digit[newsize-1] = (digit)accum;
4060 else
4061 assert(!accum);
4062 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004063 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004065}
4066
Mark Dickinson27a87a22009-10-25 20:43:34 +00004067/* Compute two's complement of digit vector a[0:m], writing result to
4068 z[0:m]. The digit vector a need not be normalized, but should not
4069 be entirely zero. a and z may point to the same digit vector. */
4070
4071static void
4072v_complement(digit *z, digit *a, Py_ssize_t m)
4073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 Py_ssize_t i;
4075 digit carry = 1;
4076 for (i = 0; i < m; ++i) {
4077 carry += a[i] ^ PyLong_MASK;
4078 z[i] = carry & PyLong_MASK;
4079 carry >>= PyLong_SHIFT;
4080 }
4081 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004082}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004083
4084/* Bitwise and/xor/or operations */
4085
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004086static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004087long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004088 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004089 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 int nega, negb, negz;
4092 Py_ssize_t size_a, size_b, size_z, i;
4093 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 /* Bitwise operations for negative numbers operate as though
4096 on a two's complement representation. So convert arguments
4097 from sign-magnitude to two's complement, and convert the
4098 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 /* If a is negative, replace it by its two's complement. */
4101 size_a = ABS(Py_SIZE(a));
4102 nega = Py_SIZE(a) < 0;
4103 if (nega) {
4104 z = _PyLong_New(size_a);
4105 if (z == NULL)
4106 return NULL;
4107 v_complement(z->ob_digit, a->ob_digit, size_a);
4108 a = z;
4109 }
4110 else
4111 /* Keep reference count consistent. */
4112 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 /* Same for b. */
4115 size_b = ABS(Py_SIZE(b));
4116 negb = Py_SIZE(b) < 0;
4117 if (negb) {
4118 z = _PyLong_New(size_b);
4119 if (z == NULL) {
4120 Py_DECREF(a);
4121 return NULL;
4122 }
4123 v_complement(z->ob_digit, b->ob_digit, size_b);
4124 b = z;
4125 }
4126 else
4127 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 /* Swap a and b if necessary to ensure size_a >= size_b. */
4130 if (size_a < size_b) {
4131 z = a; a = b; b = z;
4132 size_z = size_a; size_a = size_b; size_b = size_z;
4133 negz = nega; nega = negb; negb = negz;
4134 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 /* JRH: The original logic here was to allocate the result value (z)
4137 as the longer of the two operands. However, there are some cases
4138 where the result is guaranteed to be shorter than that: AND of two
4139 positives, OR of two negatives: use the shorter number. AND with
4140 mixed signs: use the positive number. OR with mixed signs: use the
4141 negative number.
4142 */
4143 switch (op) {
4144 case '^':
4145 negz = nega ^ negb;
4146 size_z = size_a;
4147 break;
4148 case '&':
4149 negz = nega & negb;
4150 size_z = negb ? size_a : size_b;
4151 break;
4152 case '|':
4153 negz = nega | negb;
4154 size_z = negb ? size_b : size_a;
4155 break;
4156 default:
4157 PyErr_BadArgument();
4158 return NULL;
4159 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 /* We allow an extra digit if z is negative, to make sure that
4162 the final two's complement of z doesn't overflow. */
4163 z = _PyLong_New(size_z + negz);
4164 if (z == NULL) {
4165 Py_DECREF(a);
4166 Py_DECREF(b);
4167 return NULL;
4168 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 /* Compute digits for overlap of a and b. */
4171 switch(op) {
4172 case '&':
4173 for (i = 0; i < size_b; ++i)
4174 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4175 break;
4176 case '|':
4177 for (i = 0; i < size_b; ++i)
4178 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4179 break;
4180 case '^':
4181 for (i = 0; i < size_b; ++i)
4182 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4183 break;
4184 default:
4185 PyErr_BadArgument();
4186 return NULL;
4187 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 /* Copy any remaining digits of a, inverting if necessary. */
4190 if (op == '^' && negb)
4191 for (; i < size_z; ++i)
4192 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4193 else if (i < size_z)
4194 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4195 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 /* Complement result if negative. */
4198 if (negz) {
4199 Py_SIZE(z) = -(Py_SIZE(z));
4200 z->ob_digit[size_z] = PyLong_MASK;
4201 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4202 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 Py_DECREF(a);
4205 Py_DECREF(b);
4206 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004207}
4208
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004209static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004210long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 PyObject *c;
4213 CHECK_BINOP(a, b);
4214 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4215 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004216}
4217
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004218static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004219long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 PyObject *c;
4222 CHECK_BINOP(a, b);
4223 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4224 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004225}
4226
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004227static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004228long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 PyObject *c;
4231 CHECK_BINOP(a, b);
4232 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4233 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004234}
4235
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004236static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004237long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 if (PyLong_CheckExact(v))
4240 Py_INCREF(v);
4241 else
4242 v = _PyLong_Copy((PyLongObject *)v);
4243 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004244}
4245
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004246static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004247long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 double result;
4250 result = PyLong_AsDouble(v);
4251 if (result == -1.0 && PyErr_Occurred())
4252 return NULL;
4253 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004254}
4255
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004256static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004257long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004258
Tim Peters6d6c1a32001-08-02 04:15:00 +00004259static PyObject *
4260long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4261{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004262 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004263 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 if (type != &PyLong_Type)
4267 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004268 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4269 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004271 if (x == NULL) {
4272 if (obase != NULL) {
4273 PyErr_SetString(PyExc_TypeError,
4274 "int() missing string argument");
4275 return NULL;
4276 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004278 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004279 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004281
Gregory P. Smitha689e522012-12-25 22:38:32 -08004282 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004283 if (base == -1 && PyErr_Occurred())
4284 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004285 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004286 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004287 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004288 return NULL;
4289 }
4290
4291 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004292 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4294 /* Since PyLong_FromString doesn't have a length parameter,
4295 * check here for possible NULs in the string. */
4296 char *string;
4297 Py_ssize_t size = Py_SIZE(x);
4298 if (PyByteArray_Check(x))
4299 string = PyByteArray_AS_STRING(x);
4300 else
4301 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004302 if (strlen(string) != (size_t)size || !size) {
4303 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 x is a bytes or buffer, *and* a base is given. */
4305 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004306 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004307 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 return NULL;
4309 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004310 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 }
4312 else {
4313 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004314 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 return NULL;
4316 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004317}
4318
Guido van Rossumbef14172001-08-29 15:47:46 +00004319/* Wimpy, slow approach to tp_new calls for subtypes of long:
4320 first create a regular long from whatever arguments we got,
4321 then allocate a subtype instance and initialize it from
4322 the regular long. The regular long is then thrown away.
4323*/
4324static PyObject *
4325long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 PyLongObject *tmp, *newobj;
4328 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 assert(PyType_IsSubtype(type, &PyLong_Type));
4331 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4332 if (tmp == NULL)
4333 return NULL;
4334 assert(PyLong_CheckExact(tmp));
4335 n = Py_SIZE(tmp);
4336 if (n < 0)
4337 n = -n;
4338 newobj = (PyLongObject *)type->tp_alloc(type, n);
4339 if (newobj == NULL) {
4340 Py_DECREF(tmp);
4341 return NULL;
4342 }
4343 assert(PyLong_Check(newobj));
4344 Py_SIZE(newobj) = Py_SIZE(tmp);
4345 for (i = 0; i < n; i++)
4346 newobj->ob_digit[i] = tmp->ob_digit[i];
4347 Py_DECREF(tmp);
4348 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004349}
4350
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004351static PyObject *
4352long_getnewargs(PyLongObject *v)
4353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004355}
4356
Guido van Rossumb43daf72007-08-01 18:08:08 +00004357static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004358long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004360}
4361
4362static PyObject *
4363long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004365}
4366
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004367static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004368long__format__(PyObject *self, PyObject *args)
4369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004371 _PyUnicodeWriter writer;
4372 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4375 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004376
Victor Stinner8f674cc2013-04-17 23:02:17 +02004377 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004378 ret = _PyLong_FormatAdvancedWriter(
4379 &writer,
4380 self,
4381 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4382 if (ret == -1) {
4383 _PyUnicodeWriter_Dealloc(&writer);
4384 return NULL;
4385 }
4386 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004387}
4388
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004389/* Return a pair (q, r) such that a = b * q + r, and
4390 abs(r) <= abs(b)/2, with equality possible only if q is even.
4391 In other words, q == a / b, rounded to the nearest integer using
4392 round-half-to-even. */
4393
4394PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004395_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004396{
4397 PyLongObject *quo = NULL, *rem = NULL;
4398 PyObject *one = NULL, *twice_rem, *result, *temp;
4399 int cmp, quo_is_odd, quo_is_neg;
4400
4401 /* Equivalent Python code:
4402
4403 def divmod_near(a, b):
4404 q, r = divmod(a, b)
4405 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4406 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4407 # positive, 2 * r < b if b negative.
4408 greater_than_half = 2*r > b if b > 0 else 2*r < b
4409 exactly_half = 2*r == b
4410 if greater_than_half or exactly_half and q % 2 == 1:
4411 q += 1
4412 r -= b
4413 return q, r
4414
4415 */
4416 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4417 PyErr_SetString(PyExc_TypeError,
4418 "non-integer arguments in division");
4419 return NULL;
4420 }
4421
4422 /* Do a and b have different signs? If so, quotient is negative. */
4423 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4424
4425 one = PyLong_FromLong(1L);
4426 if (one == NULL)
4427 return NULL;
4428
4429 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4430 goto error;
4431
4432 /* compare twice the remainder with the divisor, to see
4433 if we need to adjust the quotient and remainder */
4434 twice_rem = long_lshift((PyObject *)rem, one);
4435 if (twice_rem == NULL)
4436 goto error;
4437 if (quo_is_neg) {
4438 temp = long_neg((PyLongObject*)twice_rem);
4439 Py_DECREF(twice_rem);
4440 twice_rem = temp;
4441 if (twice_rem == NULL)
4442 goto error;
4443 }
4444 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4445 Py_DECREF(twice_rem);
4446
4447 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4448 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4449 /* fix up quotient */
4450 if (quo_is_neg)
4451 temp = long_sub(quo, (PyLongObject *)one);
4452 else
4453 temp = long_add(quo, (PyLongObject *)one);
4454 Py_DECREF(quo);
4455 quo = (PyLongObject *)temp;
4456 if (quo == NULL)
4457 goto error;
4458 /* and remainder */
4459 if (quo_is_neg)
4460 temp = long_add(rem, (PyLongObject *)b);
4461 else
4462 temp = long_sub(rem, (PyLongObject *)b);
4463 Py_DECREF(rem);
4464 rem = (PyLongObject *)temp;
4465 if (rem == NULL)
4466 goto error;
4467 }
4468
4469 result = PyTuple_New(2);
4470 if (result == NULL)
4471 goto error;
4472
4473 /* PyTuple_SET_ITEM steals references */
4474 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4475 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4476 Py_DECREF(one);
4477 return result;
4478
4479 error:
4480 Py_XDECREF(quo);
4481 Py_XDECREF(rem);
4482 Py_XDECREF(one);
4483 return NULL;
4484}
4485
Eric Smith8c663262007-08-25 02:26:07 +00004486static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004487long_round(PyObject *self, PyObject *args)
4488{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004489 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004490
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004491 /* To round an integer m to the nearest 10**n (n positive), we make use of
4492 * the divmod_near operation, defined by:
4493 *
4494 * divmod_near(a, b) = (q, r)
4495 *
4496 * where q is the nearest integer to the quotient a / b (the
4497 * nearest even integer in the case of a tie) and r == a - q * b.
4498 * Hence q * b = a - r is the nearest multiple of b to a,
4499 * preferring even multiples in the case of a tie.
4500 *
4501 * So the nearest multiple of 10**n to m is:
4502 *
4503 * m - divmod_near(m, 10**n)[1].
4504 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4506 return NULL;
4507 if (o_ndigits == NULL)
4508 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004509
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004510 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 if (ndigits == NULL)
4512 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004513
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004514 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 if (Py_SIZE(ndigits) >= 0) {
4516 Py_DECREF(ndigits);
4517 return long_long(self);
4518 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004519
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004520 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4521 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004523 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004525 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004526
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004527 result = PyLong_FromLong(10L);
4528 if (result == NULL) {
4529 Py_DECREF(ndigits);
4530 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004532
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004533 temp = long_pow(result, ndigits, Py_None);
4534 Py_DECREF(ndigits);
4535 Py_DECREF(result);
4536 result = temp;
4537 if (result == NULL)
4538 return NULL;
4539
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004540 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004541 Py_DECREF(result);
4542 result = temp;
4543 if (result == NULL)
4544 return NULL;
4545
4546 temp = long_sub((PyLongObject *)self,
4547 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4548 Py_DECREF(result);
4549 result = temp;
4550
4551 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004552}
4553
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004554static PyObject *
4555long_sizeof(PyLongObject *v)
4556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4560 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004561}
4562
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004563static PyObject *
4564long_bit_length(PyLongObject *v)
4565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 PyLongObject *result, *x, *y;
4567 Py_ssize_t ndigits, msd_bits = 0;
4568 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 assert(v != NULL);
4571 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 ndigits = ABS(Py_SIZE(v));
4574 if (ndigits == 0)
4575 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 msd = v->ob_digit[ndigits-1];
4578 while (msd >= 32) {
4579 msd_bits += 6;
4580 msd >>= 6;
4581 }
4582 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4585 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 /* expression above may overflow; use Python integers instead */
4588 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4589 if (result == NULL)
4590 return NULL;
4591 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4592 if (x == NULL)
4593 goto error;
4594 y = (PyLongObject *)long_mul(result, x);
4595 Py_DECREF(x);
4596 if (y == NULL)
4597 goto error;
4598 Py_DECREF(result);
4599 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4602 if (x == NULL)
4603 goto error;
4604 y = (PyLongObject *)long_add(result, x);
4605 Py_DECREF(x);
4606 if (y == NULL)
4607 goto error;
4608 Py_DECREF(result);
4609 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004612
Mark Dickinson22b20182010-05-10 21:27:53 +00004613 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 Py_DECREF(result);
4615 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004616}
4617
4618PyDoc_STRVAR(long_bit_length_doc,
4619"int.bit_length() -> int\n\
4620\n\
4621Number of bits necessary to represent self in binary.\n\
4622>>> bin(37)\n\
4623'0b100101'\n\
4624>>> (37).bit_length()\n\
46256");
4626
Christian Heimes53876d92008-04-19 00:31:39 +00004627#if 0
4628static PyObject *
4629long_is_finite(PyObject *v)
4630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004632}
4633#endif
4634
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004635
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004636static PyObject *
4637long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 PyObject *byteorder_str;
4640 PyObject *is_signed_obj = NULL;
4641 Py_ssize_t length;
4642 int little_endian;
4643 int is_signed;
4644 PyObject *bytes;
4645 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4648 &length, &byteorder_str,
4649 &is_signed_obj))
4650 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 if (args != NULL && Py_SIZE(args) > 2) {
4653 PyErr_SetString(PyExc_TypeError,
4654 "'signed' is a keyword-only argument");
4655 return NULL;
4656 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4659 little_endian = 1;
4660 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4661 little_endian = 0;
4662 else {
4663 PyErr_SetString(PyExc_ValueError,
4664 "byteorder must be either 'little' or 'big'");
4665 return NULL;
4666 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 if (is_signed_obj != NULL) {
4669 int cmp = PyObject_IsTrue(is_signed_obj);
4670 if (cmp < 0)
4671 return NULL;
4672 is_signed = cmp ? 1 : 0;
4673 }
4674 else {
4675 /* If the signed argument was omitted, use False as the
4676 default. */
4677 is_signed = 0;
4678 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 if (length < 0) {
4681 PyErr_SetString(PyExc_ValueError,
4682 "length argument must be non-negative");
4683 return NULL;
4684 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 bytes = PyBytes_FromStringAndSize(NULL, length);
4687 if (bytes == NULL)
4688 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4691 length, little_endian, is_signed) < 0) {
4692 Py_DECREF(bytes);
4693 return NULL;
4694 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004697}
4698
Mark Dickinson078c2532010-01-30 18:06:17 +00004699PyDoc_STRVAR(long_to_bytes_doc,
4700"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004701\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004702Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004703\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004705raised if the integer is not representable with the given number of\n\
4706bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004707\n\
4708The byteorder argument determines the byte order used to represent the\n\
4709integer. If byteorder is 'big', the most significant byte is at the\n\
4710beginning of the byte array. If byteorder is 'little', the most\n\
4711significant byte is at the end of the byte array. To request the native\n\
4712byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4713\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004714The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004715used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004716is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004717
4718static PyObject *
4719long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 PyObject *byteorder_str;
4722 PyObject *is_signed_obj = NULL;
4723 int little_endian;
4724 int is_signed;
4725 PyObject *obj;
4726 PyObject *bytes;
4727 PyObject *long_obj;
4728 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4731 &obj, &byteorder_str,
4732 &is_signed_obj))
4733 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 if (args != NULL && Py_SIZE(args) > 2) {
4736 PyErr_SetString(PyExc_TypeError,
4737 "'signed' is a keyword-only argument");
4738 return NULL;
4739 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4742 little_endian = 1;
4743 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4744 little_endian = 0;
4745 else {
4746 PyErr_SetString(PyExc_ValueError,
4747 "byteorder must be either 'little' or 'big'");
4748 return NULL;
4749 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 if (is_signed_obj != NULL) {
4752 int cmp = PyObject_IsTrue(is_signed_obj);
4753 if (cmp < 0)
4754 return NULL;
4755 is_signed = cmp ? 1 : 0;
4756 }
4757 else {
4758 /* If the signed argument was omitted, use False as the
4759 default. */
4760 is_signed = 0;
4761 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 bytes = PyObject_Bytes(obj);
4764 if (bytes == NULL)
4765 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 long_obj = _PyLong_FromByteArray(
4768 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4769 little_endian, is_signed);
4770 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 /* If from_bytes() was used on subclass, allocate new subclass
4773 * instance, initialize it with decoded long value and return it.
4774 */
4775 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4776 PyLongObject *newobj;
4777 int i;
4778 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 newobj = (PyLongObject *)type->tp_alloc(type, n);
4781 if (newobj == NULL) {
4782 Py_DECREF(long_obj);
4783 return NULL;
4784 }
4785 assert(PyLong_Check(newobj));
4786 Py_SIZE(newobj) = Py_SIZE(long_obj);
4787 for (i = 0; i < n; i++) {
4788 newobj->ob_digit[i] =
4789 ((PyLongObject *)long_obj)->ob_digit[i];
4790 }
4791 Py_DECREF(long_obj);
4792 return (PyObject *)newobj;
4793 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004796}
4797
Mark Dickinson078c2532010-01-30 18:06:17 +00004798PyDoc_STRVAR(long_from_bytes_doc,
4799"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4800\n\
4801Return the integer represented by the given array of bytes.\n\
4802\n\
4803The bytes argument must either support the buffer protocol or be an\n\
4804iterable object producing bytes. Bytes and bytearray are examples of\n\
4805built-in objects that support the buffer protocol.\n\
4806\n\
4807The byteorder argument determines the byte order used to represent the\n\
4808integer. If byteorder is 'big', the most significant byte is at the\n\
4809beginning of the byte array. If byteorder is 'little', the most\n\
4810significant byte is at the end of the byte array. To request the native\n\
4811byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4812\n\
4813The signed keyword-only argument indicates whether two's complement is\n\
4814used to represent the integer.");
4815
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004816static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4818 "Returns self, the complex conjugate of any int."},
4819 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4820 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004821#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004822 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4823 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004824#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 {"to_bytes", (PyCFunction)long_to_bytes,
4826 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4827 {"from_bytes", (PyCFunction)long_from_bytes,
4828 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4829 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4830 "Truncating an Integral returns itself."},
4831 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4832 "Flooring an Integral returns itself."},
4833 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4834 "Ceiling of an Integral returns itself."},
4835 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4836 "Rounding an Integral returns itself.\n"
4837 "Rounding with an ndigits argument also returns an integer."},
4838 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4839 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4840 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4841 "Returns size in memory, in bytes"},
4842 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004843};
4844
Guido van Rossumb43daf72007-08-01 18:08:08 +00004845static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004846 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004847 (getter)long_long, (setter)NULL,
4848 "the real part of a complex number",
4849 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004850 {"imag",
4851 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004852 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004853 NULL},
4854 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004855 (getter)long_long, (setter)NULL,
4856 "the numerator of a rational number in lowest terms",
4857 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004858 {"denominator",
4859 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004860 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004861 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004862 {NULL} /* Sentinel */
4863};
4864
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004865PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004866"int(x=0) -> integer\n\
4867int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004868\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004869Convert a number or string to an integer, or return 0 if no arguments\n\
4870are given. If x is a number, return x.__int__(). For floating point\n\
4871numbers, this truncates towards zero.\n\
4872\n\
4873If x is not a number or if base is given, then x must be a string,\n\
4874bytes, or bytearray instance representing an integer literal in the\n\
4875given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4876by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4877Base 0 means to interpret the base from the string as an integer literal.\n\
4878>>> int('0b100', base=0)\n\
48794");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004880
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004881static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004882 (binaryfunc)long_add, /*nb_add*/
4883 (binaryfunc)long_sub, /*nb_subtract*/
4884 (binaryfunc)long_mul, /*nb_multiply*/
4885 long_mod, /*nb_remainder*/
4886 long_divmod, /*nb_divmod*/
4887 long_pow, /*nb_power*/
4888 (unaryfunc)long_neg, /*nb_negative*/
4889 (unaryfunc)long_long, /*tp_positive*/
4890 (unaryfunc)long_abs, /*tp_absolute*/
4891 (inquiry)long_bool, /*tp_bool*/
4892 (unaryfunc)long_invert, /*nb_invert*/
4893 long_lshift, /*nb_lshift*/
4894 (binaryfunc)long_rshift, /*nb_rshift*/
4895 long_and, /*nb_and*/
4896 long_xor, /*nb_xor*/
4897 long_or, /*nb_or*/
4898 long_long, /*nb_int*/
4899 0, /*nb_reserved*/
4900 long_float, /*nb_float*/
4901 0, /* nb_inplace_add */
4902 0, /* nb_inplace_subtract */
4903 0, /* nb_inplace_multiply */
4904 0, /* nb_inplace_remainder */
4905 0, /* nb_inplace_power */
4906 0, /* nb_inplace_lshift */
4907 0, /* nb_inplace_rshift */
4908 0, /* nb_inplace_and */
4909 0, /* nb_inplace_xor */
4910 0, /* nb_inplace_or */
4911 long_div, /* nb_floor_divide */
4912 long_true_divide, /* nb_true_divide */
4913 0, /* nb_inplace_floor_divide */
4914 0, /* nb_inplace_true_divide */
4915 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004916};
4917
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004918PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004919 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4920 "int", /* tp_name */
4921 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4922 sizeof(digit), /* tp_itemsize */
4923 long_dealloc, /* tp_dealloc */
4924 0, /* tp_print */
4925 0, /* tp_getattr */
4926 0, /* tp_setattr */
4927 0, /* tp_reserved */
4928 long_to_decimal_string, /* tp_repr */
4929 &long_as_number, /* tp_as_number */
4930 0, /* tp_as_sequence */
4931 0, /* tp_as_mapping */
4932 (hashfunc)long_hash, /* tp_hash */
4933 0, /* tp_call */
4934 long_to_decimal_string, /* tp_str */
4935 PyObject_GenericGetAttr, /* tp_getattro */
4936 0, /* tp_setattro */
4937 0, /* tp_as_buffer */
4938 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4939 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4940 long_doc, /* tp_doc */
4941 0, /* tp_traverse */
4942 0, /* tp_clear */
4943 long_richcompare, /* tp_richcompare */
4944 0, /* tp_weaklistoffset */
4945 0, /* tp_iter */
4946 0, /* tp_iternext */
4947 long_methods, /* tp_methods */
4948 0, /* tp_members */
4949 long_getset, /* tp_getset */
4950 0, /* tp_base */
4951 0, /* tp_dict */
4952 0, /* tp_descr_get */
4953 0, /* tp_descr_set */
4954 0, /* tp_dictoffset */
4955 0, /* tp_init */
4956 0, /* tp_alloc */
4957 long_new, /* tp_new */
4958 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004959};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004960
Mark Dickinsonbd792642009-03-18 20:06:12 +00004961static PyTypeObject Int_InfoType;
4962
4963PyDoc_STRVAR(int_info__doc__,
4964"sys.int_info\n\
4965\n\
4966A struct sequence that holds information about Python's\n\
4967internal representation of integers. The attributes are read only.");
4968
4969static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004971 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004972 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004973};
4974
4975static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 "sys.int_info", /* name */
4977 int_info__doc__, /* doc */
4978 int_info_fields, /* fields */
4979 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004980};
4981
4982PyObject *
4983PyLong_GetInfo(void)
4984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 PyObject* int_info;
4986 int field = 0;
4987 int_info = PyStructSequence_New(&Int_InfoType);
4988 if (int_info == NULL)
4989 return NULL;
4990 PyStructSequence_SET_ITEM(int_info, field++,
4991 PyLong_FromLong(PyLong_SHIFT));
4992 PyStructSequence_SET_ITEM(int_info, field++,
4993 PyLong_FromLong(sizeof(digit)));
4994 if (PyErr_Occurred()) {
4995 Py_CLEAR(int_info);
4996 return NULL;
4997 }
4998 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004999}
5000
Guido van Rossumddefaf32007-01-14 03:31:43 +00005001int
5002_PyLong_Init(void)
5003{
5004#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005005 int ival, size;
5006 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5009 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5010 if (Py_TYPE(v) == &PyLong_Type) {
5011 /* The element is already initialized, most likely
5012 * the Python interpreter was initialized before.
5013 */
5014 Py_ssize_t refcnt;
5015 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005017 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5018 _Py_NewReference(op);
5019 /* _Py_NewReference sets the ref count to 1 but
5020 * the ref count might be larger. Set the refcnt
5021 * to the original refcnt + 1 */
5022 Py_REFCNT(op) = refcnt + 1;
5023 assert(Py_SIZE(op) == size);
5024 assert(v->ob_digit[0] == abs(ival));
5025 }
5026 else {
5027 PyObject_INIT(v, &PyLong_Type);
5028 }
5029 Py_SIZE(v) = size;
5030 v->ob_digit[0] = abs(ival);
5031 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005032#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 /* initialize int_info */
5034 if (Int_InfoType.tp_name == 0)
5035 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005038}
5039
5040void
5041PyLong_Fini(void)
5042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 /* Integers are currently statically allocated. Py_DECREF is not
5044 needed, but Python must forget about the reference or multiple
5045 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005046#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 int i;
5048 PyLongObject *v = small_ints;
5049 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5050 _Py_DEC_REFTOTAL;
5051 _Py_ForgetReference((PyObject*)v);
5052 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005053#endif
5054}