blob: a894ec5a642327ac38d42154f8f6984cfddf39fa [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 */
Victor Stinner8aed6f12013-07-17 22:31:17 +020073Py_LOCAL_INLINE(void)
74_PyLong_Negate(PyLongObject **x_p)
75{
76 PyLongObject *x;
77
78 x = (PyLongObject *)*x_p;
79 if (Py_REFCNT(x) == 1) {
80 Py_SIZE(x) = -Py_SIZE(x);
81 return;
82 }
83
84 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
85 Py_DECREF(x);
86}
87
Tim Peters5af4e6c2002-08-12 02:31:19 +000088/* For long multiplication, use the O(N**2) school algorithm unless
89 * both operands contain more than KARATSUBA_CUTOFF digits (this
90 * being an internal Python long digit, in base BASE).
91 */
Tim Peters0973b992004-08-29 22:16:50 +000092#define KARATSUBA_CUTOFF 70
93#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000094
Tim Peters47e52ee2004-08-30 02:44:38 +000095/* For exponentiation, use the binary left-to-right algorithm
96 * unless the exponent contains more than FIVEARY_CUTOFF digits.
97 * In that case, do 5 bits at a time. The potential drawback is that
98 * a table of 2**5 intermediate results is computed.
99 */
100#define FIVEARY_CUTOFF 8
101
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000102#define SIGCHECK(PyTryBlock) \
103 do { \
104 if (PyErr_CheckSignals()) PyTryBlock \
105 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000106
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000107/* Normalize (remove leading zeros from) a long int object.
108 Doesn't attempt to free the storage--in most cases, due to the nature
109 of the algorithms used, this could save at most be one word anyway. */
110
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000112long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 Py_ssize_t j = ABS(Py_SIZE(v));
115 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 while (i > 0 && v->ob_digit[i-1] == 0)
118 --i;
119 if (i != j)
120 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
121 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000122}
123
124/* Allocate a new long int object with size digits.
125 Return NULL and set exception if we run out of memory. */
126
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000127#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000129
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000131_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 PyLongObject *result;
134 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
135 sizeof(digit)*size. Previous incarnations of this code used
136 sizeof(PyVarObject) instead of the offsetof, but this risks being
137 incorrect in the presence of padding between the PyVarObject header
138 and the digits. */
139 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
140 PyErr_SetString(PyExc_OverflowError,
141 "too many digits in integer");
142 return NULL;
143 }
144 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
145 size*sizeof(digit));
146 if (!result) {
147 PyErr_NoMemory();
148 return NULL;
149 }
150 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000151}
152
Tim Peters64b5ce32001-09-10 20:52:51 +0000153PyObject *
154_PyLong_Copy(PyLongObject *src)
155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 PyLongObject *result;
157 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 assert(src != NULL);
160 i = Py_SIZE(src);
161 if (i < 0)
162 i = -(i);
163 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100164 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 CHECK_SMALL_INT(ival);
166 }
167 result = _PyLong_New(i);
168 if (result != NULL) {
169 Py_SIZE(result) = Py_SIZE(src);
170 while (--i >= 0)
171 result->ob_digit[i] = src->ob_digit[i];
172 }
173 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000174}
175
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000176/* Create a new long int object from a C long int */
177
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000179PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 PyLongObject *v;
182 unsigned long abs_ival;
183 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
184 int ndigits = 0;
185 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 if (ival < 0) {
190 /* negate: can't write this as abs_ival = -ival since that
191 invokes undefined behaviour when ival is LONG_MIN */
192 abs_ival = 0U-(unsigned long)ival;
193 sign = -1;
194 }
195 else {
196 abs_ival = (unsigned long)ival;
197 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 /* Fast path for single-digit ints */
200 if (!(abs_ival >> PyLong_SHIFT)) {
201 v = _PyLong_New(1);
202 if (v) {
203 Py_SIZE(v) = sign;
204 v->ob_digit[0] = Py_SAFE_DOWNCAST(
205 abs_ival, unsigned long, digit);
206 }
207 return (PyObject*)v;
208 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000209
Mark Dickinson249b8982009-04-27 19:41:00 +0000210#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 /* 2 digits */
212 if (!(abs_ival >> 2*PyLong_SHIFT)) {
213 v = _PyLong_New(2);
214 if (v) {
215 Py_SIZE(v) = 2*sign;
216 v->ob_digit[0] = Py_SAFE_DOWNCAST(
217 abs_ival & PyLong_MASK, unsigned long, digit);
218 v->ob_digit[1] = Py_SAFE_DOWNCAST(
219 abs_ival >> PyLong_SHIFT, unsigned long, digit);
220 }
221 return (PyObject*)v;
222 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000223#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 /* Larger numbers: loop to determine number of digits */
226 t = abs_ival;
227 while (t) {
228 ++ndigits;
229 t >>= PyLong_SHIFT;
230 }
231 v = _PyLong_New(ndigits);
232 if (v != NULL) {
233 digit *p = v->ob_digit;
234 Py_SIZE(v) = ndigits*sign;
235 t = abs_ival;
236 while (t) {
237 *p++ = Py_SAFE_DOWNCAST(
238 t & PyLong_MASK, unsigned long, digit);
239 t >>= PyLong_SHIFT;
240 }
241 }
242 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000243}
244
Guido van Rossum53756b11997-01-03 17:14:46 +0000245/* Create a new long int object from a C unsigned long int */
246
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000247PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000248PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 PyLongObject *v;
251 unsigned long t;
252 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 if (ival < PyLong_BASE)
255 return PyLong_FromLong(ival);
256 /* Count the number of Python digits. */
257 t = (unsigned long)ival;
258 while (t) {
259 ++ndigits;
260 t >>= PyLong_SHIFT;
261 }
262 v = _PyLong_New(ndigits);
263 if (v != NULL) {
264 digit *p = v->ob_digit;
265 Py_SIZE(v) = ndigits;
266 while (ival) {
267 *p++ = (digit)(ival & PyLong_MASK);
268 ival >>= PyLong_SHIFT;
269 }
270 }
271 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000272}
273
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000274/* Create a new long int object from a C double */
275
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000276PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000277PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 PyLongObject *v;
280 double frac;
281 int i, ndig, expo, neg;
282 neg = 0;
283 if (Py_IS_INFINITY(dval)) {
284 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000285 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return NULL;
287 }
288 if (Py_IS_NAN(dval)) {
289 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000290 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 return NULL;
292 }
293 if (dval < 0.0) {
294 neg = 1;
295 dval = -dval;
296 }
297 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
298 if (expo <= 0)
299 return PyLong_FromLong(0L);
300 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
301 v = _PyLong_New(ndig);
302 if (v == NULL)
303 return NULL;
304 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
305 for (i = ndig; --i >= 0; ) {
306 digit bits = (digit)frac;
307 v->ob_digit[i] = bits;
308 frac = frac - (double)bits;
309 frac = ldexp(frac, PyLong_SHIFT);
310 }
311 if (neg)
312 Py_SIZE(v) = -(Py_SIZE(v));
313 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000314}
315
Thomas Wouters89f507f2006-12-13 04:49:30 +0000316/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
317 * anything about what happens when a signed integer operation overflows,
318 * and some compilers think they're doing you a favor by being "clever"
319 * then. The bit pattern for the largest postive signed long is
320 * (unsigned long)LONG_MAX, and for the smallest negative signed long
321 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
322 * However, some other compilers warn about applying unary minus to an
323 * unsigned operand. Hence the weird "0-".
324 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
326#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000327
Mark Dickinson8d48b432011-10-23 20:47:14 +0100328/* Get a C long int from a long int object or any object that has an __int__
329 method.
330
331 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
332 the result. Otherwise *overflow is 0.
333
334 For other errors (e.g., TypeError), return -1 and set an error condition.
335 In this case *overflow will be 0.
336*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000337
338long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000339PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 /* This version by Tim Peters */
342 register PyLongObject *v;
343 unsigned long x, prev;
344 long res;
345 Py_ssize_t i;
346 int sign;
347 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 *overflow = 0;
350 if (vv == NULL) {
351 PyErr_BadInternalCall();
352 return -1;
353 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (!PyLong_Check(vv)) {
356 PyNumberMethods *nb;
357 nb = vv->ob_type->tp_as_number;
358 if (nb == NULL || nb->nb_int == NULL) {
359 PyErr_SetString(PyExc_TypeError,
360 "an integer is required");
361 return -1;
362 }
363 vv = (*nb->nb_int) (vv);
364 if (vv == NULL)
365 return -1;
366 do_decref = 1;
367 if (!PyLong_Check(vv)) {
368 Py_DECREF(vv);
369 PyErr_SetString(PyExc_TypeError,
370 "nb_int should return int object");
371 return -1;
372 }
373 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 res = -1;
376 v = (PyLongObject *)vv;
377 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 switch (i) {
380 case -1:
381 res = -(sdigit)v->ob_digit[0];
382 break;
383 case 0:
384 res = 0;
385 break;
386 case 1:
387 res = v->ob_digit[0];
388 break;
389 default:
390 sign = 1;
391 x = 0;
392 if (i < 0) {
393 sign = -1;
394 i = -(i);
395 }
396 while (--i >= 0) {
397 prev = x;
398 x = (x << PyLong_SHIFT) | v->ob_digit[i];
399 if ((x >> PyLong_SHIFT) != prev) {
400 *overflow = sign;
401 goto exit;
402 }
403 }
404 /* Haven't lost any bits, but casting to long requires extra
405 * care (see comment above).
406 */
407 if (x <= (unsigned long)LONG_MAX) {
408 res = (long)x * sign;
409 }
410 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
411 res = LONG_MIN;
412 }
413 else {
414 *overflow = sign;
415 /* res is already set to -1 */
416 }
417 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000418 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (do_decref) {
420 Py_DECREF(vv);
421 }
422 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000423}
424
Mark Dickinson8d48b432011-10-23 20:47:14 +0100425/* Get a C long int from a long int object or any object that has an __int__
426 method. Return -1 and set an error if overflow occurs. */
427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000429PyLong_AsLong(PyObject *obj)
430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 int overflow;
432 long result = PyLong_AsLongAndOverflow(obj, &overflow);
433 if (overflow) {
434 /* XXX: could be cute and give a different
435 message for overflow == -1 */
436 PyErr_SetString(PyExc_OverflowError,
437 "Python int too large to convert to C long");
438 }
439 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000440}
441
Serhiy Storchaka78980432013-01-15 01:12:17 +0200442/* Get a C int from a long int object or any object that has an __int__
443 method. Return -1 and set an error if overflow occurs. */
444
445int
446_PyLong_AsInt(PyObject *obj)
447{
448 int overflow;
449 long result = PyLong_AsLongAndOverflow(obj, &overflow);
450 if (overflow || result > INT_MAX || result < INT_MIN) {
451 /* XXX: could be cute and give a different
452 message for overflow == -1 */
453 PyErr_SetString(PyExc_OverflowError,
454 "Python int too large to convert to C int");
455 return -1;
456 }
457 return (int)result;
458}
459
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000460/* Get a Py_ssize_t from a long int object.
461 Returns -1 and sets an error condition if overflow occurs. */
462
463Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000464PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 register PyLongObject *v;
466 size_t x, prev;
467 Py_ssize_t i;
468 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (vv == NULL) {
471 PyErr_BadInternalCall();
472 return -1;
473 }
474 if (!PyLong_Check(vv)) {
475 PyErr_SetString(PyExc_TypeError, "an integer is required");
476 return -1;
477 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 v = (PyLongObject *)vv;
480 i = Py_SIZE(v);
481 switch (i) {
482 case -1: return -(sdigit)v->ob_digit[0];
483 case 0: return 0;
484 case 1: return v->ob_digit[0];
485 }
486 sign = 1;
487 x = 0;
488 if (i < 0) {
489 sign = -1;
490 i = -(i);
491 }
492 while (--i >= 0) {
493 prev = x;
494 x = (x << PyLong_SHIFT) | v->ob_digit[i];
495 if ((x >> PyLong_SHIFT) != prev)
496 goto overflow;
497 }
498 /* Haven't lost any bits, but casting to a signed type requires
499 * extra care (see comment above).
500 */
501 if (x <= (size_t)PY_SSIZE_T_MAX) {
502 return (Py_ssize_t)x * sign;
503 }
504 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
505 return PY_SSIZE_T_MIN;
506 }
507 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000508
Mark Dickinson22b20182010-05-10 21:27:53 +0000509 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyErr_SetString(PyExc_OverflowError,
511 "Python int too large to convert to C ssize_t");
512 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000513}
514
Guido van Rossumd8c80482002-08-13 00:24:58 +0000515/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000516 Returns -1 and sets an error condition if overflow occurs. */
517
518unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000519PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 register PyLongObject *v;
522 unsigned long x, prev;
523 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 if (vv == NULL) {
526 PyErr_BadInternalCall();
527 return (unsigned long)-1;
528 }
529 if (!PyLong_Check(vv)) {
530 PyErr_SetString(PyExc_TypeError, "an integer is required");
531 return (unsigned long)-1;
532 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 v = (PyLongObject *)vv;
535 i = Py_SIZE(v);
536 x = 0;
537 if (i < 0) {
538 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000539 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 return (unsigned long) -1;
541 }
542 switch (i) {
543 case 0: return 0;
544 case 1: return v->ob_digit[0];
545 }
546 while (--i >= 0) {
547 prev = x;
548 x = (x << PyLong_SHIFT) | v->ob_digit[i];
549 if ((x >> PyLong_SHIFT) != prev) {
550 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000551 "python int too large to convert "
552 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return (unsigned long) -1;
554 }
555 }
556 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000557}
558
Stefan Krahb77c6c62011-09-12 16:22:47 +0200559/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
560 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000561
562size_t
563PyLong_AsSize_t(PyObject *vv)
564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 register PyLongObject *v;
566 size_t x, prev;
567 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 if (vv == NULL) {
570 PyErr_BadInternalCall();
571 return (size_t) -1;
572 }
573 if (!PyLong_Check(vv)) {
574 PyErr_SetString(PyExc_TypeError, "an integer is required");
575 return (size_t)-1;
576 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 v = (PyLongObject *)vv;
579 i = Py_SIZE(v);
580 x = 0;
581 if (i < 0) {
582 PyErr_SetString(PyExc_OverflowError,
583 "can't convert negative value to size_t");
584 return (size_t) -1;
585 }
586 switch (i) {
587 case 0: return 0;
588 case 1: return v->ob_digit[0];
589 }
590 while (--i >= 0) {
591 prev = x;
592 x = (x << PyLong_SHIFT) | v->ob_digit[i];
593 if ((x >> PyLong_SHIFT) != prev) {
594 PyErr_SetString(PyExc_OverflowError,
595 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200596 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 }
598 }
599 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000600}
601
Thomas Hellera4ea6032003-04-17 18:55:45 +0000602/* Get a C unsigned long int from a long int object, ignoring the high bits.
603 Returns -1 and sets an error condition if an error occurs. */
604
Guido van Rossumddefaf32007-01-14 03:31:43 +0000605static unsigned long
606_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 register PyLongObject *v;
609 unsigned long x;
610 Py_ssize_t i;
611 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (vv == NULL || !PyLong_Check(vv)) {
614 PyErr_BadInternalCall();
615 return (unsigned long) -1;
616 }
617 v = (PyLongObject *)vv;
618 i = Py_SIZE(v);
619 switch (i) {
620 case 0: return 0;
621 case 1: return v->ob_digit[0];
622 }
623 sign = 1;
624 x = 0;
625 if (i < 0) {
626 sign = -1;
627 i = -i;
628 }
629 while (--i >= 0) {
630 x = (x << PyLong_SHIFT) | v->ob_digit[i];
631 }
632 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000633}
634
Guido van Rossumddefaf32007-01-14 03:31:43 +0000635unsigned long
636PyLong_AsUnsignedLongMask(register PyObject *op)
637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyNumberMethods *nb;
639 PyLongObject *lo;
640 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if (op && PyLong_Check(op))
643 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
646 nb->nb_int == NULL) {
647 PyErr_SetString(PyExc_TypeError, "an integer is required");
648 return (unsigned long)-1;
649 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 lo = (PyLongObject*) (*nb->nb_int) (op);
652 if (lo == NULL)
653 return (unsigned long)-1;
654 if (PyLong_Check(lo)) {
655 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
656 Py_DECREF(lo);
657 if (PyErr_Occurred())
658 return (unsigned long)-1;
659 return val;
660 }
661 else
662 {
663 Py_DECREF(lo);
664 PyErr_SetString(PyExc_TypeError,
665 "nb_int should return int object");
666 return (unsigned long)-1;
667 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000668}
669
Tim Peters5b8132f2003-01-31 15:52:05 +0000670int
671_PyLong_Sign(PyObject *vv)
672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 assert(v != NULL);
676 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000679}
680
Tim Petersbaefd9e2003-01-28 20:37:45 +0000681size_t
682_PyLong_NumBits(PyObject *vv)
683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 PyLongObject *v = (PyLongObject *)vv;
685 size_t result = 0;
686 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 assert(v != NULL);
689 assert(PyLong_Check(v));
690 ndigits = ABS(Py_SIZE(v));
691 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
692 if (ndigits > 0) {
693 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100694 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100696 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 do {
698 ++result;
699 if (result == 0)
700 goto Overflow;
701 msd >>= 1;
702 } while (msd);
703 }
704 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000705
Mark Dickinson22b20182010-05-10 21:27:53 +0000706 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
708 "to express in a platform size_t");
709 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000710}
711
Tim Peters2a9b3672001-06-11 21:23:58 +0000712PyObject *
713_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000715{
Mark Dickinson22b20182010-05-10 21:27:53 +0000716 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 int incr; /* direction to move pstartbyte */
718 const unsigned char* pendbyte; /* MSB of bytes */
719 size_t numsignificantbytes; /* number of bytes that matter */
720 Py_ssize_t ndigits; /* number of Python long digits */
721 PyLongObject* v; /* result */
722 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (n == 0)
725 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 if (little_endian) {
728 pstartbyte = bytes;
729 pendbyte = bytes + n - 1;
730 incr = 1;
731 }
732 else {
733 pstartbyte = bytes + n - 1;
734 pendbyte = bytes;
735 incr = -1;
736 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 if (is_signed)
739 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200742 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 is positive, and leading 0xff bytes if negative. */
744 {
745 size_t i;
746 const unsigned char* p = pendbyte;
747 const int pincr = -incr; /* search MSB to LSB */
748 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 for (i = 0; i < n; ++i, p += pincr) {
751 if (*p != insignficant)
752 break;
753 }
754 numsignificantbytes = n - i;
755 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
756 actually has 2 significant bytes. OTOH, 0xff0001 ==
757 -0x00ffff, so we wouldn't *need* to bump it there; but we
758 do for 0xffff = -0x0001. To be safe without bothering to
759 check every case, bump it regardless. */
760 if (is_signed && numsignificantbytes < n)
761 ++numsignificantbytes;
762 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 /* How many Python long digits do we need? We have
765 8*numsignificantbytes bits, and each Python long digit has
766 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
767 /* catch overflow before it happens */
768 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
769 PyErr_SetString(PyExc_OverflowError,
770 "byte array too long to convert to int");
771 return NULL;
772 }
773 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
774 v = _PyLong_New(ndigits);
775 if (v == NULL)
776 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 /* Copy the bits over. The tricky parts are computing 2's-comp on
779 the fly for signed numbers, and dealing with the mismatch between
780 8-bit bytes and (probably) 15-bit Python digits.*/
781 {
782 size_t i;
783 twodigits carry = 1; /* for 2's-comp calculation */
784 twodigits accum = 0; /* sliding register */
785 unsigned int accumbits = 0; /* number of bits in accum */
786 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
789 twodigits thisbyte = *p;
790 /* Compute correction for 2's comp, if needed. */
791 if (is_signed) {
792 thisbyte = (0xff ^ thisbyte) + carry;
793 carry = thisbyte >> 8;
794 thisbyte &= 0xff;
795 }
796 /* Because we're going LSB to MSB, thisbyte is
797 more significant than what's already in accum,
798 so needs to be prepended to accum. */
799 accum |= (twodigits)thisbyte << accumbits;
800 accumbits += 8;
801 if (accumbits >= PyLong_SHIFT) {
802 /* There's enough to fill a Python digit. */
803 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000804 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 ++idigit;
806 accum >>= PyLong_SHIFT;
807 accumbits -= PyLong_SHIFT;
808 assert(accumbits < PyLong_SHIFT);
809 }
810 }
811 assert(accumbits < PyLong_SHIFT);
812 if (accumbits) {
813 assert(idigit < ndigits);
814 v->ob_digit[idigit] = (digit)accum;
815 ++idigit;
816 }
817 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 Py_SIZE(v) = is_signed ? -idigit : idigit;
820 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000821}
822
823int
824_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 unsigned char* bytes, size_t n,
826 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000829 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000831 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
833 digit carry; /* for computing 2's-comp */
834 size_t j; /* # bytes filled */
835 unsigned char* p; /* pointer to next byte in bytes */
836 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if (Py_SIZE(v) < 0) {
841 ndigits = -(Py_SIZE(v));
842 if (!is_signed) {
843 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000844 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 return -1;
846 }
847 do_twos_comp = 1;
848 }
849 else {
850 ndigits = Py_SIZE(v);
851 do_twos_comp = 0;
852 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 if (little_endian) {
855 p = bytes;
856 pincr = 1;
857 }
858 else {
859 p = bytes + n - 1;
860 pincr = -1;
861 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 /* Copy over all the Python digits.
864 It's crucial that every Python digit except for the MSD contribute
865 exactly PyLong_SHIFT bits to the total, so first assert that the long is
866 normalized. */
867 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
868 j = 0;
869 accum = 0;
870 accumbits = 0;
871 carry = do_twos_comp ? 1 : 0;
872 for (i = 0; i < ndigits; ++i) {
873 digit thisdigit = v->ob_digit[i];
874 if (do_twos_comp) {
875 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
876 carry = thisdigit >> PyLong_SHIFT;
877 thisdigit &= PyLong_MASK;
878 }
879 /* Because we're going LSB to MSB, thisdigit is more
880 significant than what's already in accum, so needs to be
881 prepended to accum. */
882 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 /* The most-significant digit may be (probably is) at least
885 partly empty. */
886 if (i == ndigits - 1) {
887 /* Count # of sign bits -- they needn't be stored,
888 * although for signed conversion we need later to
889 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000890 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 while (s != 0) {
892 s >>= 1;
893 accumbits++;
894 }
895 }
896 else
897 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* Store as many bytes as possible. */
900 while (accumbits >= 8) {
901 if (j >= n)
902 goto Overflow;
903 ++j;
904 *p = (unsigned char)(accum & 0xff);
905 p += pincr;
906 accumbits -= 8;
907 accum >>= 8;
908 }
909 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 /* Store the straggler (if any). */
912 assert(accumbits < 8);
913 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
914 if (accumbits > 0) {
915 if (j >= n)
916 goto Overflow;
917 ++j;
918 if (do_twos_comp) {
919 /* Fill leading bits of the byte with sign bits
920 (appropriately pretending that the long had an
921 infinite supply of sign bits). */
922 accum |= (~(twodigits)0) << accumbits;
923 }
924 *p = (unsigned char)(accum & 0xff);
925 p += pincr;
926 }
927 else if (j == n && n > 0 && is_signed) {
928 /* The main loop filled the byte array exactly, so the code
929 just above didn't get to ensure there's a sign bit, and the
930 loop below wouldn't add one either. Make sure a sign bit
931 exists. */
932 unsigned char msb = *(p - pincr);
933 int sign_bit_set = msb >= 0x80;
934 assert(accumbits == 0);
935 if (sign_bit_set == do_twos_comp)
936 return 0;
937 else
938 goto Overflow;
939 }
Tim Peters05607ad2001-06-13 21:01:27 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Fill remaining bytes with copies of the sign bit. */
942 {
943 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
944 for ( ; j < n; ++j, p += pincr)
945 *p = signbyte;
946 }
Tim Peters05607ad2001-06-13 21:01:27 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000949
Mark Dickinson22b20182010-05-10 21:27:53 +0000950 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
952 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000953
Tim Peters2a9b3672001-06-11 21:23:58 +0000954}
955
Mark Dickinson8d48b432011-10-23 20:47:14 +0100956/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000957
958PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000959PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000960{
Mark Dickinson91044792012-10-18 19:21:43 +0100961#if SIZEOF_VOID_P <= SIZEOF_LONG
Mark Dickinson91044792012-10-18 19:21:43 +0100962 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
963#else
964
Tim Peters70128a12001-06-16 08:48:40 +0000965#ifndef HAVE_LONG_LONG
966# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
967#endif
968#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000969# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000970#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100972#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000973
Guido van Rossum78694d91998-09-18 14:14:13 +0000974}
975
Mark Dickinson8d48b432011-10-23 20:47:14 +0100976/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000977
978void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000979PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000980{
Tim Peters70128a12001-06-16 08:48:40 +0000981#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
985 x = PyLong_AsLong(vv);
986 else
987 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000988#else
Tim Peters70128a12001-06-16 08:48:40 +0000989
990#ifndef HAVE_LONG_LONG
991# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
992#endif
993#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000994# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000995#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
999 x = PyLong_AsLongLong(vv);
1000 else
1001 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001002
1003#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (x == -1 && PyErr_Occurred())
1006 return NULL;
1007 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001008}
1009
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001010#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001011
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001012/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001013 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001014 */
1015
Mark Dickinson22b20182010-05-10 21:27:53 +00001016#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001017
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001018/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001019
1020PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001021PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 PyLongObject *v;
1024 unsigned PY_LONG_LONG abs_ival;
1025 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1026 int ndigits = 0;
1027 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 CHECK_SMALL_INT(ival);
1030 if (ival < 0) {
1031 /* avoid signed overflow on negation; see comments
1032 in PyLong_FromLong above. */
1033 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1034 negative = 1;
1035 }
1036 else {
1037 abs_ival = (unsigned PY_LONG_LONG)ival;
1038 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 /* Count the number of Python digits.
1041 We used to pick 5 ("big enough for anything"), but that's a
1042 waste of time and space given that 5*15 = 75 bits are rarely
1043 needed. */
1044 t = abs_ival;
1045 while (t) {
1046 ++ndigits;
1047 t >>= PyLong_SHIFT;
1048 }
1049 v = _PyLong_New(ndigits);
1050 if (v != NULL) {
1051 digit *p = v->ob_digit;
1052 Py_SIZE(v) = negative ? -ndigits : ndigits;
1053 t = abs_ival;
1054 while (t) {
1055 *p++ = (digit)(t & PyLong_MASK);
1056 t >>= PyLong_SHIFT;
1057 }
1058 }
1059 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001060}
1061
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001062/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001063
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001064PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001065PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyLongObject *v;
1068 unsigned PY_LONG_LONG t;
1069 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (ival < PyLong_BASE)
1072 return PyLong_FromLong((long)ival);
1073 /* Count the number of Python digits. */
1074 t = (unsigned PY_LONG_LONG)ival;
1075 while (t) {
1076 ++ndigits;
1077 t >>= PyLong_SHIFT;
1078 }
1079 v = _PyLong_New(ndigits);
1080 if (v != NULL) {
1081 digit *p = v->ob_digit;
1082 Py_SIZE(v) = ndigits;
1083 while (ival) {
1084 *p++ = (digit)(ival & PyLong_MASK);
1085 ival >>= PyLong_SHIFT;
1086 }
1087 }
1088 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001089}
1090
Martin v. Löwis18e16552006-02-15 17:27:45 +00001091/* Create a new long int object from a C Py_ssize_t. */
1092
1093PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001094PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 PyLongObject *v;
1097 size_t abs_ival;
1098 size_t t; /* unsigned so >> doesn't propagate sign bit */
1099 int ndigits = 0;
1100 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 CHECK_SMALL_INT(ival);
1103 if (ival < 0) {
1104 /* avoid signed overflow when ival = SIZE_T_MIN */
1105 abs_ival = (size_t)(-1-ival)+1;
1106 negative = 1;
1107 }
1108 else {
1109 abs_ival = (size_t)ival;
1110 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 /* Count the number of Python digits. */
1113 t = abs_ival;
1114 while (t) {
1115 ++ndigits;
1116 t >>= PyLong_SHIFT;
1117 }
1118 v = _PyLong_New(ndigits);
1119 if (v != NULL) {
1120 digit *p = v->ob_digit;
1121 Py_SIZE(v) = negative ? -ndigits : ndigits;
1122 t = abs_ival;
1123 while (t) {
1124 *p++ = (digit)(t & PyLong_MASK);
1125 t >>= PyLong_SHIFT;
1126 }
1127 }
1128 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001129}
1130
1131/* Create a new long int object from a C size_t. */
1132
1133PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001134PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 PyLongObject *v;
1137 size_t t;
1138 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 if (ival < PyLong_BASE)
1141 return PyLong_FromLong((long)ival);
1142 /* Count the number of Python digits. */
1143 t = ival;
1144 while (t) {
1145 ++ndigits;
1146 t >>= PyLong_SHIFT;
1147 }
1148 v = _PyLong_New(ndigits);
1149 if (v != NULL) {
1150 digit *p = v->ob_digit;
1151 Py_SIZE(v) = ndigits;
1152 while (ival) {
1153 *p++ = (digit)(ival & PyLong_MASK);
1154 ival >>= PyLong_SHIFT;
1155 }
1156 }
1157 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001158}
1159
Mark Dickinson8d48b432011-10-23 20:47:14 +01001160/* Get a C long long int from a long int object or any object that has an
1161 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001162
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001163PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001164PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 PyLongObject *v;
1167 PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (vv == NULL) {
1171 PyErr_BadInternalCall();
1172 return -1;
1173 }
1174 if (!PyLong_Check(vv)) {
1175 PyNumberMethods *nb;
1176 PyObject *io;
1177 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1178 nb->nb_int == NULL) {
1179 PyErr_SetString(PyExc_TypeError, "an integer is required");
1180 return -1;
1181 }
1182 io = (*nb->nb_int) (vv);
1183 if (io == NULL)
1184 return -1;
1185 if (PyLong_Check(io)) {
1186 bytes = PyLong_AsLongLong(io);
1187 Py_DECREF(io);
1188 return bytes;
1189 }
1190 Py_DECREF(io);
1191 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1192 return -1;
1193 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 v = (PyLongObject*)vv;
1196 switch(Py_SIZE(v)) {
1197 case -1: return -(sdigit)v->ob_digit[0];
1198 case 0: return 0;
1199 case 1: return v->ob_digit[0];
1200 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001201 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001202 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1205 if (res < 0)
1206 return (PY_LONG_LONG)-1;
1207 else
1208 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001209}
1210
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001211/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001212 Return -1 and set an error if overflow occurs. */
1213
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001214unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001215PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 PyLongObject *v;
1218 unsigned PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001220
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001221 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 PyErr_BadInternalCall();
1223 return (unsigned PY_LONG_LONG)-1;
1224 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001225 if (!PyLong_Check(vv)) {
1226 PyErr_SetString(PyExc_TypeError, "an integer is required");
1227 return (unsigned PY_LONG_LONG)-1;
1228 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 v = (PyLongObject*)vv;
1231 switch(Py_SIZE(v)) {
1232 case 0: return 0;
1233 case 1: return v->ob_digit[0];
1234 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001235
Mark Dickinson22b20182010-05-10 21:27:53 +00001236 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001237 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1240 if (res < 0)
1241 return (unsigned PY_LONG_LONG)res;
1242 else
1243 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001244}
Tim Petersd1a7da62001-06-13 00:35:57 +00001245
Thomas Hellera4ea6032003-04-17 18:55:45 +00001246/* Get a C unsigned long int from a long int object, ignoring the high bits.
1247 Returns -1 and sets an error condition if an error occurs. */
1248
Guido van Rossumddefaf32007-01-14 03:31:43 +00001249static unsigned PY_LONG_LONG
1250_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 register PyLongObject *v;
1253 unsigned PY_LONG_LONG x;
1254 Py_ssize_t i;
1255 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (vv == NULL || !PyLong_Check(vv)) {
1258 PyErr_BadInternalCall();
1259 return (unsigned long) -1;
1260 }
1261 v = (PyLongObject *)vv;
1262 switch(Py_SIZE(v)) {
1263 case 0: return 0;
1264 case 1: return v->ob_digit[0];
1265 }
1266 i = Py_SIZE(v);
1267 sign = 1;
1268 x = 0;
1269 if (i < 0) {
1270 sign = -1;
1271 i = -i;
1272 }
1273 while (--i >= 0) {
1274 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1275 }
1276 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001277}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001278
1279unsigned PY_LONG_LONG
1280PyLong_AsUnsignedLongLongMask(register PyObject *op)
1281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 PyNumberMethods *nb;
1283 PyLongObject *lo;
1284 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (op && PyLong_Check(op))
1287 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1290 nb->nb_int == NULL) {
1291 PyErr_SetString(PyExc_TypeError, "an integer is required");
1292 return (unsigned PY_LONG_LONG)-1;
1293 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 lo = (PyLongObject*) (*nb->nb_int) (op);
1296 if (lo == NULL)
1297 return (unsigned PY_LONG_LONG)-1;
1298 if (PyLong_Check(lo)) {
1299 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1300 Py_DECREF(lo);
1301 if (PyErr_Occurred())
1302 return (unsigned PY_LONG_LONG)-1;
1303 return val;
1304 }
1305 else
1306 {
1307 Py_DECREF(lo);
1308 PyErr_SetString(PyExc_TypeError,
1309 "nb_int should return int object");
1310 return (unsigned PY_LONG_LONG)-1;
1311 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001312}
Tim Petersd1a7da62001-06-13 00:35:57 +00001313
Mark Dickinson8d48b432011-10-23 20:47:14 +01001314/* Get a C long long int from a long int object or any object that has an
1315 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001316
Mark Dickinson8d48b432011-10-23 20:47:14 +01001317 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1318 the result. Otherwise *overflow is 0.
1319
1320 For other errors (e.g., TypeError), return -1 and set an error condition.
1321 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001322*/
1323
1324PY_LONG_LONG
1325PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 /* This version by Tim Peters */
1328 register PyLongObject *v;
1329 unsigned PY_LONG_LONG x, prev;
1330 PY_LONG_LONG res;
1331 Py_ssize_t i;
1332 int sign;
1333 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 *overflow = 0;
1336 if (vv == NULL) {
1337 PyErr_BadInternalCall();
1338 return -1;
1339 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 if (!PyLong_Check(vv)) {
1342 PyNumberMethods *nb;
1343 nb = vv->ob_type->tp_as_number;
1344 if (nb == NULL || nb->nb_int == NULL) {
1345 PyErr_SetString(PyExc_TypeError,
1346 "an integer is required");
1347 return -1;
1348 }
1349 vv = (*nb->nb_int) (vv);
1350 if (vv == NULL)
1351 return -1;
1352 do_decref = 1;
1353 if (!PyLong_Check(vv)) {
1354 Py_DECREF(vv);
1355 PyErr_SetString(PyExc_TypeError,
1356 "nb_int should return int object");
1357 return -1;
1358 }
1359 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 res = -1;
1362 v = (PyLongObject *)vv;
1363 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 switch (i) {
1366 case -1:
1367 res = -(sdigit)v->ob_digit[0];
1368 break;
1369 case 0:
1370 res = 0;
1371 break;
1372 case 1:
1373 res = v->ob_digit[0];
1374 break;
1375 default:
1376 sign = 1;
1377 x = 0;
1378 if (i < 0) {
1379 sign = -1;
1380 i = -(i);
1381 }
1382 while (--i >= 0) {
1383 prev = x;
1384 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1385 if ((x >> PyLong_SHIFT) != prev) {
1386 *overflow = sign;
1387 goto exit;
1388 }
1389 }
1390 /* Haven't lost any bits, but casting to long requires extra
1391 * care (see comment above).
1392 */
1393 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1394 res = (PY_LONG_LONG)x * sign;
1395 }
1396 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1397 res = PY_LLONG_MIN;
1398 }
1399 else {
1400 *overflow = sign;
1401 /* res is already set to -1 */
1402 }
1403 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001404 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (do_decref) {
1406 Py_DECREF(vv);
1407 }
1408 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001409}
1410
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001411#endif /* HAVE_LONG_LONG */
1412
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001413#define CHECK_BINOP(v,w) \
1414 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001415 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1416 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001417 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001418
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001419/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1420 2**k if d is nonzero, else 0. */
1421
1422static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1424 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001425};
1426
1427static int
1428bits_in_digit(digit d)
1429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 int d_bits = 0;
1431 while (d >= 32) {
1432 d_bits += 6;
1433 d >>= 6;
1434 }
1435 d_bits += (int)BitLengthTable[d];
1436 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001437}
1438
Tim Peters877a2122002-08-12 05:09:36 +00001439/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1440 * is modified in place, by adding y to it. Carries are propagated as far as
1441 * x[m-1], and the remaining carry (0 or 1) is returned.
1442 */
1443static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001444v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 Py_ssize_t i;
1447 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 assert(m >= n);
1450 for (i = 0; i < n; ++i) {
1451 carry += x[i] + y[i];
1452 x[i] = carry & PyLong_MASK;
1453 carry >>= PyLong_SHIFT;
1454 assert((carry & 1) == carry);
1455 }
1456 for (; carry && i < m; ++i) {
1457 carry += x[i];
1458 x[i] = carry & PyLong_MASK;
1459 carry >>= PyLong_SHIFT;
1460 assert((carry & 1) == carry);
1461 }
1462 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001463}
1464
1465/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1466 * is modified in place, by subtracting y from it. Borrows are propagated as
1467 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1468 */
1469static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001470v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 Py_ssize_t i;
1473 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 assert(m >= n);
1476 for (i = 0; i < n; ++i) {
1477 borrow = x[i] - y[i] - borrow;
1478 x[i] = borrow & PyLong_MASK;
1479 borrow >>= PyLong_SHIFT;
1480 borrow &= 1; /* keep only 1 sign bit */
1481 }
1482 for (; borrow && i < m; ++i) {
1483 borrow = x[i] - borrow;
1484 x[i] = borrow & PyLong_MASK;
1485 borrow >>= PyLong_SHIFT;
1486 borrow &= 1;
1487 }
1488 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001489}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001490
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001491/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1492 * result in z[0:m], and return the d bits shifted out of the top.
1493 */
1494static digit
1495v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 Py_ssize_t i;
1498 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 assert(0 <= d && d < PyLong_SHIFT);
1501 for (i=0; i < m; i++) {
1502 twodigits acc = (twodigits)a[i] << d | carry;
1503 z[i] = (digit)acc & PyLong_MASK;
1504 carry = (digit)(acc >> PyLong_SHIFT);
1505 }
1506 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001507}
1508
1509/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1510 * result in z[0:m], and return the d bits shifted out of the bottom.
1511 */
1512static digit
1513v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 Py_ssize_t i;
1516 digit carry = 0;
1517 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 assert(0 <= d && d < PyLong_SHIFT);
1520 for (i=m; i-- > 0;) {
1521 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1522 carry = (digit)acc & mask;
1523 z[i] = (digit)(acc >> d);
1524 }
1525 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001526}
1527
Tim Peters212e6142001-07-14 12:23:19 +00001528/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1529 in pout, and returning the remainder. pin and pout point at the LSD.
1530 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001531 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001532 immutable. */
1533
1534static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001535inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 assert(n > 0 && n <= PyLong_MASK);
1540 pin += size;
1541 pout += size;
1542 while (--size >= 0) {
1543 digit hi;
1544 rem = (rem << PyLong_SHIFT) | *--pin;
1545 *--pout = hi = (digit)(rem / n);
1546 rem -= (twodigits)hi * n;
1547 }
1548 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001549}
1550
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001551/* Divide a long integer by a digit, returning both the quotient
1552 (as function result) and the remainder (through *prem).
1553 The sign of a is ignored; n should not be zero. */
1554
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001555static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001556divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 const Py_ssize_t size = ABS(Py_SIZE(a));
1559 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 assert(n > 0 && n <= PyLong_MASK);
1562 z = _PyLong_New(size);
1563 if (z == NULL)
1564 return NULL;
1565 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1566 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001567}
1568
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001569/* Convert a long integer to a base 10 string. Returns a new non-shared
1570 string. (Return value is non-shared so that callers can modify the
1571 returned value if necessary.) */
1572
Victor Stinnerd3f08822012-05-29 12:57:52 +02001573static int
1574long_to_decimal_string_internal(PyObject *aa,
1575 PyObject **p_output,
1576 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 PyLongObject *scratch, *a;
1579 PyObject *str;
1580 Py_ssize_t size, strlen, size_a, i, j;
1581 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001583 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 a = (PyLongObject *)aa;
1586 if (a == NULL || !PyLong_Check(a)) {
1587 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001588 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 }
1590 size_a = ABS(Py_SIZE(a));
1591 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 /* quick and dirty upper bound for the number of digits
1594 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 But log2(a) < size_a * PyLong_SHIFT, and
1599 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1600 > 3 * _PyLong_DECIMAL_SHIFT
1601 */
1602 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1603 PyErr_SetString(PyExc_OverflowError,
1604 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001605 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 }
1607 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1608 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1609 scratch = _PyLong_New(size);
1610 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001611 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 /* convert array of base _PyLong_BASE digits in pin to an array of
1614 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1615 Volume 2 (3rd edn), section 4.4, Method 1b). */
1616 pin = a->ob_digit;
1617 pout = scratch->ob_digit;
1618 size = 0;
1619 for (i = size_a; --i >= 0; ) {
1620 digit hi = pin[i];
1621 for (j = 0; j < size; j++) {
1622 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1623 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1624 pout[j] = (digit)(z - (twodigits)hi *
1625 _PyLong_DECIMAL_BASE);
1626 }
1627 while (hi) {
1628 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1629 hi /= _PyLong_DECIMAL_BASE;
1630 }
1631 /* check for keyboard interrupt */
1632 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001633 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001634 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001635 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 }
1637 /* pout should have at least one digit, so that the case when a = 0
1638 works correctly */
1639 if (size == 0)
1640 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 /* calculate exact length of output string, and allocate */
1643 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1644 tenpow = 10;
1645 rem = pout[size-1];
1646 while (rem >= tenpow) {
1647 tenpow *= 10;
1648 strlen++;
1649 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001650 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001651 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1652 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001653 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001654 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001655 kind = writer->kind;
1656 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001658 else {
1659 str = PyUnicode_New(strlen, '9');
1660 if (str == NULL) {
1661 Py_DECREF(scratch);
1662 return -1;
1663 }
1664 kind = PyUnicode_KIND(str);
1665 }
1666
1667#define WRITE_DIGITS(TYPE) \
1668 do { \
1669 if (writer) \
1670 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1671 else \
1672 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1673 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001674 /* pout[0] through pout[size-2] contribute exactly \
1675 _PyLong_DECIMAL_SHIFT digits each */ \
1676 for (i=0; i < size - 1; i++) { \
1677 rem = pout[i]; \
1678 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1679 *--p = '0' + rem % 10; \
1680 rem /= 10; \
1681 } \
1682 } \
1683 /* pout[size-1]: always produce at least one decimal digit */ \
1684 rem = pout[i]; \
1685 do { \
1686 *--p = '0' + rem % 10; \
1687 rem /= 10; \
1688 } while (rem != 0); \
1689 \
1690 /* and sign */ \
1691 if (negative) \
1692 *--p = '-'; \
1693 \
1694 /* check we've counted correctly */ \
1695 if (writer) \
1696 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1697 else \
1698 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1699 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001702 if (kind == PyUnicode_1BYTE_KIND) {
1703 Py_UCS1 *p;
1704 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001706 else if (kind == PyUnicode_2BYTE_KIND) {
1707 Py_UCS2 *p;
1708 WRITE_DIGITS(Py_UCS2);
1709 }
1710 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001711 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001712 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001713 WRITE_DIGITS(Py_UCS4);
1714 }
1715#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001718 if (writer) {
1719 writer->pos += strlen;
1720 }
1721 else {
1722 assert(_PyUnicode_CheckConsistency(str, 1));
1723 *p_output = (PyObject *)str;
1724 }
1725 return 0;
1726}
1727
1728static PyObject *
1729long_to_decimal_string(PyObject *aa)
1730{
1731 PyObject *v;
1732 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1733 return NULL;
1734 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001735}
1736
Mark Dickinsoncd068122009-09-18 14:53:08 +00001737/* Convert a long int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001738 which should be one of 2, 8 or 16. Return a string object.
1739 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1740 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001741
Victor Stinnerd3f08822012-05-29 12:57:52 +02001742static int
1743long_format_binary(PyObject *aa, int base, int alternate,
1744 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001747 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001748 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001750 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001751 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001753
Victor Stinnerd3f08822012-05-29 12:57:52 +02001754 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 if (a == NULL || !PyLong_Check(a)) {
1756 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001757 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 }
1759 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001760 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 /* Compute a rough upper bound for the length of the string */
1763 switch (base) {
1764 case 16:
1765 bits = 4;
1766 break;
1767 case 8:
1768 bits = 3;
1769 break;
1770 case 2:
1771 bits = 1;
1772 break;
1773 default:
1774 assert(0); /* shouldn't ever get here */
1775 bits = 0; /* to silence gcc warning */
1776 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001777
Mark Dickinsone2846542012-04-20 21:21:24 +01001778 /* Compute exact length 'sz' of output string. */
1779 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001780 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001781 }
1782 else {
1783 Py_ssize_t size_a_in_bits;
1784 /* Ensure overflow doesn't occur during computation of sz. */
1785 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1786 PyErr_SetString(PyExc_OverflowError,
1787 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001788 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001789 }
1790 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1791 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001792 /* Allow 1 character for a '-' sign. */
1793 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1794 }
1795 if (alternate) {
1796 /* 2 characters for prefix */
1797 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001798 }
1799
Victor Stinnerd3f08822012-05-29 12:57:52 +02001800 if (writer) {
1801 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1802 return -1;
1803 kind = writer->kind;
1804 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 }
1806 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001807 v = PyUnicode_New(sz, 'x');
1808 if (v == NULL)
1809 return -1;
1810 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001812
Victor Stinnerd3f08822012-05-29 12:57:52 +02001813#define WRITE_DIGITS(TYPE) \
1814 do { \
1815 if (writer) \
1816 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1817 else \
1818 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1819 \
1820 if (size_a == 0) { \
1821 *--p = '0'; \
1822 } \
1823 else { \
1824 /* JRH: special case for power-of-2 bases */ \
1825 twodigits accum = 0; \
1826 int accumbits = 0; /* # of bits in accum */ \
1827 Py_ssize_t i; \
1828 for (i = 0; i < size_a; ++i) { \
1829 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1830 accumbits += PyLong_SHIFT; \
1831 assert(accumbits >= bits); \
1832 do { \
1833 char cdigit; \
1834 cdigit = (char)(accum & (base - 1)); \
1835 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1836 *--p = cdigit; \
1837 accumbits -= bits; \
1838 accum >>= bits; \
1839 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1840 } \
1841 } \
1842 \
1843 if (alternate) { \
1844 if (base == 16) \
1845 *--p = 'x'; \
1846 else if (base == 8) \
1847 *--p = 'o'; \
1848 else /* (base == 2) */ \
1849 *--p = 'b'; \
1850 *--p = '0'; \
1851 } \
1852 if (negative) \
1853 *--p = '-'; \
1854 if (writer) \
1855 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1856 else \
1857 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1858 } while (0)
1859
1860 if (kind == PyUnicode_1BYTE_KIND) {
1861 Py_UCS1 *p;
1862 WRITE_DIGITS(Py_UCS1);
1863 }
1864 else if (kind == PyUnicode_2BYTE_KIND) {
1865 Py_UCS2 *p;
1866 WRITE_DIGITS(Py_UCS2);
1867 }
1868 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001869 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001870 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001871 WRITE_DIGITS(Py_UCS4);
1872 }
1873#undef WRITE_DIGITS
1874
1875 if (writer) {
1876 writer->pos += sz;
1877 }
1878 else {
1879 assert(_PyUnicode_CheckConsistency(v, 1));
1880 *p_output = v;
1881 }
1882 return 0;
1883}
1884
1885PyObject *
1886_PyLong_Format(PyObject *obj, int base)
1887{
1888 PyObject *str;
1889 int err;
1890 if (base == 10)
1891 err = long_to_decimal_string_internal(obj, &str, NULL);
1892 else
1893 err = long_format_binary(obj, base, 1, &str, NULL);
1894 if (err == -1)
1895 return NULL;
1896 return str;
1897}
1898
1899int
1900_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1901 PyObject *obj,
1902 int base, int alternate)
1903{
1904 if (base == 10)
1905 return long_to_decimal_string_internal(obj, NULL, writer);
1906 else
1907 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001908}
1909
Thomas Wouters477c8d52006-05-27 19:21:47 +00001910/* Table of digit values for 8-bit string -> integer conversion.
1911 * '0' maps to 0, ..., '9' maps to 9.
1912 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1913 * All other indices map to 37.
1914 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001915 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001916 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001917unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 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 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1922 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1923 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1924 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1925 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1926 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1927 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1928 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1929 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1930 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1931 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1932 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1933 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001934};
1935
1936/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001937 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1938 * non-digit (which may be *str!). A normalized long is returned.
1939 * The point to this routine is that it takes time linear in the number of
1940 * string characters.
1941 */
1942static PyLongObject *
1943long_from_binary_base(char **str, int base)
1944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 char *p = *str;
1946 char *start = p;
1947 int bits_per_char;
1948 Py_ssize_t n;
1949 PyLongObject *z;
1950 twodigits accum;
1951 int bits_in_accum;
1952 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1955 n = base;
1956 for (bits_per_char = -1; n; ++bits_per_char)
1957 n >>= 1;
1958 /* n <- total # of bits needed, while setting p to end-of-string */
1959 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1960 ++p;
1961 *str = p;
1962 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1963 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1964 if (n / bits_per_char < p - start) {
1965 PyErr_SetString(PyExc_ValueError,
1966 "int string too large to convert");
1967 return NULL;
1968 }
1969 n = n / PyLong_SHIFT;
1970 z = _PyLong_New(n);
1971 if (z == NULL)
1972 return NULL;
1973 /* Read string from right, and fill in long from left; i.e.,
1974 * from least to most significant in both.
1975 */
1976 accum = 0;
1977 bits_in_accum = 0;
1978 pdigit = z->ob_digit;
1979 while (--p >= start) {
1980 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1981 assert(k >= 0 && k < base);
1982 accum |= (twodigits)k << bits_in_accum;
1983 bits_in_accum += bits_per_char;
1984 if (bits_in_accum >= PyLong_SHIFT) {
1985 *pdigit++ = (digit)(accum & PyLong_MASK);
1986 assert(pdigit - z->ob_digit <= n);
1987 accum >>= PyLong_SHIFT;
1988 bits_in_accum -= PyLong_SHIFT;
1989 assert(bits_in_accum < PyLong_SHIFT);
1990 }
1991 }
1992 if (bits_in_accum) {
1993 assert(bits_in_accum <= PyLong_SHIFT);
1994 *pdigit++ = (digit)accum;
1995 assert(pdigit - z->ob_digit <= n);
1996 }
1997 while (pdigit - z->ob_digit < n)
1998 *pdigit++ = 0;
1999 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002000}
2001
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002002PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002003PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 int sign = 1, error_if_nonzero = 0;
2006 char *start, *orig_str = str;
2007 PyLongObject *z = NULL;
2008 PyObject *strobj;
2009 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if ((base != 0 && base < 2) || base > 36) {
2012 PyErr_SetString(PyExc_ValueError,
2013 "int() arg 2 must be >= 2 and <= 36");
2014 return NULL;
2015 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002016 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 str++;
2018 if (*str == '+')
2019 ++str;
2020 else if (*str == '-') {
2021 ++str;
2022 sign = -1;
2023 }
2024 if (base == 0) {
2025 if (str[0] != '0')
2026 base = 10;
2027 else if (str[1] == 'x' || str[1] == 'X')
2028 base = 16;
2029 else if (str[1] == 'o' || str[1] == 'O')
2030 base = 8;
2031 else if (str[1] == 'b' || str[1] == 'B')
2032 base = 2;
2033 else {
2034 /* "old" (C-style) octal literal, now invalid.
2035 it might still be zero though */
2036 error_if_nonzero = 1;
2037 base = 10;
2038 }
2039 }
2040 if (str[0] == '0' &&
2041 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2042 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2043 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2044 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 start = str;
2047 if ((base & (base - 1)) == 0)
2048 z = long_from_binary_base(&str, base);
2049 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002050/***
2051Binary bases can be converted in time linear in the number of digits, because
2052Python's representation base is binary. Other bases (including decimal!) use
2053the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002054
Thomas Wouters477c8d52006-05-27 19:21:47 +00002055First some math: the largest integer that can be expressed in N base-B digits
2056is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2057case number of Python digits needed to hold it is the smallest integer n s.t.
2058
2059 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2060 BASE**n >= B**N [taking logs to base BASE]
2061 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2062
2063The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2064this quickly. A Python long with that much space is reserved near the start,
2065and the result is computed into it.
2066
2067The input string is actually treated as being in base base**i (i.e., i digits
2068are processed at a time), where two more static arrays hold:
2069
2070 convwidth_base[base] = the largest integer i such that base**i <= BASE
2071 convmultmax_base[base] = base ** convwidth_base[base]
2072
2073The first of these is the largest i such that i consecutive input digits
2074must fit in a single Python digit. The second is effectively the input
2075base we're really using.
2076
2077Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2078convmultmax_base[base], the result is "simply"
2079
2080 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2081
2082where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002083
2084Error analysis: as above, the number of Python digits `n` needed is worst-
2085case
2086
2087 n >= N * log(B)/log(BASE)
2088
2089where `N` is the number of input digits in base `B`. This is computed via
2090
2091 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2092
2093below. Two numeric concerns are how much space this can waste, and whether
2094the computed result can be too small. To be concrete, assume BASE = 2**15,
2095which is the default (and it's unlikely anyone changes that).
2096
2097Waste isn't a problem: provided the first input digit isn't 0, the difference
2098between the worst-case input with N digits and the smallest input with N
2099digits is about a factor of B, but B is small compared to BASE so at most
2100one allocated Python digit can remain unused on that count. If
2101N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2102and adding 1 returns a result 1 larger than necessary. However, that can't
2103happen: whenever B is a power of 2, long_from_binary_base() is called
2104instead, and it's impossible for B**i to be an integer power of 2**15 when
2105B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2106an exact integer when B is not a power of 2, since B**i has a prime factor
2107other than 2 in that case, but (2**15)**j's only prime factor is 2).
2108
2109The computed result can be too small if the true value of N*log(B)/log(BASE)
2110is a little bit larger than an exact integer, but due to roundoff errors (in
2111computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2112yields a numeric result a little less than that integer. Unfortunately, "how
2113close can a transcendental function get to an integer over some range?"
2114questions are generally theoretically intractable. Computer analysis via
2115continued fractions is practical: expand log(B)/log(BASE) via continued
2116fractions, giving a sequence i/j of "the best" rational approximations. Then
2117j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2118we can get very close to being in trouble, but very rarely. For example,
211976573 is a denominator in one of the continued-fraction approximations to
2120log(10)/log(2**15), and indeed:
2121
2122 >>> log(10)/log(2**15)*76573
2123 16958.000000654003
2124
2125is very close to an integer. If we were working with IEEE single-precision,
2126rounding errors could kill us. Finding worst cases in IEEE double-precision
2127requires better-than-double-precision log() functions, and Tim didn't bother.
2128Instead the code checks to see whether the allocated space is enough as each
2129new Python digit is added, and copies the whole thing to a larger long if not.
2130This should happen extremely rarely, and in fact I don't have a test case
2131that triggers it(!). Instead the code was tested by artificially allocating
2132just 1 digit at the start, so that the copying code was exercised for every
2133digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002134***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 register twodigits c; /* current input character */
2136 Py_ssize_t size_z;
2137 int i;
2138 int convwidth;
2139 twodigits convmultmax, convmult;
2140 digit *pz, *pzstop;
2141 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 static double log_base_BASE[37] = {0.0e0,};
2144 static int convwidth_base[37] = {0,};
2145 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 if (log_base_BASE[base] == 0.0) {
2148 twodigits convmax = base;
2149 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002150
Mark Dickinson22b20182010-05-10 21:27:53 +00002151 log_base_BASE[base] = (log((double)base) /
2152 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 for (;;) {
2154 twodigits next = convmax * base;
2155 if (next > PyLong_BASE)
2156 break;
2157 convmax = next;
2158 ++i;
2159 }
2160 convmultmax_base[base] = convmax;
2161 assert(i > 0);
2162 convwidth_base[base] = i;
2163 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 /* Find length of the string of numeric characters. */
2166 scan = str;
2167 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2168 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* Create a long object that can contain the largest possible
2171 * integer with this base and length. Note that there's no
2172 * need to initialize z->ob_digit -- no slot is read up before
2173 * being stored into.
2174 */
2175 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2176 /* Uncomment next line to test exceedingly rare copy code */
2177 /* size_z = 1; */
2178 assert(size_z > 0);
2179 z = _PyLong_New(size_z);
2180 if (z == NULL)
2181 return NULL;
2182 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 /* `convwidth` consecutive input digits are treated as a single
2185 * digit in base `convmultmax`.
2186 */
2187 convwidth = convwidth_base[base];
2188 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* Work ;-) */
2191 while (str < scan) {
2192 /* grab up to convwidth digits from the input string */
2193 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2194 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2195 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002196 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 assert(c < PyLong_BASE);
2198 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 convmult = convmultmax;
2201 /* Calculate the shift only if we couldn't get
2202 * convwidth digits.
2203 */
2204 if (i != convwidth) {
2205 convmult = base;
2206 for ( ; i > 1; --i)
2207 convmult *= base;
2208 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 /* Multiply z by convmult, and add c. */
2211 pz = z->ob_digit;
2212 pzstop = pz + Py_SIZE(z);
2213 for (; pz < pzstop; ++pz) {
2214 c += (twodigits)*pz * convmult;
2215 *pz = (digit)(c & PyLong_MASK);
2216 c >>= PyLong_SHIFT;
2217 }
2218 /* carry off the current end? */
2219 if (c) {
2220 assert(c < PyLong_BASE);
2221 if (Py_SIZE(z) < size_z) {
2222 *pz = (digit)c;
2223 ++Py_SIZE(z);
2224 }
2225 else {
2226 PyLongObject *tmp;
2227 /* Extremely rare. Get more space. */
2228 assert(Py_SIZE(z) == size_z);
2229 tmp = _PyLong_New(size_z + 1);
2230 if (tmp == NULL) {
2231 Py_DECREF(z);
2232 return NULL;
2233 }
2234 memcpy(tmp->ob_digit,
2235 z->ob_digit,
2236 sizeof(digit) * size_z);
2237 Py_DECREF(z);
2238 z = tmp;
2239 z->ob_digit[size_z] = (digit)c;
2240 ++size_z;
2241 }
2242 }
2243 }
2244 }
2245 if (z == NULL)
2246 return NULL;
2247 if (error_if_nonzero) {
2248 /* reset the base to 0, else the exception message
2249 doesn't make too much sense */
2250 base = 0;
2251 if (Py_SIZE(z) != 0)
2252 goto onError;
2253 /* there might still be other problems, therefore base
2254 remains zero here for the same reason */
2255 }
2256 if (str == start)
2257 goto onError;
2258 if (sign < 0)
2259 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002260 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 str++;
2262 if (*str != '\0')
2263 goto onError;
2264 if (pend)
2265 *pend = str;
2266 long_normalize(z);
2267 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002268
Mark Dickinson22b20182010-05-10 21:27:53 +00002269 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 Py_XDECREF(z);
2271 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2272 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2273 if (strobj == NULL)
2274 return NULL;
2275 PyErr_Format(PyExc_ValueError,
2276 "invalid literal for int() with base %d: %R",
2277 base, strobj);
2278 Py_DECREF(strobj);
2279 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002280}
2281
2282PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002283PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002284{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002285 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2286 if (unicode == NULL)
2287 return NULL;
2288 v = PyLong_FromUnicodeObject(unicode, base);
2289 Py_DECREF(unicode);
2290 return v;
2291}
2292
2293PyObject *
2294PyLong_FromUnicodeObject(PyObject *u, int base)
2295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002297 PyObject *asciidig;
2298 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002299 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002301 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002302 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002304 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002305 if (buffer == NULL) {
2306 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 return NULL;
2308 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002309 result = PyLong_FromString(buffer, &end, base);
2310 if (result != NULL && end != buffer + buflen) {
2311 PyErr_SetString(PyExc_ValueError,
2312 "null byte in argument for int()");
2313 Py_DECREF(result);
2314 result = NULL;
2315 }
2316 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002318}
2319
Tim Peters9f688bf2000-07-07 15:53:28 +00002320/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002321static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002323static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002324
2325/* Long division with remainder, top-level routine */
2326
Guido van Rossume32e0141992-01-19 16:31:05 +00002327static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002328long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2332 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (size_b == 0) {
2335 PyErr_SetString(PyExc_ZeroDivisionError,
2336 "integer division or modulo by zero");
2337 return -1;
2338 }
2339 if (size_a < size_b ||
2340 (size_a == size_b &&
2341 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2342 /* |a| < |b|. */
2343 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2344 if (*pdiv == NULL)
2345 return -1;
2346 Py_INCREF(a);
2347 *prem = (PyLongObject *) a;
2348 return 0;
2349 }
2350 if (size_b == 1) {
2351 digit rem = 0;
2352 z = divrem1(a, b->ob_digit[0], &rem);
2353 if (z == NULL)
2354 return -1;
2355 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2356 if (*prem == NULL) {
2357 Py_DECREF(z);
2358 return -1;
2359 }
2360 }
2361 else {
2362 z = x_divrem(a, b, prem);
2363 if (z == NULL)
2364 return -1;
2365 }
2366 /* Set the signs.
2367 The quotient z has the sign of a*b;
2368 the remainder r has the sign of a,
2369 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002370 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2371 _PyLong_Negate(&z);
2372 if (z == NULL) {
2373 Py_CLEAR(*prem);
2374 return -1;
2375 }
2376 }
2377 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2378 _PyLong_Negate(prem);
2379 if (*prem == NULL) {
2380 Py_DECREF(z);
2381 Py_CLEAR(*prem);
2382 return -1;
2383 }
2384 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 *pdiv = maybe_small_long(z);
2386 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002387}
2388
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002389/* Unsigned long division with remainder -- the algorithm. The arguments v1
2390 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002391
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002392static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002393x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 PyLongObject *v, *w, *a;
2396 Py_ssize_t i, k, size_v, size_w;
2397 int d;
2398 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2399 twodigits vv;
2400 sdigit zhi;
2401 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2404 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2405 handle the special case when the initial estimate q for a quotient
2406 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2407 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 /* allocate space; w will also be used to hold the final remainder */
2410 size_v = ABS(Py_SIZE(v1));
2411 size_w = ABS(Py_SIZE(w1));
2412 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2413 v = _PyLong_New(size_v+1);
2414 if (v == NULL) {
2415 *prem = NULL;
2416 return NULL;
2417 }
2418 w = _PyLong_New(size_w);
2419 if (w == NULL) {
2420 Py_DECREF(v);
2421 *prem = NULL;
2422 return NULL;
2423 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2426 shift v1 left by the same amount. Results go into w and v. */
2427 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2428 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2429 assert(carry == 0);
2430 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2431 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2432 v->ob_digit[size_v] = carry;
2433 size_v++;
2434 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2437 at most (and usually exactly) k = size_v - size_w digits. */
2438 k = size_v - size_w;
2439 assert(k >= 0);
2440 a = _PyLong_New(k);
2441 if (a == NULL) {
2442 Py_DECREF(w);
2443 Py_DECREF(v);
2444 *prem = NULL;
2445 return NULL;
2446 }
2447 v0 = v->ob_digit;
2448 w0 = w->ob_digit;
2449 wm1 = w0[size_w-1];
2450 wm2 = w0[size_w-2];
2451 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2452 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2453 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002456 Py_DECREF(a);
2457 Py_DECREF(w);
2458 Py_DECREF(v);
2459 *prem = NULL;
2460 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002461 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 /* estimate quotient digit q; may overestimate by 1 (rare) */
2464 vtop = vk[size_w];
2465 assert(vtop <= wm1);
2466 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2467 q = (digit)(vv / wm1);
2468 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2469 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2470 | vk[size_w-2])) {
2471 --q;
2472 r += wm1;
2473 if (r >= PyLong_BASE)
2474 break;
2475 }
2476 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2479 zhi = 0;
2480 for (i = 0; i < size_w; ++i) {
2481 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2482 -PyLong_BASE * q <= z < PyLong_BASE */
2483 z = (sdigit)vk[i] + zhi -
2484 (stwodigits)q * (stwodigits)w0[i];
2485 vk[i] = (digit)z & PyLong_MASK;
2486 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002487 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* add w back if q was too large (this branch taken rarely) */
2491 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2492 if ((sdigit)vtop + zhi < 0) {
2493 carry = 0;
2494 for (i = 0; i < size_w; ++i) {
2495 carry += vk[i] + w0[i];
2496 vk[i] = carry & PyLong_MASK;
2497 carry >>= PyLong_SHIFT;
2498 }
2499 --q;
2500 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 /* store quotient digit */
2503 assert(q < PyLong_BASE);
2504 *--ak = q;
2505 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 /* unshift remainder; we reuse w to store the result */
2508 carry = v_rshift(w0, v0, size_w, d);
2509 assert(carry==0);
2510 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 *prem = long_normalize(w);
2513 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002514}
2515
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002516/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2517 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2518 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2519 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2520 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2521 -1.0. */
2522
2523/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2524#if DBL_MANT_DIG == 53
2525#define EXP2_DBL_MANT_DIG 9007199254740992.0
2526#else
2527#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2528#endif
2529
2530double
2531_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2534 /* See below for why x_digits is always large enough. */
2535 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2536 double dx;
2537 /* Correction term for round-half-to-even rounding. For a digit x,
2538 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2539 multiple of 4, rounding ties to a multiple of 8. */
2540 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 a_size = ABS(Py_SIZE(a));
2543 if (a_size == 0) {
2544 /* Special case for 0: significand 0.0, exponent 0. */
2545 *e = 0;
2546 return 0.0;
2547 }
2548 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2549 /* The following is an overflow-free version of the check
2550 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2551 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2552 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2553 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002554 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2558 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 Number of digits needed for result: write // for floor division.
2561 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2570 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2573 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2574 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 in both cases.
2581 */
2582 if (a_bits <= DBL_MANT_DIG + 2) {
2583 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2584 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2585 x_size = 0;
2586 while (x_size < shift_digits)
2587 x_digits[x_size++] = 0;
2588 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2589 (int)shift_bits);
2590 x_size += a_size;
2591 x_digits[x_size++] = rem;
2592 }
2593 else {
2594 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2595 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2596 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2597 a_size - shift_digits, (int)shift_bits);
2598 x_size = a_size - shift_digits;
2599 /* For correct rounding below, we need the least significant
2600 bit of x to be 'sticky' for this shift: if any of the bits
2601 shifted out was nonzero, we set the least significant bit
2602 of x. */
2603 if (rem)
2604 x_digits[0] |= 1;
2605 else
2606 while (shift_digits > 0)
2607 if (a->ob_digit[--shift_digits]) {
2608 x_digits[0] |= 1;
2609 break;
2610 }
2611 }
Victor Stinner63941882011-09-29 00:42:28 +02002612 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 /* Round, and convert to double. */
2615 x_digits[0] += half_even_correction[x_digits[0] & 7];
2616 dx = x_digits[--x_size];
2617 while (x_size > 0)
2618 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 /* Rescale; make correction if result is 1.0. */
2621 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2622 if (dx == 1.0) {
2623 if (a_bits == PY_SSIZE_T_MAX)
2624 goto overflow;
2625 dx = 0.5;
2626 a_bits += 1;
2627 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 *e = a_bits;
2630 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002631
2632 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 /* exponent > PY_SSIZE_T_MAX */
2634 PyErr_SetString(PyExc_OverflowError,
2635 "huge integer: number of bits overflows a Py_ssize_t");
2636 *e = 0;
2637 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002638}
2639
2640/* Get a C double from a long int object. Rounds to the nearest double,
2641 using the round-half-to-even rule in the case of a tie. */
2642
2643double
2644PyLong_AsDouble(PyObject *v)
2645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 Py_ssize_t exponent;
2647 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002648
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002649 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 PyErr_BadInternalCall();
2651 return -1.0;
2652 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002653 if (!PyLong_Check(v)) {
2654 PyErr_SetString(PyExc_TypeError, "an integer is required");
2655 return -1.0;
2656 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2658 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2659 PyErr_SetString(PyExc_OverflowError,
2660 "long int too large to convert to float");
2661 return -1.0;
2662 }
2663 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002664}
2665
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002666/* Methods */
2667
2668static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002669long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002672}
2673
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002674static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002675long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 if (Py_SIZE(a) != Py_SIZE(b)) {
2680 sign = Py_SIZE(a) - Py_SIZE(b);
2681 }
2682 else {
2683 Py_ssize_t i = ABS(Py_SIZE(a));
2684 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2685 ;
2686 if (i < 0)
2687 sign = 0;
2688 else {
2689 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2690 if (Py_SIZE(a) < 0)
2691 sign = -sign;
2692 }
2693 }
2694 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002695}
2696
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002697#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002699
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002700static PyObject *
2701long_richcompare(PyObject *self, PyObject *other, int op)
2702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 int result;
2704 PyObject *v;
2705 CHECK_BINOP(self, other);
2706 if (self == other)
2707 result = 0;
2708 else
2709 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2710 /* Convert the return value to a Boolean */
2711 switch (op) {
2712 case Py_EQ:
2713 v = TEST_COND(result == 0);
2714 break;
2715 case Py_NE:
2716 v = TEST_COND(result != 0);
2717 break;
2718 case Py_LE:
2719 v = TEST_COND(result <= 0);
2720 break;
2721 case Py_GE:
2722 v = TEST_COND(result >= 0);
2723 break;
2724 case Py_LT:
2725 v = TEST_COND(result == -1);
2726 break;
2727 case Py_GT:
2728 v = TEST_COND(result == 1);
2729 break;
2730 default:
2731 PyErr_BadArgument();
2732 return NULL;
2733 }
2734 Py_INCREF(v);
2735 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002736}
2737
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002738static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002739long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002740{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002741 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 Py_ssize_t i;
2743 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 i = Py_SIZE(v);
2746 switch(i) {
2747 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2748 case 0: return 0;
2749 case 1: return v->ob_digit[0];
2750 }
2751 sign = 1;
2752 x = 0;
2753 if (i < 0) {
2754 sign = -1;
2755 i = -(i);
2756 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002758 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2759 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2760 _PyHASH_MODULUS.
2761
2762 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2763 amounts to a rotation of the bits of x. To see this, write
2764
2765 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2766
2767 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2768 PyLong_SHIFT bits of x (those that are shifted out of the
2769 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2770 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2771 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2772 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2773 congruent to y modulo _PyHASH_MODULUS. So
2774
2775 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2776
2777 The right-hand side is just the result of rotating the
2778 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2779 not all _PyHASH_BITS bits of x are 1s, the same is true
2780 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2781 the reduction of x*2**PyLong_SHIFT modulo
2782 _PyHASH_MODULUS. */
2783 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2784 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002786 if (x >= _PyHASH_MODULUS)
2787 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 }
2789 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002790 if (x == (Py_uhash_t)-1)
2791 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002792 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002793}
2794
2795
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002796/* Add the absolute values of two long integers. */
2797
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002798static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002799x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2802 PyLongObject *z;
2803 Py_ssize_t i;
2804 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 /* Ensure a is the larger of the two: */
2807 if (size_a < size_b) {
2808 { PyLongObject *temp = a; a = b; b = temp; }
2809 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002810 size_a = size_b;
2811 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 }
2813 z = _PyLong_New(size_a+1);
2814 if (z == NULL)
2815 return NULL;
2816 for (i = 0; i < size_b; ++i) {
2817 carry += a->ob_digit[i] + b->ob_digit[i];
2818 z->ob_digit[i] = carry & PyLong_MASK;
2819 carry >>= PyLong_SHIFT;
2820 }
2821 for (; i < size_a; ++i) {
2822 carry += a->ob_digit[i];
2823 z->ob_digit[i] = carry & PyLong_MASK;
2824 carry >>= PyLong_SHIFT;
2825 }
2826 z->ob_digit[i] = carry;
2827 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002828}
2829
2830/* Subtract the absolute values of two integers. */
2831
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002832static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002833x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2836 PyLongObject *z;
2837 Py_ssize_t i;
2838 int sign = 1;
2839 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 /* Ensure a is the larger of the two: */
2842 if (size_a < size_b) {
2843 sign = -1;
2844 { PyLongObject *temp = a; a = b; b = temp; }
2845 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002846 size_a = size_b;
2847 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 }
2849 else if (size_a == size_b) {
2850 /* Find highest digit where a and b differ: */
2851 i = size_a;
2852 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2853 ;
2854 if (i < 0)
2855 return (PyLongObject *)PyLong_FromLong(0);
2856 if (a->ob_digit[i] < b->ob_digit[i]) {
2857 sign = -1;
2858 { PyLongObject *temp = a; a = b; b = temp; }
2859 }
2860 size_a = size_b = i+1;
2861 }
2862 z = _PyLong_New(size_a);
2863 if (z == NULL)
2864 return NULL;
2865 for (i = 0; i < size_b; ++i) {
2866 /* The following assumes unsigned arithmetic
2867 works module 2**N for some N>PyLong_SHIFT. */
2868 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2869 z->ob_digit[i] = borrow & PyLong_MASK;
2870 borrow >>= PyLong_SHIFT;
2871 borrow &= 1; /* Keep only one sign bit */
2872 }
2873 for (; i < size_a; ++i) {
2874 borrow = a->ob_digit[i] - borrow;
2875 z->ob_digit[i] = borrow & PyLong_MASK;
2876 borrow >>= PyLong_SHIFT;
2877 borrow &= 1; /* Keep only one sign bit */
2878 }
2879 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02002880 if (sign < 0) {
2881 _PyLong_Negate(&z);
2882 if (z == NULL)
2883 return NULL;
2884 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002886}
2887
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002888static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002889long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2896 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2897 MEDIUM_VALUE(b));
2898 return result;
2899 }
2900 if (Py_SIZE(a) < 0) {
2901 if (Py_SIZE(b) < 0) {
2902 z = x_add(a, b);
2903 if (z != NULL && Py_SIZE(z) != 0)
2904 Py_SIZE(z) = -(Py_SIZE(z));
2905 }
2906 else
2907 z = x_sub(b, a);
2908 }
2909 else {
2910 if (Py_SIZE(b) < 0)
2911 z = x_sub(a, b);
2912 else
2913 z = x_add(a, b);
2914 }
2915 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002916}
2917
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002918static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002919long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2926 PyObject* r;
2927 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2928 return r;
2929 }
2930 if (Py_SIZE(a) < 0) {
2931 if (Py_SIZE(b) < 0)
2932 z = x_sub(a, b);
2933 else
2934 z = x_add(a, b);
2935 if (z != NULL && Py_SIZE(z) != 0)
2936 Py_SIZE(z) = -(Py_SIZE(z));
2937 }
2938 else {
2939 if (Py_SIZE(b) < 0)
2940 z = x_add(a, b);
2941 else
2942 z = x_sub(a, b);
2943 }
2944 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002945}
2946
Tim Peters5af4e6c2002-08-12 02:31:19 +00002947/* Grade school multiplication, ignoring the signs.
2948 * Returns the absolute value of the product, or NULL if error.
2949 */
2950static PyLongObject *
2951x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 PyLongObject *z;
2954 Py_ssize_t size_a = ABS(Py_SIZE(a));
2955 Py_ssize_t size_b = ABS(Py_SIZE(b));
2956 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 z = _PyLong_New(size_a + size_b);
2959 if (z == NULL)
2960 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2963 if (a == b) {
2964 /* Efficient squaring per HAC, Algorithm 14.16:
2965 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2966 * Gives slightly less than a 2x speedup when a == b,
2967 * via exploiting that each entry in the multiplication
2968 * pyramid appears twice (except for the size_a squares).
2969 */
2970 for (i = 0; i < size_a; ++i) {
2971 twodigits carry;
2972 twodigits f = a->ob_digit[i];
2973 digit *pz = z->ob_digit + (i << 1);
2974 digit *pa = a->ob_digit + i + 1;
2975 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002978 Py_DECREF(z);
2979 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002980 });
Tim Peters0973b992004-08-29 22:16:50 +00002981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 carry = *pz + f * f;
2983 *pz++ = (digit)(carry & PyLong_MASK);
2984 carry >>= PyLong_SHIFT;
2985 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 /* Now f is added in twice in each column of the
2988 * pyramid it appears. Same as adding f<<1 once.
2989 */
2990 f <<= 1;
2991 while (pa < paend) {
2992 carry += *pz + *pa++ * f;
2993 *pz++ = (digit)(carry & PyLong_MASK);
2994 carry >>= PyLong_SHIFT;
2995 assert(carry <= (PyLong_MASK << 1));
2996 }
2997 if (carry) {
2998 carry += *pz;
2999 *pz++ = (digit)(carry & PyLong_MASK);
3000 carry >>= PyLong_SHIFT;
3001 }
3002 if (carry)
3003 *pz += (digit)(carry & PyLong_MASK);
3004 assert((carry >> PyLong_SHIFT) == 0);
3005 }
3006 }
3007 else { /* a is not the same as b -- gradeschool long mult */
3008 for (i = 0; i < size_a; ++i) {
3009 twodigits carry = 0;
3010 twodigits f = a->ob_digit[i];
3011 digit *pz = z->ob_digit + i;
3012 digit *pb = b->ob_digit;
3013 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003016 Py_DECREF(z);
3017 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003018 });
Tim Peters0973b992004-08-29 22:16:50 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 while (pb < pbend) {
3021 carry += *pz + *pb++ * f;
3022 *pz++ = (digit)(carry & PyLong_MASK);
3023 carry >>= PyLong_SHIFT;
3024 assert(carry <= PyLong_MASK);
3025 }
3026 if (carry)
3027 *pz += (digit)(carry & PyLong_MASK);
3028 assert((carry >> PyLong_SHIFT) == 0);
3029 }
3030 }
3031 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003032}
3033
3034/* A helper for Karatsuba multiplication (k_mul).
3035 Takes a long "n" and an integer "size" representing the place to
3036 split, and sets low and high such that abs(n) == (high << size) + low,
3037 viewing the shift as being by digits. The sign bit is ignored, and
3038 the return values are >= 0.
3039 Returns 0 on success, -1 on failure.
3040*/
3041static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003042kmul_split(PyLongObject *n,
3043 Py_ssize_t size,
3044 PyLongObject **high,
3045 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 PyLongObject *hi, *lo;
3048 Py_ssize_t size_lo, size_hi;
3049 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003050
Victor Stinner640c35c2013-06-04 23:14:37 +02003051 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 if ((hi = _PyLong_New(size_hi)) == NULL)
3055 return -1;
3056 if ((lo = _PyLong_New(size_lo)) == NULL) {
3057 Py_DECREF(hi);
3058 return -1;
3059 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3062 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 *high = long_normalize(hi);
3065 *low = long_normalize(lo);
3066 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003067}
3068
Tim Peters60004642002-08-12 22:01:34 +00003069static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3070
Tim Peters5af4e6c2002-08-12 02:31:19 +00003071/* Karatsuba multiplication. Ignores the input signs, and returns the
3072 * absolute value of the product (or NULL if error).
3073 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3074 */
3075static PyLongObject *
3076k_mul(PyLongObject *a, PyLongObject *b)
3077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 Py_ssize_t asize = ABS(Py_SIZE(a));
3079 Py_ssize_t bsize = ABS(Py_SIZE(b));
3080 PyLongObject *ah = NULL;
3081 PyLongObject *al = NULL;
3082 PyLongObject *bh = NULL;
3083 PyLongObject *bl = NULL;
3084 PyLongObject *ret = NULL;
3085 PyLongObject *t1, *t2, *t3;
3086 Py_ssize_t shift; /* the number of digits we split off */
3087 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3090 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3091 * Then the original product is
3092 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3093 * By picking X to be a power of 2, "*X" is just shifting, and it's
3094 * been reduced to 3 multiplies on numbers half the size.
3095 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 /* We want to split based on the larger number; fiddle so that b
3098 * is largest.
3099 */
3100 if (asize > bsize) {
3101 t1 = a;
3102 a = b;
3103 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 i = asize;
3106 asize = bsize;
3107 bsize = i;
3108 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 /* Use gradeschool math when either number is too small. */
3111 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3112 if (asize <= i) {
3113 if (asize == 0)
3114 return (PyLongObject *)PyLong_FromLong(0);
3115 else
3116 return x_mul(a, b);
3117 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 /* If a is small compared to b, splitting on b gives a degenerate
3120 * case with ah==0, and Karatsuba may be (even much) less efficient
3121 * than "grade school" then. However, we can still win, by viewing
3122 * b as a string of "big digits", each of width a->ob_size. That
3123 * leads to a sequence of balanced calls to k_mul.
3124 */
3125 if (2 * asize <= bsize)
3126 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 /* Split a & b into hi & lo pieces. */
3129 shift = bsize >> 1;
3130 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3131 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 if (a == b) {
3134 bh = ah;
3135 bl = al;
3136 Py_INCREF(bh);
3137 Py_INCREF(bl);
3138 }
3139 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 /* The plan:
3142 * 1. Allocate result space (asize + bsize digits: that's always
3143 * enough).
3144 * 2. Compute ah*bh, and copy into result at 2*shift.
3145 * 3. Compute al*bl, and copy into result at 0. Note that this
3146 * can't overlap with #2.
3147 * 4. Subtract al*bl from the result, starting at shift. This may
3148 * underflow (borrow out of the high digit), but we don't care:
3149 * we're effectively doing unsigned arithmetic mod
3150 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3151 * borrows and carries out of the high digit can be ignored.
3152 * 5. Subtract ah*bh from the result, starting at shift.
3153 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3154 * at shift.
3155 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* 1. Allocate result space. */
3158 ret = _PyLong_New(asize + bsize);
3159 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003160#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 /* Fill with trash, to catch reference to uninitialized digits. */
3162 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003163#endif
Tim Peters44121a62002-08-12 06:17:58 +00003164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3166 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3167 assert(Py_SIZE(t1) >= 0);
3168 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3169 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3170 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 /* Zero-out the digits higher than the ah*bh copy. */
3173 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3174 if (i)
3175 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3176 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 /* 3. t2 <- al*bl, and copy into the low digits. */
3179 if ((t2 = k_mul(al, bl)) == NULL) {
3180 Py_DECREF(t1);
3181 goto fail;
3182 }
3183 assert(Py_SIZE(t2) >= 0);
3184 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3185 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 /* Zero out remaining digits. */
3188 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3189 if (i)
3190 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3193 * because it's fresher in cache.
3194 */
3195 i = Py_SIZE(ret) - shift; /* # digits after shift */
3196 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3197 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3200 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3203 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3204 Py_DECREF(ah);
3205 Py_DECREF(al);
3206 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 if (a == b) {
3209 t2 = t1;
3210 Py_INCREF(t2);
3211 }
3212 else if ((t2 = x_add(bh, bl)) == NULL) {
3213 Py_DECREF(t1);
3214 goto fail;
3215 }
3216 Py_DECREF(bh);
3217 Py_DECREF(bl);
3218 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 t3 = k_mul(t1, t2);
3221 Py_DECREF(t1);
3222 Py_DECREF(t2);
3223 if (t3 == NULL) goto fail;
3224 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 /* Add t3. It's not obvious why we can't run out of room here.
3227 * See the (*) comment after this function.
3228 */
3229 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3230 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003233
Mark Dickinson22b20182010-05-10 21:27:53 +00003234 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 Py_XDECREF(ret);
3236 Py_XDECREF(ah);
3237 Py_XDECREF(al);
3238 Py_XDECREF(bh);
3239 Py_XDECREF(bl);
3240 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003241}
3242
Tim Petersd6974a52002-08-13 20:37:51 +00003243/* (*) Why adding t3 can't "run out of room" above.
3244
Tim Petersab86c2b2002-08-15 20:06:00 +00003245Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3246to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003247
Tim Petersab86c2b2002-08-15 20:06:00 +000032481. For any integer i, i = c(i/2) + f(i/2). In particular,
3249 bsize = c(bsize/2) + f(bsize/2).
32502. shift = f(bsize/2)
32513. asize <= bsize
32524. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3253 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003254
Tim Petersab86c2b2002-08-15 20:06:00 +00003255We allocated asize + bsize result digits, and add t3 into them at an offset
3256of shift. This leaves asize+bsize-shift allocated digit positions for t3
3257to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3258asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003259
Tim Petersab86c2b2002-08-15 20:06:00 +00003260bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3261at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003262
Tim Petersab86c2b2002-08-15 20:06:00 +00003263If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3264digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3265most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003266
Tim Petersab86c2b2002-08-15 20:06:00 +00003267The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003268
Tim Petersab86c2b2002-08-15 20:06:00 +00003269 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003270
Tim Petersab86c2b2002-08-15 20:06:00 +00003271and we have asize + c(bsize/2) available digit positions. We need to show
3272this is always enough. An instance of c(bsize/2) cancels out in both, so
3273the question reduces to whether asize digits is enough to hold
3274(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3275then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3276asize 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 +00003277digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003278asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003279c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3280is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3281bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003282
Tim Peters48d52c02002-08-14 17:07:32 +00003283Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3284clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3285ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003286*/
3287
Tim Peters60004642002-08-12 22:01:34 +00003288/* b has at least twice the digits of a, and a is big enough that Karatsuba
3289 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3290 * of slices, each with a->ob_size digits, and multiply the slices by a,
3291 * one at a time. This gives k_mul balanced inputs to work with, and is
3292 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003293 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003294 * single-width slice overlap between successive partial sums).
3295 */
3296static PyLongObject *
3297k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 const Py_ssize_t asize = ABS(Py_SIZE(a));
3300 Py_ssize_t bsize = ABS(Py_SIZE(b));
3301 Py_ssize_t nbdone; /* # of b digits already multiplied */
3302 PyLongObject *ret;
3303 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 assert(asize > KARATSUBA_CUTOFF);
3306 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 /* Allocate result space, and zero it out. */
3309 ret = _PyLong_New(asize + bsize);
3310 if (ret == NULL)
3311 return NULL;
3312 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 /* Successive slices of b are copied into bslice. */
3315 bslice = _PyLong_New(asize);
3316 if (bslice == NULL)
3317 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 nbdone = 0;
3320 while (bsize > 0) {
3321 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003322 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 /* Multiply the next slice of b by a. */
3325 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3326 nbtouse * sizeof(digit));
3327 Py_SIZE(bslice) = nbtouse;
3328 product = k_mul(a, bslice);
3329 if (product == NULL)
3330 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 /* Add into result. */
3333 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3334 product->ob_digit, Py_SIZE(product));
3335 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 bsize -= nbtouse;
3338 nbdone += nbtouse;
3339 }
Tim Peters60004642002-08-12 22:01:34 +00003340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 Py_DECREF(bslice);
3342 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003343
Mark Dickinson22b20182010-05-10 21:27:53 +00003344 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 Py_DECREF(ret);
3346 Py_XDECREF(bslice);
3347 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003348}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003349
3350static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003351long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 /* fast path for single-digit multiplication */
3358 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3359 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003360#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003362#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 /* if we don't have long long then we're almost certainly
3364 using 15-bit digits, so v will fit in a long. In the
3365 unlikely event that we're using 30-bit digits on a platform
3366 without long long, a large v will just cause us to fall
3367 through to the general multiplication code below. */
3368 if (v >= LONG_MIN && v <= LONG_MAX)
3369 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003370#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 z = k_mul(a, b);
3374 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003375 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3376 _PyLong_Negate(&z);
3377 if (z == NULL)
3378 return NULL;
3379 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003381}
3382
Guido van Rossume32e0141992-01-19 16:31:05 +00003383/* The / and % operators are now defined in terms of divmod().
3384 The expression a mod b has the value a - b*floor(a/b).
3385 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003386 |a| by |b|, with the sign of a. This is also expressed
3387 as a - b*trunc(a/b), if trunc truncates towards zero.
3388 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 a b a rem b a mod b
3390 13 10 3 3
3391 -13 10 -3 7
3392 13 -10 3 -7
3393 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003394 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003395 have different signs. We then subtract one from the 'div'
3396 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003397
Tim Peters47e52ee2004-08-30 02:44:38 +00003398/* Compute
3399 * *pdiv, *pmod = divmod(v, w)
3400 * NULL can be passed for pdiv or pmod, in which case that part of
3401 * the result is simply thrown away. The caller owns a reference to
3402 * each of these it requests (does not pass NULL for).
3403 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003404static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003405l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 if (long_divrem(v, w, &div, &mod) < 0)
3411 return -1;
3412 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3413 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3414 PyLongObject *temp;
3415 PyLongObject *one;
3416 temp = (PyLongObject *) long_add(mod, w);
3417 Py_DECREF(mod);
3418 mod = temp;
3419 if (mod == NULL) {
3420 Py_DECREF(div);
3421 return -1;
3422 }
3423 one = (PyLongObject *) PyLong_FromLong(1L);
3424 if (one == NULL ||
3425 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3426 Py_DECREF(mod);
3427 Py_DECREF(div);
3428 Py_XDECREF(one);
3429 return -1;
3430 }
3431 Py_DECREF(one);
3432 Py_DECREF(div);
3433 div = temp;
3434 }
3435 if (pdiv != NULL)
3436 *pdiv = div;
3437 else
3438 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 if (pmod != NULL)
3441 *pmod = mod;
3442 else
3443 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003446}
3447
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003448static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003449long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 CHECK_BINOP(a, b);
3454 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3455 div = NULL;
3456 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003457}
3458
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003459/* PyLong/PyLong -> float, with correctly rounded result. */
3460
3461#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3462#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3463
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003464static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003465long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 PyLongObject *a, *b, *x;
3468 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3469 digit mask, low;
3470 int inexact, negate, a_is_small, b_is_small;
3471 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 CHECK_BINOP(v, w);
3474 a = (PyLongObject *)v;
3475 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 /*
3478 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3481 1. choose a suitable integer 'shift'
3482 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3483 3. adjust x for correct rounding
3484 4. convert x to a double dx with the same value
3485 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3490 returns either 0.0 or -0.0, depending on the sign of b. For a and
3491 b both nonzero, ignore signs of a and b, and add the sign back in
3492 at the end. Now write a_bits and b_bits for the bit lengths of a
3493 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3494 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3499 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3500 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3501 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 1. The integer 'shift' is chosen so that x has the right number of
3506 bits for a double, plus two or three extra bits that will be used
3507 in the rounding decisions. Writing a_bits and b_bits for the
3508 number of significant bits in a and b respectively, a
3509 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 This is fine in the usual case, but if a/b is smaller than the
3514 smallest normal float then it can lead to double rounding on an
3515 IEEE 754 platform, giving incorrectly rounded results. So we
3516 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 2. The quantity x is computed by first shifting a (left -shift bits
3521 if shift <= 0, right shift bits if shift > 0) and then dividing by
3522 b. For both the shift and the division, we keep track of whether
3523 the result is inexact, in a flag 'inexact'; this information is
3524 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 With the choice of shift above, together with our assumption that
3527 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3528 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3531 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 For float representability, we need x/2**extra_bits <
3536 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3537 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 To round, we just modify the bottom digit of x in-place; this can
3542 end up giving a digit with value > PyLONG_MASK, but that's not a
3543 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 With the original choices for shift above, extra_bits will always
3546 be 2 or 3. Then rounding under the round-half-to-even rule, we
3547 round up iff the most significant of the extra bits is 1, and
3548 either: (a) the computation of x in step 2 had an inexact result,
3549 or (b) at least one other of the extra bits is 1, or (c) the least
3550 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 4. Conversion to a double is straightforward; all floating-point
3553 operations involved in the conversion are exact, so there's no
3554 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3557 The result will always be exactly representable as a double, except
3558 in the case that it overflows. To avoid dependence on the exact
3559 behaviour of ldexp on overflow, we check for overflow before
3560 applying ldexp. The result of ldexp is adjusted for sign before
3561 returning.
3562 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 /* Reduce to case where a and b are both positive. */
3565 a_size = ABS(Py_SIZE(a));
3566 b_size = ABS(Py_SIZE(b));
3567 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3568 if (b_size == 0) {
3569 PyErr_SetString(PyExc_ZeroDivisionError,
3570 "division by zero");
3571 goto error;
3572 }
3573 if (a_size == 0)
3574 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 /* Fast path for a and b small (exactly representable in a double).
3577 Relies on floating-point division being correctly rounded; results
3578 may be subject to double rounding on x86 machines that operate with
3579 the x87 FPU set to 64-bit precision. */
3580 a_is_small = a_size <= MANT_DIG_DIGITS ||
3581 (a_size == MANT_DIG_DIGITS+1 &&
3582 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3583 b_is_small = b_size <= MANT_DIG_DIGITS ||
3584 (b_size == MANT_DIG_DIGITS+1 &&
3585 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3586 if (a_is_small && b_is_small) {
3587 double da, db;
3588 da = a->ob_digit[--a_size];
3589 while (a_size > 0)
3590 da = da * PyLong_BASE + a->ob_digit[--a_size];
3591 db = b->ob_digit[--b_size];
3592 while (b_size > 0)
3593 db = db * PyLong_BASE + b->ob_digit[--b_size];
3594 result = da / db;
3595 goto success;
3596 }
Tim Peterse2a60002001-09-04 06:17:36 +00003597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 /* Catch obvious cases of underflow and overflow */
3599 diff = a_size - b_size;
3600 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3601 /* Extreme overflow */
3602 goto overflow;
3603 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3604 /* Extreme underflow */
3605 goto underflow_or_zero;
3606 /* Next line is now safe from overflowing a Py_ssize_t */
3607 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3608 bits_in_digit(b->ob_digit[b_size - 1]);
3609 /* Now diff = a_bits - b_bits. */
3610 if (diff > DBL_MAX_EXP)
3611 goto overflow;
3612 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3613 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003616 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 /* x = abs(a * 2**-shift) */
3621 if (shift <= 0) {
3622 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3623 digit rem;
3624 /* x = a << -shift */
3625 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3626 /* In practice, it's probably impossible to end up
3627 here. Both a and b would have to be enormous,
3628 using close to SIZE_T_MAX bytes of memory each. */
3629 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003630 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 goto error;
3632 }
3633 x = _PyLong_New(a_size + shift_digits + 1);
3634 if (x == NULL)
3635 goto error;
3636 for (i = 0; i < shift_digits; i++)
3637 x->ob_digit[i] = 0;
3638 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3639 a_size, -shift % PyLong_SHIFT);
3640 x->ob_digit[a_size + shift_digits] = rem;
3641 }
3642 else {
3643 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3644 digit rem;
3645 /* x = a >> shift */
3646 assert(a_size >= shift_digits);
3647 x = _PyLong_New(a_size - shift_digits);
3648 if (x == NULL)
3649 goto error;
3650 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3651 a_size - shift_digits, shift % PyLong_SHIFT);
3652 /* set inexact if any of the bits shifted out is nonzero */
3653 if (rem)
3654 inexact = 1;
3655 while (!inexact && shift_digits > 0)
3656 if (a->ob_digit[--shift_digits])
3657 inexact = 1;
3658 }
3659 long_normalize(x);
3660 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3663 reference to x, so it's safe to modify it in-place. */
3664 if (b_size == 1) {
3665 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3666 b->ob_digit[0]);
3667 long_normalize(x);
3668 if (rem)
3669 inexact = 1;
3670 }
3671 else {
3672 PyLongObject *div, *rem;
3673 div = x_divrem(x, b, &rem);
3674 Py_DECREF(x);
3675 x = div;
3676 if (x == NULL)
3677 goto error;
3678 if (Py_SIZE(rem))
3679 inexact = 1;
3680 Py_DECREF(rem);
3681 }
3682 x_size = ABS(Py_SIZE(x));
3683 assert(x_size > 0); /* result of division is never zero */
3684 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003687 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 /* Round by directly modifying the low digit of x. */
3691 mask = (digit)1 << (extra_bits - 1);
3692 low = x->ob_digit[0] | inexact;
3693 if (low & mask && low & (3*mask-1))
3694 low += mask;
3695 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 /* Convert x to a double dx; the conversion is exact. */
3698 dx = x->ob_digit[--x_size];
3699 while (x_size > 0)
3700 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3701 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 /* Check whether ldexp result will overflow a double. */
3704 if (shift + x_bits >= DBL_MAX_EXP &&
3705 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3706 goto overflow;
3707 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003708
3709 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003711
3712 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003714
3715 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 PyErr_SetString(PyExc_OverflowError,
3717 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003718 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003720}
3721
3722static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003723long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 CHECK_BINOP(a, b);
3728
3729 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3730 mod = NULL;
3731 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003732}
3733
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003734static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003735long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 PyLongObject *div, *mod;
3738 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3743 return NULL;
3744 }
3745 z = PyTuple_New(2);
3746 if (z != NULL) {
3747 PyTuple_SetItem(z, 0, (PyObject *) div);
3748 PyTuple_SetItem(z, 1, (PyObject *) mod);
3749 }
3750 else {
3751 Py_DECREF(div);
3752 Py_DECREF(mod);
3753 }
3754 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003755}
3756
Tim Peters47e52ee2004-08-30 02:44:38 +00003757/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003758static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003759long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3762 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 PyLongObject *z = NULL; /* accumulated result */
3765 Py_ssize_t i, j, k; /* counters */
3766 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 /* 5-ary values. If the exponent is large enough, table is
3769 * precomputed so that table[i] == a**i % c for i in range(32).
3770 */
3771 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3772 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 /* a, b, c = v, w, x */
3775 CHECK_BINOP(v, w);
3776 a = (PyLongObject*)v; Py_INCREF(a);
3777 b = (PyLongObject*)w; Py_INCREF(b);
3778 if (PyLong_Check(x)) {
3779 c = (PyLongObject *)x;
3780 Py_INCREF(x);
3781 }
3782 else if (x == Py_None)
3783 c = NULL;
3784 else {
3785 Py_DECREF(a);
3786 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003787 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 }
Tim Peters4c483c42001-09-05 06:24:58 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3791 if (c) {
3792 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003793 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 goto Error;
3795 }
3796 else {
3797 /* else return a float. This works because we know
3798 that this calls float_pow() which converts its
3799 arguments to double. */
3800 Py_DECREF(a);
3801 Py_DECREF(b);
3802 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3803 }
3804 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 if (c) {
3807 /* if modulus == 0:
3808 raise ValueError() */
3809 if (Py_SIZE(c) == 0) {
3810 PyErr_SetString(PyExc_ValueError,
3811 "pow() 3rd argument cannot be 0");
3812 goto Error;
3813 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 /* if modulus < 0:
3816 negativeOutput = True
3817 modulus = -modulus */
3818 if (Py_SIZE(c) < 0) {
3819 negativeOutput = 1;
3820 temp = (PyLongObject *)_PyLong_Copy(c);
3821 if (temp == NULL)
3822 goto Error;
3823 Py_DECREF(c);
3824 c = temp;
3825 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02003826 _PyLong_Negate(&c);
3827 if (c == NULL)
3828 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 /* if modulus == 1:
3832 return 0 */
3833 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3834 z = (PyLongObject *)PyLong_FromLong(0L);
3835 goto Done;
3836 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 /* if base < 0:
3839 base = base % modulus
3840 Having the base positive just makes things easier. */
3841 if (Py_SIZE(a) < 0) {
3842 if (l_divmod(a, c, NULL, &temp) < 0)
3843 goto Error;
3844 Py_DECREF(a);
3845 a = temp;
3846 temp = NULL;
3847 }
3848 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 /* At this point a, b, and c are guaranteed non-negative UNLESS
3851 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 z = (PyLongObject *)PyLong_FromLong(1L);
3854 if (z == NULL)
3855 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 /* Perform a modular reduction, X = X % c, but leave X alone if c
3858 * is NULL.
3859 */
3860#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003861 do { \
3862 if (c != NULL) { \
3863 if (l_divmod(X, c, NULL, &temp) < 0) \
3864 goto Error; \
3865 Py_XDECREF(X); \
3866 X = temp; \
3867 temp = NULL; \
3868 } \
3869 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 /* Multiply two values, then reduce the result:
3872 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003873#define MULT(X, Y, result) \
3874 do { \
3875 temp = (PyLongObject *)long_mul(X, Y); \
3876 if (temp == NULL) \
3877 goto Error; \
3878 Py_XDECREF(result); \
3879 result = temp; \
3880 temp = NULL; \
3881 REDUCE(result); \
3882 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3885 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3886 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3887 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3888 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003891 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003893 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 }
3895 }
3896 }
3897 else {
3898 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3899 Py_INCREF(z); /* still holds 1L */
3900 table[0] = z;
3901 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003902 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3905 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3908 const int index = (bi >> j) & 0x1f;
3909 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003910 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003912 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 }
3914 }
3915 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 if (negativeOutput && (Py_SIZE(z) != 0)) {
3918 temp = (PyLongObject *)long_sub(z, c);
3919 if (temp == NULL)
3920 goto Error;
3921 Py_DECREF(z);
3922 z = temp;
3923 temp = NULL;
3924 }
3925 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003926
Mark Dickinson22b20182010-05-10 21:27:53 +00003927 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02003928 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003930 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3932 for (i = 0; i < 32; ++i)
3933 Py_XDECREF(table[i]);
3934 }
3935 Py_DECREF(a);
3936 Py_DECREF(b);
3937 Py_XDECREF(c);
3938 Py_XDECREF(temp);
3939 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003940}
3941
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003942static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003943long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 /* Implement ~x as -(x+1) */
3946 PyLongObject *x;
3947 PyLongObject *w;
3948 if (ABS(Py_SIZE(v)) <=1)
3949 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3950 w = (PyLongObject *)PyLong_FromLong(1L);
3951 if (w == NULL)
3952 return NULL;
3953 x = (PyLongObject *) long_add(v, w);
3954 Py_DECREF(w);
3955 if (x == NULL)
3956 return NULL;
3957 Py_SIZE(x) = -(Py_SIZE(x));
3958 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003959}
3960
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003961static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003962long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 PyLongObject *z;
3965 if (ABS(Py_SIZE(v)) <= 1)
3966 return PyLong_FromLong(-MEDIUM_VALUE(v));
3967 z = (PyLongObject *)_PyLong_Copy(v);
3968 if (z != NULL)
3969 Py_SIZE(z) = -(Py_SIZE(v));
3970 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003971}
3972
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003973static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003974long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 if (Py_SIZE(v) < 0)
3977 return long_neg(v);
3978 else
3979 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003980}
3981
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003982static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003983long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003986}
3987
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003988static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003989long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 PyLongObject *z = NULL;
3992 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3993 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 if (Py_SIZE(a) < 0) {
3998 /* Right shifting negative numbers is harder */
3999 PyLongObject *a1, *a2;
4000 a1 = (PyLongObject *) long_invert(a);
4001 if (a1 == NULL)
4002 goto rshift_error;
4003 a2 = (PyLongObject *) long_rshift(a1, b);
4004 Py_DECREF(a1);
4005 if (a2 == NULL)
4006 goto rshift_error;
4007 z = (PyLongObject *) long_invert(a2);
4008 Py_DECREF(a2);
4009 }
4010 else {
4011 shiftby = PyLong_AsSsize_t((PyObject *)b);
4012 if (shiftby == -1L && PyErr_Occurred())
4013 goto rshift_error;
4014 if (shiftby < 0) {
4015 PyErr_SetString(PyExc_ValueError,
4016 "negative shift count");
4017 goto rshift_error;
4018 }
4019 wordshift = shiftby / PyLong_SHIFT;
4020 newsize = ABS(Py_SIZE(a)) - wordshift;
4021 if (newsize <= 0)
4022 return PyLong_FromLong(0);
4023 loshift = shiftby % PyLong_SHIFT;
4024 hishift = PyLong_SHIFT - loshift;
4025 lomask = ((digit)1 << hishift) - 1;
4026 himask = PyLong_MASK ^ lomask;
4027 z = _PyLong_New(newsize);
4028 if (z == NULL)
4029 goto rshift_error;
4030 if (Py_SIZE(a) < 0)
4031 Py_SIZE(z) = -(Py_SIZE(z));
4032 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4033 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4034 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004035 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 }
4037 z = long_normalize(z);
4038 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004039 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004041
Guido van Rossumc6913e71991-11-19 20:26:46 +00004042}
4043
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004044static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004045long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 /* This version due to Tim Peters */
4048 PyLongObject *a = (PyLongObject*)v;
4049 PyLongObject *b = (PyLongObject*)w;
4050 PyLongObject *z = NULL;
4051 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4052 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 shiftby = PyLong_AsSsize_t((PyObject *)b);
4057 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004058 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 if (shiftby < 0) {
4060 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004061 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 }
4063 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4064 wordshift = shiftby / PyLong_SHIFT;
4065 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 oldsize = ABS(Py_SIZE(a));
4068 newsize = oldsize + wordshift;
4069 if (remshift)
4070 ++newsize;
4071 z = _PyLong_New(newsize);
4072 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004073 return NULL;
4074 if (Py_SIZE(a) < 0) {
4075 assert(Py_REFCNT(z) == 1);
4076 Py_SIZE(z) = -Py_SIZE(z);
4077 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 for (i = 0; i < wordshift; i++)
4079 z->ob_digit[i] = 0;
4080 accum = 0;
4081 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4082 accum |= (twodigits)a->ob_digit[j] << remshift;
4083 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4084 accum >>= PyLong_SHIFT;
4085 }
4086 if (remshift)
4087 z->ob_digit[newsize-1] = (digit)accum;
4088 else
4089 assert(!accum);
4090 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004092}
4093
Mark Dickinson27a87a22009-10-25 20:43:34 +00004094/* Compute two's complement of digit vector a[0:m], writing result to
4095 z[0:m]. The digit vector a need not be normalized, but should not
4096 be entirely zero. a and z may point to the same digit vector. */
4097
4098static void
4099v_complement(digit *z, digit *a, Py_ssize_t m)
4100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 Py_ssize_t i;
4102 digit carry = 1;
4103 for (i = 0; i < m; ++i) {
4104 carry += a[i] ^ PyLong_MASK;
4105 z[i] = carry & PyLong_MASK;
4106 carry >>= PyLong_SHIFT;
4107 }
4108 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004109}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004110
4111/* Bitwise and/xor/or operations */
4112
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004113static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004114long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004115 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004116 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 int nega, negb, negz;
4119 Py_ssize_t size_a, size_b, size_z, i;
4120 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 /* Bitwise operations for negative numbers operate as though
4123 on a two's complement representation. So convert arguments
4124 from sign-magnitude to two's complement, and convert the
4125 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 /* If a is negative, replace it by its two's complement. */
4128 size_a = ABS(Py_SIZE(a));
4129 nega = Py_SIZE(a) < 0;
4130 if (nega) {
4131 z = _PyLong_New(size_a);
4132 if (z == NULL)
4133 return NULL;
4134 v_complement(z->ob_digit, a->ob_digit, size_a);
4135 a = z;
4136 }
4137 else
4138 /* Keep reference count consistent. */
4139 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 /* Same for b. */
4142 size_b = ABS(Py_SIZE(b));
4143 negb = Py_SIZE(b) < 0;
4144 if (negb) {
4145 z = _PyLong_New(size_b);
4146 if (z == NULL) {
4147 Py_DECREF(a);
4148 return NULL;
4149 }
4150 v_complement(z->ob_digit, b->ob_digit, size_b);
4151 b = z;
4152 }
4153 else
4154 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 /* Swap a and b if necessary to ensure size_a >= size_b. */
4157 if (size_a < size_b) {
4158 z = a; a = b; b = z;
4159 size_z = size_a; size_a = size_b; size_b = size_z;
4160 negz = nega; nega = negb; negb = negz;
4161 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 /* JRH: The original logic here was to allocate the result value (z)
4164 as the longer of the two operands. However, there are some cases
4165 where the result is guaranteed to be shorter than that: AND of two
4166 positives, OR of two negatives: use the shorter number. AND with
4167 mixed signs: use the positive number. OR with mixed signs: use the
4168 negative number.
4169 */
4170 switch (op) {
4171 case '^':
4172 negz = nega ^ negb;
4173 size_z = size_a;
4174 break;
4175 case '&':
4176 negz = nega & negb;
4177 size_z = negb ? size_a : size_b;
4178 break;
4179 case '|':
4180 negz = nega | negb;
4181 size_z = negb ? size_b : size_a;
4182 break;
4183 default:
4184 PyErr_BadArgument();
4185 return NULL;
4186 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 /* We allow an extra digit if z is negative, to make sure that
4189 the final two's complement of z doesn't overflow. */
4190 z = _PyLong_New(size_z + negz);
4191 if (z == NULL) {
4192 Py_DECREF(a);
4193 Py_DECREF(b);
4194 return NULL;
4195 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 /* Compute digits for overlap of a and b. */
4198 switch(op) {
4199 case '&':
4200 for (i = 0; i < size_b; ++i)
4201 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4202 break;
4203 case '|':
4204 for (i = 0; i < size_b; ++i)
4205 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4206 break;
4207 case '^':
4208 for (i = 0; i < size_b; ++i)
4209 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4210 break;
4211 default:
4212 PyErr_BadArgument();
4213 return NULL;
4214 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 /* Copy any remaining digits of a, inverting if necessary. */
4217 if (op == '^' && negb)
4218 for (; i < size_z; ++i)
4219 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4220 else if (i < size_z)
4221 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4222 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 /* Complement result if negative. */
4225 if (negz) {
4226 Py_SIZE(z) = -(Py_SIZE(z));
4227 z->ob_digit[size_z] = PyLong_MASK;
4228 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4229 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 Py_DECREF(a);
4232 Py_DECREF(b);
4233 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004234}
4235
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004236static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004237long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 PyObject *c;
4240 CHECK_BINOP(a, b);
4241 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4242 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004243}
4244
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004245static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004246long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 PyObject *c;
4249 CHECK_BINOP(a, b);
4250 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4251 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004252}
4253
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004254static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004255long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 PyObject *c;
4258 CHECK_BINOP(a, b);
4259 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4260 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004261}
4262
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004263static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004264long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 if (PyLong_CheckExact(v))
4267 Py_INCREF(v);
4268 else
4269 v = _PyLong_Copy((PyLongObject *)v);
4270 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004271}
4272
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004273static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004274long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 double result;
4277 result = PyLong_AsDouble(v);
4278 if (result == -1.0 && PyErr_Occurred())
4279 return NULL;
4280 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004281}
4282
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004283static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004284long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004285
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286static PyObject *
4287long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4288{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004289 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004290 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004291 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 if (type != &PyLong_Type)
4294 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004295 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4296 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004298 if (x == NULL) {
4299 if (obase != NULL) {
4300 PyErr_SetString(PyExc_TypeError,
4301 "int() missing string argument");
4302 return NULL;
4303 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004305 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004306 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004308
Gregory P. Smitha689e522012-12-25 22:38:32 -08004309 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004310 if (base == -1 && PyErr_Occurred())
4311 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004312 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004313 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004314 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004315 return NULL;
4316 }
4317
4318 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004319 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4321 /* Since PyLong_FromString doesn't have a length parameter,
4322 * check here for possible NULs in the string. */
4323 char *string;
4324 Py_ssize_t size = Py_SIZE(x);
4325 if (PyByteArray_Check(x))
4326 string = PyByteArray_AS_STRING(x);
4327 else
4328 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004329 if (strlen(string) != (size_t)size || !size) {
4330 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 x is a bytes or buffer, *and* a base is given. */
4332 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004333 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004334 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 return NULL;
4336 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004337 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 }
4339 else {
4340 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004341 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 return NULL;
4343 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004344}
4345
Guido van Rossumbef14172001-08-29 15:47:46 +00004346/* Wimpy, slow approach to tp_new calls for subtypes of long:
4347 first create a regular long from whatever arguments we got,
4348 then allocate a subtype instance and initialize it from
4349 the regular long. The regular long is then thrown away.
4350*/
4351static PyObject *
4352long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 PyLongObject *tmp, *newobj;
4355 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 assert(PyType_IsSubtype(type, &PyLong_Type));
4358 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4359 if (tmp == NULL)
4360 return NULL;
4361 assert(PyLong_CheckExact(tmp));
4362 n = Py_SIZE(tmp);
4363 if (n < 0)
4364 n = -n;
4365 newobj = (PyLongObject *)type->tp_alloc(type, n);
4366 if (newobj == NULL) {
4367 Py_DECREF(tmp);
4368 return NULL;
4369 }
4370 assert(PyLong_Check(newobj));
4371 Py_SIZE(newobj) = Py_SIZE(tmp);
4372 for (i = 0; i < n; i++)
4373 newobj->ob_digit[i] = tmp->ob_digit[i];
4374 Py_DECREF(tmp);
4375 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004376}
4377
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004378static PyObject *
4379long_getnewargs(PyLongObject *v)
4380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004382}
4383
Guido van Rossumb43daf72007-08-01 18:08:08 +00004384static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004385long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004387}
4388
4389static PyObject *
4390long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004392}
4393
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004394static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004395long__format__(PyObject *self, PyObject *args)
4396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004398 _PyUnicodeWriter writer;
4399 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4402 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004403
Victor Stinner8f674cc2013-04-17 23:02:17 +02004404 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004405 ret = _PyLong_FormatAdvancedWriter(
4406 &writer,
4407 self,
4408 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4409 if (ret == -1) {
4410 _PyUnicodeWriter_Dealloc(&writer);
4411 return NULL;
4412 }
4413 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004414}
4415
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004416/* Return a pair (q, r) such that a = b * q + r, and
4417 abs(r) <= abs(b)/2, with equality possible only if q is even.
4418 In other words, q == a / b, rounded to the nearest integer using
4419 round-half-to-even. */
4420
4421PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004422_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004423{
4424 PyLongObject *quo = NULL, *rem = NULL;
4425 PyObject *one = NULL, *twice_rem, *result, *temp;
4426 int cmp, quo_is_odd, quo_is_neg;
4427
4428 /* Equivalent Python code:
4429
4430 def divmod_near(a, b):
4431 q, r = divmod(a, b)
4432 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4433 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4434 # positive, 2 * r < b if b negative.
4435 greater_than_half = 2*r > b if b > 0 else 2*r < b
4436 exactly_half = 2*r == b
4437 if greater_than_half or exactly_half and q % 2 == 1:
4438 q += 1
4439 r -= b
4440 return q, r
4441
4442 */
4443 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4444 PyErr_SetString(PyExc_TypeError,
4445 "non-integer arguments in division");
4446 return NULL;
4447 }
4448
4449 /* Do a and b have different signs? If so, quotient is negative. */
4450 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4451
4452 one = PyLong_FromLong(1L);
4453 if (one == NULL)
4454 return NULL;
4455
4456 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4457 goto error;
4458
4459 /* compare twice the remainder with the divisor, to see
4460 if we need to adjust the quotient and remainder */
4461 twice_rem = long_lshift((PyObject *)rem, one);
4462 if (twice_rem == NULL)
4463 goto error;
4464 if (quo_is_neg) {
4465 temp = long_neg((PyLongObject*)twice_rem);
4466 Py_DECREF(twice_rem);
4467 twice_rem = temp;
4468 if (twice_rem == NULL)
4469 goto error;
4470 }
4471 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4472 Py_DECREF(twice_rem);
4473
4474 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4475 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4476 /* fix up quotient */
4477 if (quo_is_neg)
4478 temp = long_sub(quo, (PyLongObject *)one);
4479 else
4480 temp = long_add(quo, (PyLongObject *)one);
4481 Py_DECREF(quo);
4482 quo = (PyLongObject *)temp;
4483 if (quo == NULL)
4484 goto error;
4485 /* and remainder */
4486 if (quo_is_neg)
4487 temp = long_add(rem, (PyLongObject *)b);
4488 else
4489 temp = long_sub(rem, (PyLongObject *)b);
4490 Py_DECREF(rem);
4491 rem = (PyLongObject *)temp;
4492 if (rem == NULL)
4493 goto error;
4494 }
4495
4496 result = PyTuple_New(2);
4497 if (result == NULL)
4498 goto error;
4499
4500 /* PyTuple_SET_ITEM steals references */
4501 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4502 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4503 Py_DECREF(one);
4504 return result;
4505
4506 error:
4507 Py_XDECREF(quo);
4508 Py_XDECREF(rem);
4509 Py_XDECREF(one);
4510 return NULL;
4511}
4512
Eric Smith8c663262007-08-25 02:26:07 +00004513static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004514long_round(PyObject *self, PyObject *args)
4515{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004516 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004517
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004518 /* To round an integer m to the nearest 10**n (n positive), we make use of
4519 * the divmod_near operation, defined by:
4520 *
4521 * divmod_near(a, b) = (q, r)
4522 *
4523 * where q is the nearest integer to the quotient a / b (the
4524 * nearest even integer in the case of a tie) and r == a - q * b.
4525 * Hence q * b = a - r is the nearest multiple of b to a,
4526 * preferring even multiples in the case of a tie.
4527 *
4528 * So the nearest multiple of 10**n to m is:
4529 *
4530 * m - divmod_near(m, 10**n)[1].
4531 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4533 return NULL;
4534 if (o_ndigits == NULL)
4535 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004536
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004537 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 if (ndigits == NULL)
4539 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004540
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004541 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 if (Py_SIZE(ndigits) >= 0) {
4543 Py_DECREF(ndigits);
4544 return long_long(self);
4545 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004546
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004547 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4548 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004550 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004551 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004552 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004553
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004554 result = PyLong_FromLong(10L);
4555 if (result == NULL) {
4556 Py_DECREF(ndigits);
4557 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004559
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004560 temp = long_pow(result, ndigits, Py_None);
4561 Py_DECREF(ndigits);
4562 Py_DECREF(result);
4563 result = temp;
4564 if (result == NULL)
4565 return NULL;
4566
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004567 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004568 Py_DECREF(result);
4569 result = temp;
4570 if (result == NULL)
4571 return NULL;
4572
4573 temp = long_sub((PyLongObject *)self,
4574 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4575 Py_DECREF(result);
4576 result = temp;
4577
4578 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004579}
4580
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004581static PyObject *
4582long_sizeof(PyLongObject *v)
4583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4587 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004588}
4589
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004590static PyObject *
4591long_bit_length(PyLongObject *v)
4592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 PyLongObject *result, *x, *y;
4594 Py_ssize_t ndigits, msd_bits = 0;
4595 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 assert(v != NULL);
4598 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004600 ndigits = ABS(Py_SIZE(v));
4601 if (ndigits == 0)
4602 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 msd = v->ob_digit[ndigits-1];
4605 while (msd >= 32) {
4606 msd_bits += 6;
4607 msd >>= 6;
4608 }
4609 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4612 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 /* expression above may overflow; use Python integers instead */
4615 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4616 if (result == NULL)
4617 return NULL;
4618 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4619 if (x == NULL)
4620 goto error;
4621 y = (PyLongObject *)long_mul(result, x);
4622 Py_DECREF(x);
4623 if (y == NULL)
4624 goto error;
4625 Py_DECREF(result);
4626 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4629 if (x == NULL)
4630 goto error;
4631 y = (PyLongObject *)long_add(result, x);
4632 Py_DECREF(x);
4633 if (y == NULL)
4634 goto error;
4635 Py_DECREF(result);
4636 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004639
Mark Dickinson22b20182010-05-10 21:27:53 +00004640 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 Py_DECREF(result);
4642 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004643}
4644
4645PyDoc_STRVAR(long_bit_length_doc,
4646"int.bit_length() -> int\n\
4647\n\
4648Number of bits necessary to represent self in binary.\n\
4649>>> bin(37)\n\
4650'0b100101'\n\
4651>>> (37).bit_length()\n\
46526");
4653
Christian Heimes53876d92008-04-19 00:31:39 +00004654#if 0
4655static PyObject *
4656long_is_finite(PyObject *v)
4657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004659}
4660#endif
4661
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004662
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004663static PyObject *
4664long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 PyObject *byteorder_str;
4667 PyObject *is_signed_obj = NULL;
4668 Py_ssize_t length;
4669 int little_endian;
4670 int is_signed;
4671 PyObject *bytes;
4672 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4675 &length, &byteorder_str,
4676 &is_signed_obj))
4677 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 if (args != NULL && Py_SIZE(args) > 2) {
4680 PyErr_SetString(PyExc_TypeError,
4681 "'signed' is a keyword-only argument");
4682 return NULL;
4683 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4686 little_endian = 1;
4687 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4688 little_endian = 0;
4689 else {
4690 PyErr_SetString(PyExc_ValueError,
4691 "byteorder must be either 'little' or 'big'");
4692 return NULL;
4693 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 if (is_signed_obj != NULL) {
4696 int cmp = PyObject_IsTrue(is_signed_obj);
4697 if (cmp < 0)
4698 return NULL;
4699 is_signed = cmp ? 1 : 0;
4700 }
4701 else {
4702 /* If the signed argument was omitted, use False as the
4703 default. */
4704 is_signed = 0;
4705 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 if (length < 0) {
4708 PyErr_SetString(PyExc_ValueError,
4709 "length argument must be non-negative");
4710 return NULL;
4711 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 bytes = PyBytes_FromStringAndSize(NULL, length);
4714 if (bytes == NULL)
4715 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4718 length, little_endian, is_signed) < 0) {
4719 Py_DECREF(bytes);
4720 return NULL;
4721 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004724}
4725
Mark Dickinson078c2532010-01-30 18:06:17 +00004726PyDoc_STRVAR(long_to_bytes_doc,
4727"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004728\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004729Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004730\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004732raised if the integer is not representable with the given number of\n\
4733bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004734\n\
4735The byteorder argument determines the byte order used to represent the\n\
4736integer. If byteorder is 'big', the most significant byte is at the\n\
4737beginning of the byte array. If byteorder is 'little', the most\n\
4738significant byte is at the end of the byte array. To request the native\n\
4739byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4740\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004741The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004743is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004744
4745static PyObject *
4746long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 PyObject *byteorder_str;
4749 PyObject *is_signed_obj = NULL;
4750 int little_endian;
4751 int is_signed;
4752 PyObject *obj;
4753 PyObject *bytes;
4754 PyObject *long_obj;
4755 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4758 &obj, &byteorder_str,
4759 &is_signed_obj))
4760 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 if (args != NULL && Py_SIZE(args) > 2) {
4763 PyErr_SetString(PyExc_TypeError,
4764 "'signed' is a keyword-only argument");
4765 return NULL;
4766 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4769 little_endian = 1;
4770 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4771 little_endian = 0;
4772 else {
4773 PyErr_SetString(PyExc_ValueError,
4774 "byteorder must be either 'little' or 'big'");
4775 return NULL;
4776 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778 if (is_signed_obj != NULL) {
4779 int cmp = PyObject_IsTrue(is_signed_obj);
4780 if (cmp < 0)
4781 return NULL;
4782 is_signed = cmp ? 1 : 0;
4783 }
4784 else {
4785 /* If the signed argument was omitted, use False as the
4786 default. */
4787 is_signed = 0;
4788 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 bytes = PyObject_Bytes(obj);
4791 if (bytes == NULL)
4792 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004794 long_obj = _PyLong_FromByteArray(
4795 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4796 little_endian, is_signed);
4797 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 /* If from_bytes() was used on subclass, allocate new subclass
4800 * instance, initialize it with decoded long value and return it.
4801 */
4802 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4803 PyLongObject *newobj;
4804 int i;
4805 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 newobj = (PyLongObject *)type->tp_alloc(type, n);
4808 if (newobj == NULL) {
4809 Py_DECREF(long_obj);
4810 return NULL;
4811 }
4812 assert(PyLong_Check(newobj));
4813 Py_SIZE(newobj) = Py_SIZE(long_obj);
4814 for (i = 0; i < n; i++) {
4815 newobj->ob_digit[i] =
4816 ((PyLongObject *)long_obj)->ob_digit[i];
4817 }
4818 Py_DECREF(long_obj);
4819 return (PyObject *)newobj;
4820 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004822 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004823}
4824
Mark Dickinson078c2532010-01-30 18:06:17 +00004825PyDoc_STRVAR(long_from_bytes_doc,
4826"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4827\n\
4828Return the integer represented by the given array of bytes.\n\
4829\n\
4830The bytes argument must either support the buffer protocol or be an\n\
4831iterable object producing bytes. Bytes and bytearray are examples of\n\
4832built-in objects that support the buffer protocol.\n\
4833\n\
4834The byteorder argument determines the byte order used to represent the\n\
4835integer. If byteorder is 'big', the most significant byte is at the\n\
4836beginning of the byte array. If byteorder is 'little', the most\n\
4837significant byte is at the end of the byte array. To request the native\n\
4838byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4839\n\
4840The signed keyword-only argument indicates whether two's complement is\n\
4841used to represent the integer.");
4842
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004843static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4845 "Returns self, the complex conjugate of any int."},
4846 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4847 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004848#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4850 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004851#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 {"to_bytes", (PyCFunction)long_to_bytes,
4853 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4854 {"from_bytes", (PyCFunction)long_from_bytes,
4855 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4856 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4857 "Truncating an Integral returns itself."},
4858 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4859 "Flooring an Integral returns itself."},
4860 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4861 "Ceiling of an Integral returns itself."},
4862 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4863 "Rounding an Integral returns itself.\n"
4864 "Rounding with an ndigits argument also returns an integer."},
4865 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4866 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4867 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4868 "Returns size in memory, in bytes"},
4869 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004870};
4871
Guido van Rossumb43daf72007-08-01 18:08:08 +00004872static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004873 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004874 (getter)long_long, (setter)NULL,
4875 "the real part of a complex number",
4876 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004877 {"imag",
4878 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004879 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004880 NULL},
4881 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004882 (getter)long_long, (setter)NULL,
4883 "the numerator of a rational number in lowest terms",
4884 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004885 {"denominator",
4886 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004887 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004888 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004889 {NULL} /* Sentinel */
4890};
4891
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004892PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004893"int(x=0) -> integer\n\
4894int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004895\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004896Convert a number or string to an integer, or return 0 if no arguments\n\
4897are given. If x is a number, return x.__int__(). For floating point\n\
4898numbers, this truncates towards zero.\n\
4899\n\
4900If x is not a number or if base is given, then x must be a string,\n\
4901bytes, or bytearray instance representing an integer literal in the\n\
4902given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4903by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4904Base 0 means to interpret the base from the string as an integer literal.\n\
4905>>> int('0b100', base=0)\n\
49064");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004907
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004908static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004909 (binaryfunc)long_add, /*nb_add*/
4910 (binaryfunc)long_sub, /*nb_subtract*/
4911 (binaryfunc)long_mul, /*nb_multiply*/
4912 long_mod, /*nb_remainder*/
4913 long_divmod, /*nb_divmod*/
4914 long_pow, /*nb_power*/
4915 (unaryfunc)long_neg, /*nb_negative*/
4916 (unaryfunc)long_long, /*tp_positive*/
4917 (unaryfunc)long_abs, /*tp_absolute*/
4918 (inquiry)long_bool, /*tp_bool*/
4919 (unaryfunc)long_invert, /*nb_invert*/
4920 long_lshift, /*nb_lshift*/
4921 (binaryfunc)long_rshift, /*nb_rshift*/
4922 long_and, /*nb_and*/
4923 long_xor, /*nb_xor*/
4924 long_or, /*nb_or*/
4925 long_long, /*nb_int*/
4926 0, /*nb_reserved*/
4927 long_float, /*nb_float*/
4928 0, /* nb_inplace_add */
4929 0, /* nb_inplace_subtract */
4930 0, /* nb_inplace_multiply */
4931 0, /* nb_inplace_remainder */
4932 0, /* nb_inplace_power */
4933 0, /* nb_inplace_lshift */
4934 0, /* nb_inplace_rshift */
4935 0, /* nb_inplace_and */
4936 0, /* nb_inplace_xor */
4937 0, /* nb_inplace_or */
4938 long_div, /* nb_floor_divide */
4939 long_true_divide, /* nb_true_divide */
4940 0, /* nb_inplace_floor_divide */
4941 0, /* nb_inplace_true_divide */
4942 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004943};
4944
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004945PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4947 "int", /* tp_name */
4948 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4949 sizeof(digit), /* tp_itemsize */
4950 long_dealloc, /* tp_dealloc */
4951 0, /* tp_print */
4952 0, /* tp_getattr */
4953 0, /* tp_setattr */
4954 0, /* tp_reserved */
4955 long_to_decimal_string, /* tp_repr */
4956 &long_as_number, /* tp_as_number */
4957 0, /* tp_as_sequence */
4958 0, /* tp_as_mapping */
4959 (hashfunc)long_hash, /* tp_hash */
4960 0, /* tp_call */
4961 long_to_decimal_string, /* tp_str */
4962 PyObject_GenericGetAttr, /* tp_getattro */
4963 0, /* tp_setattro */
4964 0, /* tp_as_buffer */
4965 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4966 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4967 long_doc, /* tp_doc */
4968 0, /* tp_traverse */
4969 0, /* tp_clear */
4970 long_richcompare, /* tp_richcompare */
4971 0, /* tp_weaklistoffset */
4972 0, /* tp_iter */
4973 0, /* tp_iternext */
4974 long_methods, /* tp_methods */
4975 0, /* tp_members */
4976 long_getset, /* tp_getset */
4977 0, /* tp_base */
4978 0, /* tp_dict */
4979 0, /* tp_descr_get */
4980 0, /* tp_descr_set */
4981 0, /* tp_dictoffset */
4982 0, /* tp_init */
4983 0, /* tp_alloc */
4984 long_new, /* tp_new */
4985 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004986};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004987
Mark Dickinsonbd792642009-03-18 20:06:12 +00004988static PyTypeObject Int_InfoType;
4989
4990PyDoc_STRVAR(int_info__doc__,
4991"sys.int_info\n\
4992\n\
4993A struct sequence that holds information about Python's\n\
4994internal representation of integers. The attributes are read only.");
4995
4996static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004998 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005000};
5001
5002static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 "sys.int_info", /* name */
5004 int_info__doc__, /* doc */
5005 int_info_fields, /* fields */
5006 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005007};
5008
5009PyObject *
5010PyLong_GetInfo(void)
5011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 PyObject* int_info;
5013 int field = 0;
5014 int_info = PyStructSequence_New(&Int_InfoType);
5015 if (int_info == NULL)
5016 return NULL;
5017 PyStructSequence_SET_ITEM(int_info, field++,
5018 PyLong_FromLong(PyLong_SHIFT));
5019 PyStructSequence_SET_ITEM(int_info, field++,
5020 PyLong_FromLong(sizeof(digit)));
5021 if (PyErr_Occurred()) {
5022 Py_CLEAR(int_info);
5023 return NULL;
5024 }
5025 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005026}
5027
Guido van Rossumddefaf32007-01-14 03:31:43 +00005028int
5029_PyLong_Init(void)
5030{
5031#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 int ival, size;
5033 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005035 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5036 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5037 if (Py_TYPE(v) == &PyLong_Type) {
5038 /* The element is already initialized, most likely
5039 * the Python interpreter was initialized before.
5040 */
5041 Py_ssize_t refcnt;
5042 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5045 _Py_NewReference(op);
5046 /* _Py_NewReference sets the ref count to 1 but
5047 * the ref count might be larger. Set the refcnt
5048 * to the original refcnt + 1 */
5049 Py_REFCNT(op) = refcnt + 1;
5050 assert(Py_SIZE(op) == size);
5051 assert(v->ob_digit[0] == abs(ival));
5052 }
5053 else {
5054 PyObject_INIT(v, &PyLong_Type);
5055 }
5056 Py_SIZE(v) = size;
5057 v->ob_digit[0] = abs(ival);
5058 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005059#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 /* initialize int_info */
5061 if (Int_InfoType.tp_name == 0)
5062 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005065}
5066
5067void
5068PyLong_Fini(void)
5069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 /* Integers are currently statically allocated. Py_DECREF is not
5071 needed, but Python must forget about the reference or multiple
5072 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005073#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 int i;
5075 PyLongObject *v = small_ints;
5076 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5077 _Py_DEC_REFTOTAL;
5078 _Py_ForgetReference((PyObject*)v);
5079 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005080#endif
5081}