blob: 8748706e1e48d635026d02e871cb67b36ceb1296 [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 */
Victor Stinner08a80b12013-07-17 22:33:42 +020020#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
21 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 (Py_SIZE(x) == 0 ? (sdigit)0 : \
23 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024#define ABS(x) ((x) < 0 ? -(x) : (x))
25
Guido van Rossumddefaf32007-01-14 03:31:43 +000026#if NSMALLNEGINTS + NSMALLPOSINTS > 0
27/* Small integers are preallocated in this array so that they
28 can be shared.
29 The integers that are preallocated are those in the range
30 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
31*/
32static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
33#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010034Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000035#endif
36
Guido van Rossum7eaf8222007-06-18 17:58:50 +000037static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000038get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
41 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000042#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 if (ival >= 0)
44 quick_int_allocs++;
45 else
46 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000047#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000049}
50#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
52 return get_small_int((sdigit)ival); \
53 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000056maybe_small_long(PyLongObject *v)
57{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (v && ABS(Py_SIZE(v)) <= 1) {
59 sdigit ival = MEDIUM_VALUE(v);
60 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
61 Py_DECREF(v);
62 return (PyLongObject *)get_small_int(ival);
63 }
64 }
65 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000066}
Guido van Rossumddefaf32007-01-14 03:31:43 +000067#else
68#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000070#endif
71
Serhiy Storchaka95949422013-08-27 19:40:23 +030072/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000073 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020074Py_LOCAL_INLINE(void)
75_PyLong_Negate(PyLongObject **x_p)
76{
77 PyLongObject *x;
78
79 x = (PyLongObject *)*x_p;
80 if (Py_REFCNT(x) == 1) {
81 Py_SIZE(x) = -Py_SIZE(x);
82 return;
83 }
84
85 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
86 Py_DECREF(x);
87}
88
Serhiy Storchaka95949422013-08-27 19:40:23 +030089/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000090 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030091 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000092 */
Tim Peters0973b992004-08-29 22:16:50 +000093#define KARATSUBA_CUTOFF 70
94#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000095
Tim Peters47e52ee2004-08-30 02:44:38 +000096/* For exponentiation, use the binary left-to-right algorithm
97 * unless the exponent contains more than FIVEARY_CUTOFF digits.
98 * In that case, do 5 bits at a time. The potential drawback is that
99 * a table of 2**5 intermediate results is computed.
100 */
101#define FIVEARY_CUTOFF 8
102
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000103#define SIGCHECK(PyTryBlock) \
104 do { \
105 if (PyErr_CheckSignals()) PyTryBlock \
106 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000107
Serhiy Storchaka95949422013-08-27 19:40:23 +0300108/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000109 Doesn't attempt to free the storage--in most cases, due to the nature
110 of the algorithms used, this could save at most be one word anyway. */
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200113long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 Py_ssize_t j = ABS(Py_SIZE(v));
116 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 while (i > 0 && v->ob_digit[i-1] == 0)
119 --i;
120 if (i != j)
121 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
122 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000123}
124
Serhiy Storchaka95949422013-08-27 19:40:23 +0300125/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000126 Return NULL and set exception if we run out of memory. */
127
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000128#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000130
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000131PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000132_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 PyLongObject *result;
135 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
136 sizeof(digit)*size. Previous incarnations of this code used
137 sizeof(PyVarObject) instead of the offsetof, but this risks being
138 incorrect in the presence of padding between the PyVarObject header
139 and the digits. */
140 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
141 PyErr_SetString(PyExc_OverflowError,
142 "too many digits in integer");
143 return NULL;
144 }
145 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
146 size*sizeof(digit));
147 if (!result) {
148 PyErr_NoMemory();
149 return NULL;
150 }
151 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000152}
153
Tim Peters64b5ce32001-09-10 20:52:51 +0000154PyObject *
155_PyLong_Copy(PyLongObject *src)
156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyLongObject *result;
158 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 assert(src != NULL);
161 i = Py_SIZE(src);
162 if (i < 0)
163 i = -(i);
164 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100165 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 CHECK_SMALL_INT(ival);
167 }
168 result = _PyLong_New(i);
169 if (result != NULL) {
170 Py_SIZE(result) = Py_SIZE(src);
171 while (--i >= 0)
172 result->ob_digit[i] = src->ob_digit[i];
173 }
174 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000175}
176
Serhiy Storchaka95949422013-08-27 19:40:23 +0300177/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000178
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000180PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 PyLongObject *v;
183 unsigned long abs_ival;
184 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
185 int ndigits = 0;
186 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (ival < 0) {
191 /* negate: can't write this as abs_ival = -ival since that
192 invokes undefined behaviour when ival is LONG_MIN */
193 abs_ival = 0U-(unsigned long)ival;
194 sign = -1;
195 }
196 else {
197 abs_ival = (unsigned long)ival;
198 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 /* Fast path for single-digit ints */
201 if (!(abs_ival >> PyLong_SHIFT)) {
202 v = _PyLong_New(1);
203 if (v) {
204 Py_SIZE(v) = sign;
205 v->ob_digit[0] = Py_SAFE_DOWNCAST(
206 abs_ival, unsigned long, digit);
207 }
208 return (PyObject*)v;
209 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000210
Mark Dickinson249b8982009-04-27 19:41:00 +0000211#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 /* 2 digits */
213 if (!(abs_ival >> 2*PyLong_SHIFT)) {
214 v = _PyLong_New(2);
215 if (v) {
216 Py_SIZE(v) = 2*sign;
217 v->ob_digit[0] = Py_SAFE_DOWNCAST(
218 abs_ival & PyLong_MASK, unsigned long, digit);
219 v->ob_digit[1] = Py_SAFE_DOWNCAST(
220 abs_ival >> PyLong_SHIFT, unsigned long, digit);
221 }
222 return (PyObject*)v;
223 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000224#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 /* Larger numbers: loop to determine number of digits */
227 t = abs_ival;
228 while (t) {
229 ++ndigits;
230 t >>= PyLong_SHIFT;
231 }
232 v = _PyLong_New(ndigits);
233 if (v != NULL) {
234 digit *p = v->ob_digit;
235 Py_SIZE(v) = ndigits*sign;
236 t = abs_ival;
237 while (t) {
238 *p++ = Py_SAFE_DOWNCAST(
239 t & PyLong_MASK, unsigned long, digit);
240 t >>= PyLong_SHIFT;
241 }
242 }
243 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000244}
245
Serhiy Storchaka95949422013-08-27 19:40:23 +0300246/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000247
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000248PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000249PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 PyLongObject *v;
252 unsigned long t;
253 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 if (ival < PyLong_BASE)
256 return PyLong_FromLong(ival);
257 /* Count the number of Python digits. */
258 t = (unsigned long)ival;
259 while (t) {
260 ++ndigits;
261 t >>= PyLong_SHIFT;
262 }
263 v = _PyLong_New(ndigits);
264 if (v != NULL) {
265 digit *p = v->ob_digit;
266 Py_SIZE(v) = ndigits;
267 while (ival) {
268 *p++ = (digit)(ival & PyLong_MASK);
269 ival >>= PyLong_SHIFT;
270 }
271 }
272 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000273}
274
Serhiy Storchaka95949422013-08-27 19:40:23 +0300275/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000276
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000277PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000278PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyLongObject *v;
281 double frac;
282 int i, ndig, expo, neg;
283 neg = 0;
284 if (Py_IS_INFINITY(dval)) {
285 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000286 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return NULL;
288 }
289 if (Py_IS_NAN(dval)) {
290 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000291 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return NULL;
293 }
294 if (dval < 0.0) {
295 neg = 1;
296 dval = -dval;
297 }
298 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
299 if (expo <= 0)
300 return PyLong_FromLong(0L);
301 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
302 v = _PyLong_New(ndig);
303 if (v == NULL)
304 return NULL;
305 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
306 for (i = ndig; --i >= 0; ) {
307 digit bits = (digit)frac;
308 v->ob_digit[i] = bits;
309 frac = frac - (double)bits;
310 frac = ldexp(frac, PyLong_SHIFT);
311 }
312 if (neg)
313 Py_SIZE(v) = -(Py_SIZE(v));
314 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000315}
316
Thomas Wouters89f507f2006-12-13 04:49:30 +0000317/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
318 * anything about what happens when a signed integer operation overflows,
319 * and some compilers think they're doing you a favor by being "clever"
320 * then. The bit pattern for the largest postive signed long is
321 * (unsigned long)LONG_MAX, and for the smallest negative signed long
322 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
323 * However, some other compilers warn about applying unary minus to an
324 * unsigned operand. Hence the weird "0-".
325 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
327#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000328
Serhiy Storchaka95949422013-08-27 19:40:23 +0300329/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100330 method.
331
332 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
333 the result. Otherwise *overflow is 0.
334
335 For other errors (e.g., TypeError), return -1 and set an error condition.
336 In this case *overflow will be 0.
337*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000338
339long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000340PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200343 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 unsigned long x, prev;
345 long res;
346 Py_ssize_t i;
347 int sign;
348 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 *overflow = 0;
351 if (vv == NULL) {
352 PyErr_BadInternalCall();
353 return -1;
354 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 if (!PyLong_Check(vv)) {
357 PyNumberMethods *nb;
358 nb = vv->ob_type->tp_as_number;
359 if (nb == NULL || nb->nb_int == NULL) {
360 PyErr_SetString(PyExc_TypeError,
361 "an integer is required");
362 return -1;
363 }
364 vv = (*nb->nb_int) (vv);
365 if (vv == NULL)
366 return -1;
367 do_decref = 1;
368 if (!PyLong_Check(vv)) {
369 Py_DECREF(vv);
370 PyErr_SetString(PyExc_TypeError,
371 "nb_int should return int object");
372 return -1;
373 }
374 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 res = -1;
377 v = (PyLongObject *)vv;
378 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 switch (i) {
381 case -1:
382 res = -(sdigit)v->ob_digit[0];
383 break;
384 case 0:
385 res = 0;
386 break;
387 case 1:
388 res = v->ob_digit[0];
389 break;
390 default:
391 sign = 1;
392 x = 0;
393 if (i < 0) {
394 sign = -1;
395 i = -(i);
396 }
397 while (--i >= 0) {
398 prev = x;
399 x = (x << PyLong_SHIFT) | v->ob_digit[i];
400 if ((x >> PyLong_SHIFT) != prev) {
401 *overflow = sign;
402 goto exit;
403 }
404 }
405 /* Haven't lost any bits, but casting to long requires extra
406 * care (see comment above).
407 */
408 if (x <= (unsigned long)LONG_MAX) {
409 res = (long)x * sign;
410 }
411 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
412 res = LONG_MIN;
413 }
414 else {
415 *overflow = sign;
416 /* res is already set to -1 */
417 }
418 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000419 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (do_decref) {
421 Py_DECREF(vv);
422 }
423 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000424}
425
Serhiy Storchaka95949422013-08-27 19:40:23 +0300426/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100427 method. Return -1 and set an error if overflow occurs. */
428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000430PyLong_AsLong(PyObject *obj)
431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 int overflow;
433 long result = PyLong_AsLongAndOverflow(obj, &overflow);
434 if (overflow) {
435 /* XXX: could be cute and give a different
436 message for overflow == -1 */
437 PyErr_SetString(PyExc_OverflowError,
438 "Python int too large to convert to C long");
439 }
440 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000441}
442
Serhiy Storchaka95949422013-08-27 19:40:23 +0300443/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200444 method. Return -1 and set an error if overflow occurs. */
445
446int
447_PyLong_AsInt(PyObject *obj)
448{
449 int overflow;
450 long result = PyLong_AsLongAndOverflow(obj, &overflow);
451 if (overflow || result > INT_MAX || result < INT_MIN) {
452 /* XXX: could be cute and give a different
453 message for overflow == -1 */
454 PyErr_SetString(PyExc_OverflowError,
455 "Python int too large to convert to C int");
456 return -1;
457 }
458 return (int)result;
459}
460
Serhiy Storchaka95949422013-08-27 19:40:23 +0300461/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000462 Returns -1 and sets an error condition if overflow occurs. */
463
464Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000465PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200466 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 size_t x, prev;
468 Py_ssize_t i;
469 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (vv == NULL) {
472 PyErr_BadInternalCall();
473 return -1;
474 }
475 if (!PyLong_Check(vv)) {
476 PyErr_SetString(PyExc_TypeError, "an integer is required");
477 return -1;
478 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 v = (PyLongObject *)vv;
481 i = Py_SIZE(v);
482 switch (i) {
483 case -1: return -(sdigit)v->ob_digit[0];
484 case 0: return 0;
485 case 1: return v->ob_digit[0];
486 }
487 sign = 1;
488 x = 0;
489 if (i < 0) {
490 sign = -1;
491 i = -(i);
492 }
493 while (--i >= 0) {
494 prev = x;
495 x = (x << PyLong_SHIFT) | v->ob_digit[i];
496 if ((x >> PyLong_SHIFT) != prev)
497 goto overflow;
498 }
499 /* Haven't lost any bits, but casting to a signed type requires
500 * extra care (see comment above).
501 */
502 if (x <= (size_t)PY_SSIZE_T_MAX) {
503 return (Py_ssize_t)x * sign;
504 }
505 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
506 return PY_SSIZE_T_MIN;
507 }
508 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000509
Mark Dickinson22b20182010-05-10 21:27:53 +0000510 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 PyErr_SetString(PyExc_OverflowError,
512 "Python int too large to convert to C ssize_t");
513 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000514}
515
Serhiy Storchaka95949422013-08-27 19:40:23 +0300516/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000517 Returns -1 and sets an error condition if overflow occurs. */
518
519unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000520PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000521{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200522 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 unsigned long x, prev;
524 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 if (vv == NULL) {
527 PyErr_BadInternalCall();
528 return (unsigned long)-1;
529 }
530 if (!PyLong_Check(vv)) {
531 PyErr_SetString(PyExc_TypeError, "an integer is required");
532 return (unsigned long)-1;
533 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 v = (PyLongObject *)vv;
536 i = Py_SIZE(v);
537 x = 0;
538 if (i < 0) {
539 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000540 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 return (unsigned long) -1;
542 }
543 switch (i) {
544 case 0: return 0;
545 case 1: return v->ob_digit[0];
546 }
547 while (--i >= 0) {
548 prev = x;
549 x = (x << PyLong_SHIFT) | v->ob_digit[i];
550 if ((x >> PyLong_SHIFT) != prev) {
551 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100552 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000553 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 return (unsigned long) -1;
555 }
556 }
557 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000558}
559
Serhiy Storchaka95949422013-08-27 19:40:23 +0300560/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200561 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000562
563size_t
564PyLong_AsSize_t(PyObject *vv)
565{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200566 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 size_t x, prev;
568 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (vv == NULL) {
571 PyErr_BadInternalCall();
572 return (size_t) -1;
573 }
574 if (!PyLong_Check(vv)) {
575 PyErr_SetString(PyExc_TypeError, "an integer is required");
576 return (size_t)-1;
577 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 v = (PyLongObject *)vv;
580 i = Py_SIZE(v);
581 x = 0;
582 if (i < 0) {
583 PyErr_SetString(PyExc_OverflowError,
584 "can't convert negative value to size_t");
585 return (size_t) -1;
586 }
587 switch (i) {
588 case 0: return 0;
589 case 1: return v->ob_digit[0];
590 }
591 while (--i >= 0) {
592 prev = x;
593 x = (x << PyLong_SHIFT) | v->ob_digit[i];
594 if ((x >> PyLong_SHIFT) != prev) {
595 PyErr_SetString(PyExc_OverflowError,
596 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200597 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 }
599 }
600 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000601}
602
Serhiy Storchaka95949422013-08-27 19:40:23 +0300603/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000604 Returns -1 and sets an error condition if an error occurs. */
605
Guido van Rossumddefaf32007-01-14 03:31:43 +0000606static unsigned long
607_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000608{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200609 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 unsigned long x;
611 Py_ssize_t i;
612 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (vv == NULL || !PyLong_Check(vv)) {
615 PyErr_BadInternalCall();
616 return (unsigned long) -1;
617 }
618 v = (PyLongObject *)vv;
619 i = Py_SIZE(v);
620 switch (i) {
621 case 0: return 0;
622 case 1: return v->ob_digit[0];
623 }
624 sign = 1;
625 x = 0;
626 if (i < 0) {
627 sign = -1;
628 i = -i;
629 }
630 while (--i >= 0) {
631 x = (x << PyLong_SHIFT) | v->ob_digit[i];
632 }
633 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000634}
635
Guido van Rossumddefaf32007-01-14 03:31:43 +0000636unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200637PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyNumberMethods *nb;
640 PyLongObject *lo;
641 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (op && PyLong_Check(op))
644 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
647 nb->nb_int == NULL) {
648 PyErr_SetString(PyExc_TypeError, "an integer is required");
649 return (unsigned long)-1;
650 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 lo = (PyLongObject*) (*nb->nb_int) (op);
653 if (lo == NULL)
654 return (unsigned long)-1;
655 if (PyLong_Check(lo)) {
656 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
657 Py_DECREF(lo);
658 if (PyErr_Occurred())
659 return (unsigned long)-1;
660 return val;
661 }
662 else
663 {
664 Py_DECREF(lo);
665 PyErr_SetString(PyExc_TypeError,
666 "nb_int should return int object");
667 return (unsigned long)-1;
668 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000669}
670
Tim Peters5b8132f2003-01-31 15:52:05 +0000671int
672_PyLong_Sign(PyObject *vv)
673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 assert(v != NULL);
677 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000680}
681
Tim Petersbaefd9e2003-01-28 20:37:45 +0000682size_t
683_PyLong_NumBits(PyObject *vv)
684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyLongObject *v = (PyLongObject *)vv;
686 size_t result = 0;
687 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 assert(v != NULL);
690 assert(PyLong_Check(v));
691 ndigits = ABS(Py_SIZE(v));
692 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
693 if (ndigits > 0) {
694 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100695 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100697 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 do {
699 ++result;
700 if (result == 0)
701 goto Overflow;
702 msd >>= 1;
703 } while (msd);
704 }
705 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000706
Mark Dickinson22b20182010-05-10 21:27:53 +0000707 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
709 "to express in a platform size_t");
710 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000711}
712
Tim Peters2a9b3672001-06-11 21:23:58 +0000713PyObject *
714_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000716{
Mark Dickinson22b20182010-05-10 21:27:53 +0000717 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 int incr; /* direction to move pstartbyte */
719 const unsigned char* pendbyte; /* MSB of bytes */
720 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300721 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 PyLongObject* v; /* result */
723 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (n == 0)
726 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (little_endian) {
729 pstartbyte = bytes;
730 pendbyte = bytes + n - 1;
731 incr = 1;
732 }
733 else {
734 pstartbyte = bytes + n - 1;
735 pendbyte = bytes;
736 incr = -1;
737 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (is_signed)
740 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200743 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 is positive, and leading 0xff bytes if negative. */
745 {
746 size_t i;
747 const unsigned char* p = pendbyte;
748 const int pincr = -incr; /* search MSB to LSB */
749 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 for (i = 0; i < n; ++i, p += pincr) {
752 if (*p != insignficant)
753 break;
754 }
755 numsignificantbytes = n - i;
756 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
757 actually has 2 significant bytes. OTOH, 0xff0001 ==
758 -0x00ffff, so we wouldn't *need* to bump it there; but we
759 do for 0xffff = -0x0001. To be safe without bothering to
760 check every case, bump it regardless. */
761 if (is_signed && numsignificantbytes < n)
762 ++numsignificantbytes;
763 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000764
Serhiy Storchaka95949422013-08-27 19:40:23 +0300765 /* How many Python int digits do we need? We have
766 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
768 /* catch overflow before it happens */
769 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
770 PyErr_SetString(PyExc_OverflowError,
771 "byte array too long to convert to int");
772 return NULL;
773 }
774 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
775 v = _PyLong_New(ndigits);
776 if (v == NULL)
777 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 /* Copy the bits over. The tricky parts are computing 2's-comp on
780 the fly for signed numbers, and dealing with the mismatch between
781 8-bit bytes and (probably) 15-bit Python digits.*/
782 {
783 size_t i;
784 twodigits carry = 1; /* for 2's-comp calculation */
785 twodigits accum = 0; /* sliding register */
786 unsigned int accumbits = 0; /* number of bits in accum */
787 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
790 twodigits thisbyte = *p;
791 /* Compute correction for 2's comp, if needed. */
792 if (is_signed) {
793 thisbyte = (0xff ^ thisbyte) + carry;
794 carry = thisbyte >> 8;
795 thisbyte &= 0xff;
796 }
797 /* Because we're going LSB to MSB, thisbyte is
798 more significant than what's already in accum,
799 so needs to be prepended to accum. */
800 accum |= (twodigits)thisbyte << accumbits;
801 accumbits += 8;
802 if (accumbits >= PyLong_SHIFT) {
803 /* There's enough to fill a Python digit. */
804 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000805 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 ++idigit;
807 accum >>= PyLong_SHIFT;
808 accumbits -= PyLong_SHIFT;
809 assert(accumbits < PyLong_SHIFT);
810 }
811 }
812 assert(accumbits < PyLong_SHIFT);
813 if (accumbits) {
814 assert(idigit < ndigits);
815 v->ob_digit[idigit] = (digit)accum;
816 ++idigit;
817 }
818 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 Py_SIZE(v) = is_signed ? -idigit : idigit;
821 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000822}
823
824int
825_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 unsigned char* bytes, size_t n,
827 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000830 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000832 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
834 digit carry; /* for computing 2's-comp */
835 size_t j; /* # bytes filled */
836 unsigned char* p; /* pointer to next byte in bytes */
837 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (Py_SIZE(v) < 0) {
842 ndigits = -(Py_SIZE(v));
843 if (!is_signed) {
844 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000845 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 return -1;
847 }
848 do_twos_comp = 1;
849 }
850 else {
851 ndigits = Py_SIZE(v);
852 do_twos_comp = 0;
853 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (little_endian) {
856 p = bytes;
857 pincr = 1;
858 }
859 else {
860 p = bytes + n - 1;
861 pincr = -1;
862 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 /* Copy over all the Python digits.
865 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300866 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 normalized. */
868 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
869 j = 0;
870 accum = 0;
871 accumbits = 0;
872 carry = do_twos_comp ? 1 : 0;
873 for (i = 0; i < ndigits; ++i) {
874 digit thisdigit = v->ob_digit[i];
875 if (do_twos_comp) {
876 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
877 carry = thisdigit >> PyLong_SHIFT;
878 thisdigit &= PyLong_MASK;
879 }
880 /* Because we're going LSB to MSB, thisdigit is more
881 significant than what's already in accum, so needs to be
882 prepended to accum. */
883 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 /* The most-significant digit may be (probably is) at least
886 partly empty. */
887 if (i == ndigits - 1) {
888 /* Count # of sign bits -- they needn't be stored,
889 * although for signed conversion we need later to
890 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000891 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 while (s != 0) {
893 s >>= 1;
894 accumbits++;
895 }
896 }
897 else
898 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 /* Store as many bytes as possible. */
901 while (accumbits >= 8) {
902 if (j >= n)
903 goto Overflow;
904 ++j;
905 *p = (unsigned char)(accum & 0xff);
906 p += pincr;
907 accumbits -= 8;
908 accum >>= 8;
909 }
910 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* Store the straggler (if any). */
913 assert(accumbits < 8);
914 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
915 if (accumbits > 0) {
916 if (j >= n)
917 goto Overflow;
918 ++j;
919 if (do_twos_comp) {
920 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300921 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 infinite supply of sign bits). */
923 accum |= (~(twodigits)0) << accumbits;
924 }
925 *p = (unsigned char)(accum & 0xff);
926 p += pincr;
927 }
928 else if (j == n && n > 0 && is_signed) {
929 /* The main loop filled the byte array exactly, so the code
930 just above didn't get to ensure there's a sign bit, and the
931 loop below wouldn't add one either. Make sure a sign bit
932 exists. */
933 unsigned char msb = *(p - pincr);
934 int sign_bit_set = msb >= 0x80;
935 assert(accumbits == 0);
936 if (sign_bit_set == do_twos_comp)
937 return 0;
938 else
939 goto Overflow;
940 }
Tim Peters05607ad2001-06-13 21:01:27 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Fill remaining bytes with copies of the sign bit. */
943 {
944 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
945 for ( ; j < n; ++j, p += pincr)
946 *p = signbyte;
947 }
Tim Peters05607ad2001-06-13 21:01:27 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000950
Mark Dickinson22b20182010-05-10 21:27:53 +0000951 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
953 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000954
Tim Peters2a9b3672001-06-11 21:23:58 +0000955}
956
Serhiy Storchaka95949422013-08-27 19:40:23 +0300957/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000958
959PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000960PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000961{
Mark Dickinson91044792012-10-18 19:21:43 +0100962#if SIZEOF_VOID_P <= SIZEOF_LONG
Mark Dickinson91044792012-10-18 19:21:43 +0100963 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
964#else
965
Tim Peters70128a12001-06-16 08:48:40 +0000966#ifndef HAVE_LONG_LONG
967# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
968#endif
969#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000970# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000971#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100973#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000974
Guido van Rossum78694d91998-09-18 14:14:13 +0000975}
976
Serhiy Storchaka95949422013-08-27 19:40:23 +0300977/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000978
979void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000980PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000981{
Tim Peters70128a12001-06-16 08:48:40 +0000982#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
986 x = PyLong_AsLong(vv);
987 else
988 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000989#else
Tim Peters70128a12001-06-16 08:48:40 +0000990
991#ifndef HAVE_LONG_LONG
992# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
993#endif
994#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000996#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1000 x = PyLong_AsLongLong(vv);
1001 else
1002 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001003
1004#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (x == -1 && PyErr_Occurred())
1007 return NULL;
1008 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001009}
1010
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001011#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001012
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001013/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001014 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001015 */
1016
Mark Dickinson22b20182010-05-10 21:27:53 +00001017#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001018
Serhiy Storchaka95949422013-08-27 19:40:23 +03001019/* Create a new int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001020
1021PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001022PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 PyLongObject *v;
1025 unsigned PY_LONG_LONG abs_ival;
1026 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1027 int ndigits = 0;
1028 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 CHECK_SMALL_INT(ival);
1031 if (ival < 0) {
1032 /* avoid signed overflow on negation; see comments
1033 in PyLong_FromLong above. */
1034 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1035 negative = 1;
1036 }
1037 else {
1038 abs_ival = (unsigned PY_LONG_LONG)ival;
1039 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 /* Count the number of Python digits.
1042 We used to pick 5 ("big enough for anything"), but that's a
1043 waste of time and space given that 5*15 = 75 bits are rarely
1044 needed. */
1045 t = abs_ival;
1046 while (t) {
1047 ++ndigits;
1048 t >>= PyLong_SHIFT;
1049 }
1050 v = _PyLong_New(ndigits);
1051 if (v != NULL) {
1052 digit *p = v->ob_digit;
1053 Py_SIZE(v) = negative ? -ndigits : ndigits;
1054 t = abs_ival;
1055 while (t) {
1056 *p++ = (digit)(t & PyLong_MASK);
1057 t >>= PyLong_SHIFT;
1058 }
1059 }
1060 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001061}
1062
Serhiy Storchaka95949422013-08-27 19:40:23 +03001063/* Create a new int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001064
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001065PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001066PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 PyLongObject *v;
1069 unsigned PY_LONG_LONG t;
1070 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (ival < PyLong_BASE)
1073 return PyLong_FromLong((long)ival);
1074 /* Count the number of Python digits. */
1075 t = (unsigned PY_LONG_LONG)ival;
1076 while (t) {
1077 ++ndigits;
1078 t >>= PyLong_SHIFT;
1079 }
1080 v = _PyLong_New(ndigits);
1081 if (v != NULL) {
1082 digit *p = v->ob_digit;
1083 Py_SIZE(v) = ndigits;
1084 while (ival) {
1085 *p++ = (digit)(ival & PyLong_MASK);
1086 ival >>= PyLong_SHIFT;
1087 }
1088 }
1089 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001090}
1091
Serhiy Storchaka95949422013-08-27 19:40:23 +03001092/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001093
1094PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001095PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyLongObject *v;
1098 size_t abs_ival;
1099 size_t t; /* unsigned so >> doesn't propagate sign bit */
1100 int ndigits = 0;
1101 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 CHECK_SMALL_INT(ival);
1104 if (ival < 0) {
1105 /* avoid signed overflow when ival = SIZE_T_MIN */
1106 abs_ival = (size_t)(-1-ival)+1;
1107 negative = 1;
1108 }
1109 else {
1110 abs_ival = (size_t)ival;
1111 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 /* Count the number of Python digits. */
1114 t = abs_ival;
1115 while (t) {
1116 ++ndigits;
1117 t >>= PyLong_SHIFT;
1118 }
1119 v = _PyLong_New(ndigits);
1120 if (v != NULL) {
1121 digit *p = v->ob_digit;
1122 Py_SIZE(v) = negative ? -ndigits : ndigits;
1123 t = abs_ival;
1124 while (t) {
1125 *p++ = (digit)(t & PyLong_MASK);
1126 t >>= PyLong_SHIFT;
1127 }
1128 }
1129 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001130}
1131
Serhiy Storchaka95949422013-08-27 19:40:23 +03001132/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001133
1134PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001135PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 PyLongObject *v;
1138 size_t t;
1139 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 if (ival < PyLong_BASE)
1142 return PyLong_FromLong((long)ival);
1143 /* Count the number of Python digits. */
1144 t = ival;
1145 while (t) {
1146 ++ndigits;
1147 t >>= PyLong_SHIFT;
1148 }
1149 v = _PyLong_New(ndigits);
1150 if (v != NULL) {
1151 digit *p = v->ob_digit;
1152 Py_SIZE(v) = ndigits;
1153 while (ival) {
1154 *p++ = (digit)(ival & PyLong_MASK);
1155 ival >>= PyLong_SHIFT;
1156 }
1157 }
1158 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001159}
1160
Serhiy Storchaka95949422013-08-27 19:40:23 +03001161/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001162 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001163
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001164PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001165PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 PyLongObject *v;
1168 PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (vv == NULL) {
1172 PyErr_BadInternalCall();
1173 return -1;
1174 }
1175 if (!PyLong_Check(vv)) {
1176 PyNumberMethods *nb;
1177 PyObject *io;
1178 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1179 nb->nb_int == NULL) {
1180 PyErr_SetString(PyExc_TypeError, "an integer is required");
1181 return -1;
1182 }
1183 io = (*nb->nb_int) (vv);
1184 if (io == NULL)
1185 return -1;
1186 if (PyLong_Check(io)) {
1187 bytes = PyLong_AsLongLong(io);
1188 Py_DECREF(io);
1189 return bytes;
1190 }
1191 Py_DECREF(io);
1192 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1193 return -1;
1194 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 v = (PyLongObject*)vv;
1197 switch(Py_SIZE(v)) {
1198 case -1: return -(sdigit)v->ob_digit[0];
1199 case 0: return 0;
1200 case 1: return v->ob_digit[0];
1201 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001202 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001203 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1206 if (res < 0)
1207 return (PY_LONG_LONG)-1;
1208 else
1209 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001210}
1211
Serhiy Storchaka95949422013-08-27 19:40:23 +03001212/* Get a C unsigned PY_LONG_LONG int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001213 Return -1 and set an error if overflow occurs. */
1214
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001215unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001216PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 PyLongObject *v;
1219 unsigned PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001221
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001222 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyErr_BadInternalCall();
1224 return (unsigned PY_LONG_LONG)-1;
1225 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001226 if (!PyLong_Check(vv)) {
1227 PyErr_SetString(PyExc_TypeError, "an integer is required");
1228 return (unsigned PY_LONG_LONG)-1;
1229 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 v = (PyLongObject*)vv;
1232 switch(Py_SIZE(v)) {
1233 case 0: return 0;
1234 case 1: return v->ob_digit[0];
1235 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001236
Mark Dickinson22b20182010-05-10 21:27:53 +00001237 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001238 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1241 if (res < 0)
1242 return (unsigned PY_LONG_LONG)res;
1243 else
1244 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001245}
Tim Petersd1a7da62001-06-13 00:35:57 +00001246
Serhiy Storchaka95949422013-08-27 19:40:23 +03001247/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001248 Returns -1 and sets an error condition if an error occurs. */
1249
Guido van Rossumddefaf32007-01-14 03:31:43 +00001250static unsigned PY_LONG_LONG
1251_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001252{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001253 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 unsigned PY_LONG_LONG x;
1255 Py_ssize_t i;
1256 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (vv == NULL || !PyLong_Check(vv)) {
1259 PyErr_BadInternalCall();
1260 return (unsigned long) -1;
1261 }
1262 v = (PyLongObject *)vv;
1263 switch(Py_SIZE(v)) {
1264 case 0: return 0;
1265 case 1: return v->ob_digit[0];
1266 }
1267 i = Py_SIZE(v);
1268 sign = 1;
1269 x = 0;
1270 if (i < 0) {
1271 sign = -1;
1272 i = -i;
1273 }
1274 while (--i >= 0) {
1275 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1276 }
1277 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001278}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001279
1280unsigned PY_LONG_LONG
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001281PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 PyNumberMethods *nb;
1284 PyLongObject *lo;
1285 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (op && PyLong_Check(op))
1288 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1291 nb->nb_int == NULL) {
1292 PyErr_SetString(PyExc_TypeError, "an integer is required");
1293 return (unsigned PY_LONG_LONG)-1;
1294 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 lo = (PyLongObject*) (*nb->nb_int) (op);
1297 if (lo == NULL)
1298 return (unsigned PY_LONG_LONG)-1;
1299 if (PyLong_Check(lo)) {
1300 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1301 Py_DECREF(lo);
1302 if (PyErr_Occurred())
1303 return (unsigned PY_LONG_LONG)-1;
1304 return val;
1305 }
1306 else
1307 {
1308 Py_DECREF(lo);
1309 PyErr_SetString(PyExc_TypeError,
1310 "nb_int should return int object");
1311 return (unsigned PY_LONG_LONG)-1;
1312 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001313}
Tim Petersd1a7da62001-06-13 00:35:57 +00001314
Serhiy Storchaka95949422013-08-27 19:40:23 +03001315/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001316 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001317
Mark Dickinson8d48b432011-10-23 20:47:14 +01001318 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1319 the result. Otherwise *overflow is 0.
1320
1321 For other errors (e.g., TypeError), return -1 and set an error condition.
1322 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001323*/
1324
1325PY_LONG_LONG
1326PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001329 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 unsigned PY_LONG_LONG x, prev;
1331 PY_LONG_LONG res;
1332 Py_ssize_t i;
1333 int sign;
1334 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 *overflow = 0;
1337 if (vv == NULL) {
1338 PyErr_BadInternalCall();
1339 return -1;
1340 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (!PyLong_Check(vv)) {
1343 PyNumberMethods *nb;
1344 nb = vv->ob_type->tp_as_number;
1345 if (nb == NULL || nb->nb_int == NULL) {
1346 PyErr_SetString(PyExc_TypeError,
1347 "an integer is required");
1348 return -1;
1349 }
1350 vv = (*nb->nb_int) (vv);
1351 if (vv == NULL)
1352 return -1;
1353 do_decref = 1;
1354 if (!PyLong_Check(vv)) {
1355 Py_DECREF(vv);
1356 PyErr_SetString(PyExc_TypeError,
1357 "nb_int should return int object");
1358 return -1;
1359 }
1360 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 res = -1;
1363 v = (PyLongObject *)vv;
1364 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 switch (i) {
1367 case -1:
1368 res = -(sdigit)v->ob_digit[0];
1369 break;
1370 case 0:
1371 res = 0;
1372 break;
1373 case 1:
1374 res = v->ob_digit[0];
1375 break;
1376 default:
1377 sign = 1;
1378 x = 0;
1379 if (i < 0) {
1380 sign = -1;
1381 i = -(i);
1382 }
1383 while (--i >= 0) {
1384 prev = x;
1385 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1386 if ((x >> PyLong_SHIFT) != prev) {
1387 *overflow = sign;
1388 goto exit;
1389 }
1390 }
1391 /* Haven't lost any bits, but casting to long requires extra
1392 * care (see comment above).
1393 */
1394 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1395 res = (PY_LONG_LONG)x * sign;
1396 }
1397 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1398 res = PY_LLONG_MIN;
1399 }
1400 else {
1401 *overflow = sign;
1402 /* res is already set to -1 */
1403 }
1404 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001405 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (do_decref) {
1407 Py_DECREF(vv);
1408 }
1409 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001410}
1411
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001412#endif /* HAVE_LONG_LONG */
1413
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001414#define CHECK_BINOP(v,w) \
1415 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001416 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1417 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001418 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001419
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001420/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1421 2**k if d is nonzero, else 0. */
1422
1423static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1425 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001426};
1427
1428static int
1429bits_in_digit(digit d)
1430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 int d_bits = 0;
1432 while (d >= 32) {
1433 d_bits += 6;
1434 d >>= 6;
1435 }
1436 d_bits += (int)BitLengthTable[d];
1437 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001438}
1439
Tim Peters877a2122002-08-12 05:09:36 +00001440/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1441 * is modified in place, by adding y to it. Carries are propagated as far as
1442 * x[m-1], and the remaining carry (0 or 1) is returned.
1443 */
1444static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001445v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 Py_ssize_t i;
1448 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 assert(m >= n);
1451 for (i = 0; i < n; ++i) {
1452 carry += x[i] + y[i];
1453 x[i] = carry & PyLong_MASK;
1454 carry >>= PyLong_SHIFT;
1455 assert((carry & 1) == carry);
1456 }
1457 for (; carry && i < m; ++i) {
1458 carry += x[i];
1459 x[i] = carry & PyLong_MASK;
1460 carry >>= PyLong_SHIFT;
1461 assert((carry & 1) == carry);
1462 }
1463 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001464}
1465
1466/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1467 * is modified in place, by subtracting y from it. Borrows are propagated as
1468 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1469 */
1470static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001471v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 Py_ssize_t i;
1474 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 assert(m >= n);
1477 for (i = 0; i < n; ++i) {
1478 borrow = x[i] - y[i] - borrow;
1479 x[i] = borrow & PyLong_MASK;
1480 borrow >>= PyLong_SHIFT;
1481 borrow &= 1; /* keep only 1 sign bit */
1482 }
1483 for (; borrow && i < m; ++i) {
1484 borrow = x[i] - borrow;
1485 x[i] = borrow & PyLong_MASK;
1486 borrow >>= PyLong_SHIFT;
1487 borrow &= 1;
1488 }
1489 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001490}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001491
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001492/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1493 * result in z[0:m], and return the d bits shifted out of the top.
1494 */
1495static digit
1496v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 Py_ssize_t i;
1499 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 assert(0 <= d && d < PyLong_SHIFT);
1502 for (i=0; i < m; i++) {
1503 twodigits acc = (twodigits)a[i] << d | carry;
1504 z[i] = (digit)acc & PyLong_MASK;
1505 carry = (digit)(acc >> PyLong_SHIFT);
1506 }
1507 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001508}
1509
1510/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1511 * result in z[0:m], and return the d bits shifted out of the bottom.
1512 */
1513static digit
1514v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 Py_ssize_t i;
1517 digit carry = 0;
1518 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 assert(0 <= d && d < PyLong_SHIFT);
1521 for (i=m; i-- > 0;) {
1522 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1523 carry = (digit)acc & mask;
1524 z[i] = (digit)(acc >> d);
1525 }
1526 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001527}
1528
Tim Peters212e6142001-07-14 12:23:19 +00001529/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1530 in pout, and returning the remainder. pin and pout point at the LSD.
1531 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001532 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001533 immutable. */
1534
1535static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001536inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 assert(n > 0 && n <= PyLong_MASK);
1541 pin += size;
1542 pout += size;
1543 while (--size >= 0) {
1544 digit hi;
1545 rem = (rem << PyLong_SHIFT) | *--pin;
1546 *--pout = hi = (digit)(rem / n);
1547 rem -= (twodigits)hi * n;
1548 }
1549 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001550}
1551
Serhiy Storchaka95949422013-08-27 19:40:23 +03001552/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001553 (as function result) and the remainder (through *prem).
1554 The sign of a is ignored; n should not be zero. */
1555
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001556static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001557divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 const Py_ssize_t size = ABS(Py_SIZE(a));
1560 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 assert(n > 0 && n <= PyLong_MASK);
1563 z = _PyLong_New(size);
1564 if (z == NULL)
1565 return NULL;
1566 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1567 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001568}
1569
Serhiy Storchaka95949422013-08-27 19:40:23 +03001570/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001571 string. (Return value is non-shared so that callers can modify the
1572 returned value if necessary.) */
1573
Victor Stinnerd3f08822012-05-29 12:57:52 +02001574static int
1575long_to_decimal_string_internal(PyObject *aa,
1576 PyObject **p_output,
1577 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 PyLongObject *scratch, *a;
1580 PyObject *str;
1581 Py_ssize_t size, strlen, size_a, i, j;
1582 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001584 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 a = (PyLongObject *)aa;
1587 if (a == NULL || !PyLong_Check(a)) {
1588 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001589 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 }
1591 size_a = ABS(Py_SIZE(a));
1592 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 /* quick and dirty upper bound for the number of digits
1595 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 But log2(a) < size_a * PyLong_SHIFT, and
1600 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1601 > 3 * _PyLong_DECIMAL_SHIFT
1602 */
1603 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1604 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001605 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001606 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 }
1608 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1609 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1610 scratch = _PyLong_New(size);
1611 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001612 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 /* convert array of base _PyLong_BASE digits in pin to an array of
1615 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1616 Volume 2 (3rd edn), section 4.4, Method 1b). */
1617 pin = a->ob_digit;
1618 pout = scratch->ob_digit;
1619 size = 0;
1620 for (i = size_a; --i >= 0; ) {
1621 digit hi = pin[i];
1622 for (j = 0; j < size; j++) {
1623 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1624 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1625 pout[j] = (digit)(z - (twodigits)hi *
1626 _PyLong_DECIMAL_BASE);
1627 }
1628 while (hi) {
1629 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1630 hi /= _PyLong_DECIMAL_BASE;
1631 }
1632 /* check for keyboard interrupt */
1633 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001634 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001635 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001636 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 }
1638 /* pout should have at least one digit, so that the case when a = 0
1639 works correctly */
1640 if (size == 0)
1641 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 /* calculate exact length of output string, and allocate */
1644 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1645 tenpow = 10;
1646 rem = pout[size-1];
1647 while (rem >= tenpow) {
1648 tenpow *= 10;
1649 strlen++;
1650 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001651 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001652 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1653 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001654 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001655 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001656 kind = writer->kind;
1657 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001659 else {
1660 str = PyUnicode_New(strlen, '9');
1661 if (str == NULL) {
1662 Py_DECREF(scratch);
1663 return -1;
1664 }
1665 kind = PyUnicode_KIND(str);
1666 }
1667
1668#define WRITE_DIGITS(TYPE) \
1669 do { \
1670 if (writer) \
1671 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1672 else \
1673 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1674 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001675 /* pout[0] through pout[size-2] contribute exactly \
1676 _PyLong_DECIMAL_SHIFT digits each */ \
1677 for (i=0; i < size - 1; i++) { \
1678 rem = pout[i]; \
1679 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1680 *--p = '0' + rem % 10; \
1681 rem /= 10; \
1682 } \
1683 } \
1684 /* pout[size-1]: always produce at least one decimal digit */ \
1685 rem = pout[i]; \
1686 do { \
1687 *--p = '0' + rem % 10; \
1688 rem /= 10; \
1689 } while (rem != 0); \
1690 \
1691 /* and sign */ \
1692 if (negative) \
1693 *--p = '-'; \
1694 \
1695 /* check we've counted correctly */ \
1696 if (writer) \
1697 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1698 else \
1699 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1700 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001703 if (kind == PyUnicode_1BYTE_KIND) {
1704 Py_UCS1 *p;
1705 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001707 else if (kind == PyUnicode_2BYTE_KIND) {
1708 Py_UCS2 *p;
1709 WRITE_DIGITS(Py_UCS2);
1710 }
1711 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001712 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001713 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001714 WRITE_DIGITS(Py_UCS4);
1715 }
1716#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001719 if (writer) {
1720 writer->pos += strlen;
1721 }
1722 else {
1723 assert(_PyUnicode_CheckConsistency(str, 1));
1724 *p_output = (PyObject *)str;
1725 }
1726 return 0;
1727}
1728
1729static PyObject *
1730long_to_decimal_string(PyObject *aa)
1731{
1732 PyObject *v;
1733 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1734 return NULL;
1735 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001736}
1737
Serhiy Storchaka95949422013-08-27 19:40:23 +03001738/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001739 which should be one of 2, 8 or 16. Return a string object.
1740 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1741 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001742
Victor Stinnerd3f08822012-05-29 12:57:52 +02001743static int
1744long_format_binary(PyObject *aa, int base, int alternate,
1745 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001746{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001747 PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001749 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001751 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001752 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001754
Victor Stinnerd3f08822012-05-29 12:57:52 +02001755 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (a == NULL || !PyLong_Check(a)) {
1757 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001758 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 }
1760 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001761 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 /* Compute a rough upper bound for the length of the string */
1764 switch (base) {
1765 case 16:
1766 bits = 4;
1767 break;
1768 case 8:
1769 bits = 3;
1770 break;
1771 case 2:
1772 bits = 1;
1773 break;
1774 default:
1775 assert(0); /* shouldn't ever get here */
1776 bits = 0; /* to silence gcc warning */
1777 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001778
Mark Dickinsone2846542012-04-20 21:21:24 +01001779 /* Compute exact length 'sz' of output string. */
1780 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001781 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001782 }
1783 else {
1784 Py_ssize_t size_a_in_bits;
1785 /* Ensure overflow doesn't occur during computation of sz. */
1786 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1787 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001788 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001789 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001790 }
1791 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1792 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001793 /* Allow 1 character for a '-' sign. */
1794 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1795 }
1796 if (alternate) {
1797 /* 2 characters for prefix */
1798 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001799 }
1800
Victor Stinnerd3f08822012-05-29 12:57:52 +02001801 if (writer) {
1802 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1803 return -1;
1804 kind = writer->kind;
1805 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 }
1807 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001808 v = PyUnicode_New(sz, 'x');
1809 if (v == NULL)
1810 return -1;
1811 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001813
Victor Stinnerd3f08822012-05-29 12:57:52 +02001814#define WRITE_DIGITS(TYPE) \
1815 do { \
1816 if (writer) \
1817 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1818 else \
1819 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1820 \
1821 if (size_a == 0) { \
1822 *--p = '0'; \
1823 } \
1824 else { \
1825 /* JRH: special case for power-of-2 bases */ \
1826 twodigits accum = 0; \
1827 int accumbits = 0; /* # of bits in accum */ \
1828 Py_ssize_t i; \
1829 for (i = 0; i < size_a; ++i) { \
1830 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1831 accumbits += PyLong_SHIFT; \
1832 assert(accumbits >= bits); \
1833 do { \
1834 char cdigit; \
1835 cdigit = (char)(accum & (base - 1)); \
1836 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1837 *--p = cdigit; \
1838 accumbits -= bits; \
1839 accum >>= bits; \
1840 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1841 } \
1842 } \
1843 \
1844 if (alternate) { \
1845 if (base == 16) \
1846 *--p = 'x'; \
1847 else if (base == 8) \
1848 *--p = 'o'; \
1849 else /* (base == 2) */ \
1850 *--p = 'b'; \
1851 *--p = '0'; \
1852 } \
1853 if (negative) \
1854 *--p = '-'; \
1855 if (writer) \
1856 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1857 else \
1858 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1859 } while (0)
1860
1861 if (kind == PyUnicode_1BYTE_KIND) {
1862 Py_UCS1 *p;
1863 WRITE_DIGITS(Py_UCS1);
1864 }
1865 else if (kind == PyUnicode_2BYTE_KIND) {
1866 Py_UCS2 *p;
1867 WRITE_DIGITS(Py_UCS2);
1868 }
1869 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001870 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001871 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001872 WRITE_DIGITS(Py_UCS4);
1873 }
1874#undef WRITE_DIGITS
1875
1876 if (writer) {
1877 writer->pos += sz;
1878 }
1879 else {
1880 assert(_PyUnicode_CheckConsistency(v, 1));
1881 *p_output = v;
1882 }
1883 return 0;
1884}
1885
1886PyObject *
1887_PyLong_Format(PyObject *obj, int base)
1888{
1889 PyObject *str;
1890 int err;
1891 if (base == 10)
1892 err = long_to_decimal_string_internal(obj, &str, NULL);
1893 else
1894 err = long_format_binary(obj, base, 1, &str, NULL);
1895 if (err == -1)
1896 return NULL;
1897 return str;
1898}
1899
1900int
1901_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1902 PyObject *obj,
1903 int base, int alternate)
1904{
1905 if (base == 10)
1906 return long_to_decimal_string_internal(obj, NULL, writer);
1907 else
1908 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001909}
1910
Thomas Wouters477c8d52006-05-27 19:21:47 +00001911/* Table of digit values for 8-bit string -> integer conversion.
1912 * '0' maps to 0, ..., '9' maps to 9.
1913 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1914 * All other indices map to 37.
1915 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001916 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001917 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001918unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1920 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1921 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1922 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1923 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1924 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1925 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1926 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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,
1934 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001935};
1936
1937/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001938 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
Serhiy Storchaka95949422013-08-27 19:40:23 +03001939 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00001940 * The point to this routine is that it takes time linear in the number of
1941 * string characters.
1942 */
1943static PyLongObject *
1944long_from_binary_base(char **str, int base)
1945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 char *p = *str;
1947 char *start = p;
1948 int bits_per_char;
1949 Py_ssize_t n;
1950 PyLongObject *z;
1951 twodigits accum;
1952 int bits_in_accum;
1953 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1956 n = base;
1957 for (bits_per_char = -1; n; ++bits_per_char)
1958 n >>= 1;
1959 /* n <- total # of bits needed, while setting p to end-of-string */
1960 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1961 ++p;
1962 *str = p;
1963 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1964 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1965 if (n / bits_per_char < p - start) {
1966 PyErr_SetString(PyExc_ValueError,
1967 "int string too large to convert");
1968 return NULL;
1969 }
1970 n = n / PyLong_SHIFT;
1971 z = _PyLong_New(n);
1972 if (z == NULL)
1973 return NULL;
Serhiy Storchaka95949422013-08-27 19:40:23 +03001974 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 * from least to most significant in both.
1976 */
1977 accum = 0;
1978 bits_in_accum = 0;
1979 pdigit = z->ob_digit;
1980 while (--p >= start) {
1981 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1982 assert(k >= 0 && k < base);
1983 accum |= (twodigits)k << bits_in_accum;
1984 bits_in_accum += bits_per_char;
1985 if (bits_in_accum >= PyLong_SHIFT) {
1986 *pdigit++ = (digit)(accum & PyLong_MASK);
1987 assert(pdigit - z->ob_digit <= n);
1988 accum >>= PyLong_SHIFT;
1989 bits_in_accum -= PyLong_SHIFT;
1990 assert(bits_in_accum < PyLong_SHIFT);
1991 }
1992 }
1993 if (bits_in_accum) {
1994 assert(bits_in_accum <= PyLong_SHIFT);
1995 *pdigit++ = (digit)accum;
1996 assert(pdigit - z->ob_digit <= n);
1997 }
1998 while (pdigit - z->ob_digit < n)
1999 *pdigit++ = 0;
2000 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002001}
2002
Serhiy Storchaka95949422013-08-27 19:40:23 +03002003/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002004 * ignored.
2005 *
2006 * If successful, a PyLong object will be returned and 'pend' will be pointing
2007 * to the first unused byte unless it's NULL.
2008 *
2009 * If unsuccessful, NULL will be returned.
2010 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002011PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002012PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 int sign = 1, error_if_nonzero = 0;
2015 char *start, *orig_str = str;
2016 PyLongObject *z = NULL;
2017 PyObject *strobj;
2018 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if ((base != 0 && base < 2) || base > 36) {
2021 PyErr_SetString(PyExc_ValueError,
2022 "int() arg 2 must be >= 2 and <= 36");
2023 return NULL;
2024 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002025 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 str++;
2027 if (*str == '+')
2028 ++str;
2029 else if (*str == '-') {
2030 ++str;
2031 sign = -1;
2032 }
2033 if (base == 0) {
2034 if (str[0] != '0')
2035 base = 10;
2036 else if (str[1] == 'x' || str[1] == 'X')
2037 base = 16;
2038 else if (str[1] == 'o' || str[1] == 'O')
2039 base = 8;
2040 else if (str[1] == 'b' || str[1] == 'B')
2041 base = 2;
2042 else {
2043 /* "old" (C-style) octal literal, now invalid.
2044 it might still be zero though */
2045 error_if_nonzero = 1;
2046 base = 10;
2047 }
2048 }
2049 if (str[0] == '0' &&
2050 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2051 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2052 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2053 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 start = str;
2056 if ((base & (base - 1)) == 0)
2057 z = long_from_binary_base(&str, base);
2058 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002059/***
2060Binary bases can be converted in time linear in the number of digits, because
2061Python's representation base is binary. Other bases (including decimal!) use
2062the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002063
Thomas Wouters477c8d52006-05-27 19:21:47 +00002064First some math: the largest integer that can be expressed in N base-B digits
2065is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2066case number of Python digits needed to hold it is the smallest integer n s.t.
2067
2068 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2069 BASE**n >= B**N [taking logs to base BASE]
2070 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2071
2072The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002073this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002074and the result is computed into it.
2075
2076The input string is actually treated as being in base base**i (i.e., i digits
2077are processed at a time), where two more static arrays hold:
2078
2079 convwidth_base[base] = the largest integer i such that base**i <= BASE
2080 convmultmax_base[base] = base ** convwidth_base[base]
2081
2082The first of these is the largest i such that i consecutive input digits
2083must fit in a single Python digit. The second is effectively the input
2084base we're really using.
2085
2086Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2087convmultmax_base[base], the result is "simply"
2088
2089 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2090
2091where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002092
2093Error analysis: as above, the number of Python digits `n` needed is worst-
2094case
2095
2096 n >= N * log(B)/log(BASE)
2097
2098where `N` is the number of input digits in base `B`. This is computed via
2099
2100 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2101
2102below. Two numeric concerns are how much space this can waste, and whether
2103the computed result can be too small. To be concrete, assume BASE = 2**15,
2104which is the default (and it's unlikely anyone changes that).
2105
2106Waste isn't a problem: provided the first input digit isn't 0, the difference
2107between the worst-case input with N digits and the smallest input with N
2108digits is about a factor of B, but B is small compared to BASE so at most
2109one allocated Python digit can remain unused on that count. If
2110N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2111and adding 1 returns a result 1 larger than necessary. However, that can't
2112happen: whenever B is a power of 2, long_from_binary_base() is called
2113instead, and it's impossible for B**i to be an integer power of 2**15 when
2114B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2115an exact integer when B is not a power of 2, since B**i has a prime factor
2116other than 2 in that case, but (2**15)**j's only prime factor is 2).
2117
2118The computed result can be too small if the true value of N*log(B)/log(BASE)
2119is a little bit larger than an exact integer, but due to roundoff errors (in
2120computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2121yields a numeric result a little less than that integer. Unfortunately, "how
2122close can a transcendental function get to an integer over some range?"
2123questions are generally theoretically intractable. Computer analysis via
2124continued fractions is practical: expand log(B)/log(BASE) via continued
2125fractions, giving a sequence i/j of "the best" rational approximations. Then
2126j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2127we can get very close to being in trouble, but very rarely. For example,
212876573 is a denominator in one of the continued-fraction approximations to
2129log(10)/log(2**15), and indeed:
2130
2131 >>> log(10)/log(2**15)*76573
2132 16958.000000654003
2133
2134is very close to an integer. If we were working with IEEE single-precision,
2135rounding errors could kill us. Finding worst cases in IEEE double-precision
2136requires better-than-double-precision log() functions, and Tim didn't bother.
2137Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002138new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002139This should happen extremely rarely, and in fact I don't have a test case
2140that triggers it(!). Instead the code was tested by artificially allocating
2141just 1 digit at the start, so that the copying code was exercised for every
2142digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002143***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002144 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 Py_ssize_t size_z;
2146 int i;
2147 int convwidth;
2148 twodigits convmultmax, convmult;
2149 digit *pz, *pzstop;
2150 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 static double log_base_BASE[37] = {0.0e0,};
2153 static int convwidth_base[37] = {0,};
2154 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 if (log_base_BASE[base] == 0.0) {
2157 twodigits convmax = base;
2158 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002159
Mark Dickinson22b20182010-05-10 21:27:53 +00002160 log_base_BASE[base] = (log((double)base) /
2161 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 for (;;) {
2163 twodigits next = convmax * base;
2164 if (next > PyLong_BASE)
2165 break;
2166 convmax = next;
2167 ++i;
2168 }
2169 convmultmax_base[base] = convmax;
2170 assert(i > 0);
2171 convwidth_base[base] = i;
2172 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 /* Find length of the string of numeric characters. */
2175 scan = str;
2176 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2177 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002178
Serhiy Storchaka95949422013-08-27 19:40:23 +03002179 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 * integer with this base and length. Note that there's no
2181 * need to initialize z->ob_digit -- no slot is read up before
2182 * being stored into.
2183 */
2184 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2185 /* Uncomment next line to test exceedingly rare copy code */
2186 /* size_z = 1; */
2187 assert(size_z > 0);
2188 z = _PyLong_New(size_z);
2189 if (z == NULL)
2190 return NULL;
2191 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 /* `convwidth` consecutive input digits are treated as a single
2194 * digit in base `convmultmax`.
2195 */
2196 convwidth = convwidth_base[base];
2197 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 /* Work ;-) */
2200 while (str < scan) {
2201 /* grab up to convwidth digits from the input string */
2202 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2203 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2204 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002205 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 assert(c < PyLong_BASE);
2207 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 convmult = convmultmax;
2210 /* Calculate the shift only if we couldn't get
2211 * convwidth digits.
2212 */
2213 if (i != convwidth) {
2214 convmult = base;
2215 for ( ; i > 1; --i)
2216 convmult *= base;
2217 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* Multiply z by convmult, and add c. */
2220 pz = z->ob_digit;
2221 pzstop = pz + Py_SIZE(z);
2222 for (; pz < pzstop; ++pz) {
2223 c += (twodigits)*pz * convmult;
2224 *pz = (digit)(c & PyLong_MASK);
2225 c >>= PyLong_SHIFT;
2226 }
2227 /* carry off the current end? */
2228 if (c) {
2229 assert(c < PyLong_BASE);
2230 if (Py_SIZE(z) < size_z) {
2231 *pz = (digit)c;
2232 ++Py_SIZE(z);
2233 }
2234 else {
2235 PyLongObject *tmp;
2236 /* Extremely rare. Get more space. */
2237 assert(Py_SIZE(z) == size_z);
2238 tmp = _PyLong_New(size_z + 1);
2239 if (tmp == NULL) {
2240 Py_DECREF(z);
2241 return NULL;
2242 }
2243 memcpy(tmp->ob_digit,
2244 z->ob_digit,
2245 sizeof(digit) * size_z);
2246 Py_DECREF(z);
2247 z = tmp;
2248 z->ob_digit[size_z] = (digit)c;
2249 ++size_z;
2250 }
2251 }
2252 }
2253 }
2254 if (z == NULL)
2255 return NULL;
2256 if (error_if_nonzero) {
2257 /* reset the base to 0, else the exception message
2258 doesn't make too much sense */
2259 base = 0;
2260 if (Py_SIZE(z) != 0)
2261 goto onError;
2262 /* there might still be other problems, therefore base
2263 remains zero here for the same reason */
2264 }
2265 if (str == start)
2266 goto onError;
2267 if (sign < 0)
2268 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002269 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 str++;
2271 if (*str != '\0')
2272 goto onError;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002274 z = maybe_small_long(z);
2275 if (z == NULL)
2276 return NULL;
2277 if (pend != NULL)
2278 *pend = str;
2279 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002280
Mark Dickinson22b20182010-05-10 21:27:53 +00002281 onError:
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002282 if (pend != NULL)
2283 *pend = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 Py_XDECREF(z);
2285 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2286 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2287 if (strobj == NULL)
2288 return NULL;
2289 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002290 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 base, strobj);
2292 Py_DECREF(strobj);
2293 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002294}
2295
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002296/* Since PyLong_FromString doesn't have a length parameter,
2297 * check here for possible NULs in the string.
2298 *
2299 * Reports an invalid literal as a bytes object.
2300 */
2301PyObject *
2302_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2303{
2304 PyObject *result, *strobj;
2305 char *end = NULL;
2306
2307 result = PyLong_FromString((char*)s, &end, base);
2308 if (end == NULL || (result != NULL && end == s + len))
2309 return result;
2310 Py_XDECREF(result);
2311 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2312 if (strobj != NULL) {
2313 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002314 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002315 base, strobj);
2316 Py_DECREF(strobj);
2317 }
2318 return NULL;
2319}
2320
Guido van Rossum9e896b32000-04-05 20:11:21 +00002321PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002322PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002323{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002324 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2325 if (unicode == NULL)
2326 return NULL;
2327 v = PyLong_FromUnicodeObject(unicode, base);
2328 Py_DECREF(unicode);
2329 return v;
2330}
2331
2332PyObject *
2333PyLong_FromUnicodeObject(PyObject *u, int base)
2334{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002335 PyObject *result, *asciidig;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002336 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002337 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002339 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002340 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002342 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002343 if (buffer == NULL) {
2344 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002345 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2346 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002348 else {
2349 result = PyLong_FromString(buffer, &end, base);
2350 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2351 Py_DECREF(asciidig);
2352 return result;
2353 }
2354 Py_DECREF(asciidig);
2355 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002356 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002357 PyErr_Format(PyExc_ValueError,
2358 "invalid literal for int() with base %d: %.200R",
2359 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002360 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002361}
2362
Tim Peters9f688bf2000-07-07 15:53:28 +00002363/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002364static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002366static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002367
Serhiy Storchaka95949422013-08-27 19:40:23 +03002368/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002369
Guido van Rossume32e0141992-01-19 16:31:05 +00002370static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002371long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2375 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if (size_b == 0) {
2378 PyErr_SetString(PyExc_ZeroDivisionError,
2379 "integer division or modulo by zero");
2380 return -1;
2381 }
2382 if (size_a < size_b ||
2383 (size_a == size_b &&
2384 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2385 /* |a| < |b|. */
2386 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2387 if (*pdiv == NULL)
2388 return -1;
2389 Py_INCREF(a);
2390 *prem = (PyLongObject *) a;
2391 return 0;
2392 }
2393 if (size_b == 1) {
2394 digit rem = 0;
2395 z = divrem1(a, b->ob_digit[0], &rem);
2396 if (z == NULL)
2397 return -1;
2398 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2399 if (*prem == NULL) {
2400 Py_DECREF(z);
2401 return -1;
2402 }
2403 }
2404 else {
2405 z = x_divrem(a, b, prem);
2406 if (z == NULL)
2407 return -1;
2408 }
2409 /* Set the signs.
2410 The quotient z has the sign of a*b;
2411 the remainder r has the sign of a,
2412 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002413 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2414 _PyLong_Negate(&z);
2415 if (z == NULL) {
2416 Py_CLEAR(*prem);
2417 return -1;
2418 }
2419 }
2420 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2421 _PyLong_Negate(prem);
2422 if (*prem == NULL) {
2423 Py_DECREF(z);
2424 Py_CLEAR(*prem);
2425 return -1;
2426 }
2427 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 *pdiv = maybe_small_long(z);
2429 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002430}
2431
Serhiy Storchaka95949422013-08-27 19:40:23 +03002432/* Unsigned int division with remainder -- the algorithm. The arguments v1
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002433 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002434
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002435static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002436x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 PyLongObject *v, *w, *a;
2439 Py_ssize_t i, k, size_v, size_w;
2440 int d;
2441 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2442 twodigits vv;
2443 sdigit zhi;
2444 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2447 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2448 handle the special case when the initial estimate q for a quotient
2449 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2450 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 /* allocate space; w will also be used to hold the final remainder */
2453 size_v = ABS(Py_SIZE(v1));
2454 size_w = ABS(Py_SIZE(w1));
2455 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2456 v = _PyLong_New(size_v+1);
2457 if (v == NULL) {
2458 *prem = NULL;
2459 return NULL;
2460 }
2461 w = _PyLong_New(size_w);
2462 if (w == NULL) {
2463 Py_DECREF(v);
2464 *prem = NULL;
2465 return NULL;
2466 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2469 shift v1 left by the same amount. Results go into w and v. */
2470 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2471 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2472 assert(carry == 0);
2473 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2474 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2475 v->ob_digit[size_v] = carry;
2476 size_v++;
2477 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2480 at most (and usually exactly) k = size_v - size_w digits. */
2481 k = size_v - size_w;
2482 assert(k >= 0);
2483 a = _PyLong_New(k);
2484 if (a == NULL) {
2485 Py_DECREF(w);
2486 Py_DECREF(v);
2487 *prem = NULL;
2488 return NULL;
2489 }
2490 v0 = v->ob_digit;
2491 w0 = w->ob_digit;
2492 wm1 = w0[size_w-1];
2493 wm2 = w0[size_w-2];
2494 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2495 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2496 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002499 Py_DECREF(a);
2500 Py_DECREF(w);
2501 Py_DECREF(v);
2502 *prem = NULL;
2503 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002504 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 /* estimate quotient digit q; may overestimate by 1 (rare) */
2507 vtop = vk[size_w];
2508 assert(vtop <= wm1);
2509 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2510 q = (digit)(vv / wm1);
2511 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2512 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2513 | vk[size_w-2])) {
2514 --q;
2515 r += wm1;
2516 if (r >= PyLong_BASE)
2517 break;
2518 }
2519 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2522 zhi = 0;
2523 for (i = 0; i < size_w; ++i) {
2524 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2525 -PyLong_BASE * q <= z < PyLong_BASE */
2526 z = (sdigit)vk[i] + zhi -
2527 (stwodigits)q * (stwodigits)w0[i];
2528 vk[i] = (digit)z & PyLong_MASK;
2529 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002530 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 /* add w back if q was too large (this branch taken rarely) */
2534 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2535 if ((sdigit)vtop + zhi < 0) {
2536 carry = 0;
2537 for (i = 0; i < size_w; ++i) {
2538 carry += vk[i] + w0[i];
2539 vk[i] = carry & PyLong_MASK;
2540 carry >>= PyLong_SHIFT;
2541 }
2542 --q;
2543 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 /* store quotient digit */
2546 assert(q < PyLong_BASE);
2547 *--ak = q;
2548 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 /* unshift remainder; we reuse w to store the result */
2551 carry = v_rshift(w0, v0, size_w, d);
2552 assert(carry==0);
2553 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 *prem = long_normalize(w);
2556 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002557}
2558
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002559/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2560 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2561 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2562 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2563 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2564 -1.0. */
2565
2566/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2567#if DBL_MANT_DIG == 53
2568#define EXP2_DBL_MANT_DIG 9007199254740992.0
2569#else
2570#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2571#endif
2572
2573double
2574_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2577 /* See below for why x_digits is always large enough. */
2578 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2579 double dx;
2580 /* Correction term for round-half-to-even rounding. For a digit x,
2581 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2582 multiple of 4, rounding ties to a multiple of 8. */
2583 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 a_size = ABS(Py_SIZE(a));
2586 if (a_size == 0) {
2587 /* Special case for 0: significand 0.0, exponent 0. */
2588 *e = 0;
2589 return 0.0;
2590 }
2591 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2592 /* The following is an overflow-free version of the check
2593 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2594 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2595 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2596 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002597 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2601 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 Number of digits needed for result: write // for floor division.
2604 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2613 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2616 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2617 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 in both cases.
2624 */
2625 if (a_bits <= DBL_MANT_DIG + 2) {
2626 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2627 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2628 x_size = 0;
2629 while (x_size < shift_digits)
2630 x_digits[x_size++] = 0;
2631 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2632 (int)shift_bits);
2633 x_size += a_size;
2634 x_digits[x_size++] = rem;
2635 }
2636 else {
2637 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2638 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2639 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2640 a_size - shift_digits, (int)shift_bits);
2641 x_size = a_size - shift_digits;
2642 /* For correct rounding below, we need the least significant
2643 bit of x to be 'sticky' for this shift: if any of the bits
2644 shifted out was nonzero, we set the least significant bit
2645 of x. */
2646 if (rem)
2647 x_digits[0] |= 1;
2648 else
2649 while (shift_digits > 0)
2650 if (a->ob_digit[--shift_digits]) {
2651 x_digits[0] |= 1;
2652 break;
2653 }
2654 }
Victor Stinner63941882011-09-29 00:42:28 +02002655 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 /* Round, and convert to double. */
2658 x_digits[0] += half_even_correction[x_digits[0] & 7];
2659 dx = x_digits[--x_size];
2660 while (x_size > 0)
2661 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 /* Rescale; make correction if result is 1.0. */
2664 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2665 if (dx == 1.0) {
2666 if (a_bits == PY_SSIZE_T_MAX)
2667 goto overflow;
2668 dx = 0.5;
2669 a_bits += 1;
2670 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 *e = a_bits;
2673 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002674
2675 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 /* exponent > PY_SSIZE_T_MAX */
2677 PyErr_SetString(PyExc_OverflowError,
2678 "huge integer: number of bits overflows a Py_ssize_t");
2679 *e = 0;
2680 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002681}
2682
Serhiy Storchaka95949422013-08-27 19:40:23 +03002683/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002684 using the round-half-to-even rule in the case of a tie. */
2685
2686double
2687PyLong_AsDouble(PyObject *v)
2688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 Py_ssize_t exponent;
2690 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002691
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002692 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 PyErr_BadInternalCall();
2694 return -1.0;
2695 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002696 if (!PyLong_Check(v)) {
2697 PyErr_SetString(PyExc_TypeError, "an integer is required");
2698 return -1.0;
2699 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2701 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2702 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002703 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 return -1.0;
2705 }
2706 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002707}
2708
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002709/* Methods */
2710
2711static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002712long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002715}
2716
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002717static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002718long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 if (Py_SIZE(a) != Py_SIZE(b)) {
2723 sign = Py_SIZE(a) - Py_SIZE(b);
2724 }
2725 else {
2726 Py_ssize_t i = ABS(Py_SIZE(a));
2727 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2728 ;
2729 if (i < 0)
2730 sign = 0;
2731 else {
2732 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2733 if (Py_SIZE(a) < 0)
2734 sign = -sign;
2735 }
2736 }
2737 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002738}
2739
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002740#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002742
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002743static PyObject *
2744long_richcompare(PyObject *self, PyObject *other, int op)
2745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 int result;
2747 PyObject *v;
2748 CHECK_BINOP(self, other);
2749 if (self == other)
2750 result = 0;
2751 else
2752 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2753 /* Convert the return value to a Boolean */
2754 switch (op) {
2755 case Py_EQ:
2756 v = TEST_COND(result == 0);
2757 break;
2758 case Py_NE:
2759 v = TEST_COND(result != 0);
2760 break;
2761 case Py_LE:
2762 v = TEST_COND(result <= 0);
2763 break;
2764 case Py_GE:
2765 v = TEST_COND(result >= 0);
2766 break;
2767 case Py_LT:
2768 v = TEST_COND(result == -1);
2769 break;
2770 case Py_GT:
2771 v = TEST_COND(result == 1);
2772 break;
2773 default:
2774 PyErr_BadArgument();
2775 return NULL;
2776 }
2777 Py_INCREF(v);
2778 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002779}
2780
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002781static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002782long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002783{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002784 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 Py_ssize_t i;
2786 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 i = Py_SIZE(v);
2789 switch(i) {
2790 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2791 case 0: return 0;
2792 case 1: return v->ob_digit[0];
2793 }
2794 sign = 1;
2795 x = 0;
2796 if (i < 0) {
2797 sign = -1;
2798 i = -(i);
2799 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002801 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2802 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2803 _PyHASH_MODULUS.
2804
2805 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2806 amounts to a rotation of the bits of x. To see this, write
2807
2808 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2809
2810 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2811 PyLong_SHIFT bits of x (those that are shifted out of the
2812 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2813 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2814 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2815 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2816 congruent to y modulo _PyHASH_MODULUS. So
2817
2818 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2819
2820 The right-hand side is just the result of rotating the
2821 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2822 not all _PyHASH_BITS bits of x are 1s, the same is true
2823 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2824 the reduction of x*2**PyLong_SHIFT modulo
2825 _PyHASH_MODULUS. */
2826 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2827 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002829 if (x >= _PyHASH_MODULUS)
2830 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 }
2832 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002833 if (x == (Py_uhash_t)-1)
2834 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002835 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002836}
2837
2838
Serhiy Storchaka95949422013-08-27 19:40:23 +03002839/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002840
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002841static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002842x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2845 PyLongObject *z;
2846 Py_ssize_t i;
2847 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 /* Ensure a is the larger of the two: */
2850 if (size_a < size_b) {
2851 { PyLongObject *temp = a; a = b; b = temp; }
2852 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002853 size_a = size_b;
2854 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 }
2856 z = _PyLong_New(size_a+1);
2857 if (z == NULL)
2858 return NULL;
2859 for (i = 0; i < size_b; ++i) {
2860 carry += a->ob_digit[i] + b->ob_digit[i];
2861 z->ob_digit[i] = carry & PyLong_MASK;
2862 carry >>= PyLong_SHIFT;
2863 }
2864 for (; i < size_a; ++i) {
2865 carry += a->ob_digit[i];
2866 z->ob_digit[i] = carry & PyLong_MASK;
2867 carry >>= PyLong_SHIFT;
2868 }
2869 z->ob_digit[i] = carry;
2870 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002871}
2872
2873/* Subtract the absolute values of two integers. */
2874
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002875static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002876x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2879 PyLongObject *z;
2880 Py_ssize_t i;
2881 int sign = 1;
2882 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 /* Ensure a is the larger of the two: */
2885 if (size_a < size_b) {
2886 sign = -1;
2887 { PyLongObject *temp = a; a = b; b = temp; }
2888 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002889 size_a = size_b;
2890 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 }
2892 else if (size_a == size_b) {
2893 /* Find highest digit where a and b differ: */
2894 i = size_a;
2895 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2896 ;
2897 if (i < 0)
2898 return (PyLongObject *)PyLong_FromLong(0);
2899 if (a->ob_digit[i] < b->ob_digit[i]) {
2900 sign = -1;
2901 { PyLongObject *temp = a; a = b; b = temp; }
2902 }
2903 size_a = size_b = i+1;
2904 }
2905 z = _PyLong_New(size_a);
2906 if (z == NULL)
2907 return NULL;
2908 for (i = 0; i < size_b; ++i) {
2909 /* The following assumes unsigned arithmetic
2910 works module 2**N for some N>PyLong_SHIFT. */
2911 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2912 z->ob_digit[i] = borrow & PyLong_MASK;
2913 borrow >>= PyLong_SHIFT;
2914 borrow &= 1; /* Keep only one sign bit */
2915 }
2916 for (; i < size_a; ++i) {
2917 borrow = a->ob_digit[i] - borrow;
2918 z->ob_digit[i] = borrow & PyLong_MASK;
2919 borrow >>= PyLong_SHIFT;
2920 borrow &= 1; /* Keep only one sign bit */
2921 }
2922 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02002923 if (sign < 0) {
2924 _PyLong_Negate(&z);
2925 if (z == NULL)
2926 return NULL;
2927 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002929}
2930
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002931static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002932long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2939 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2940 MEDIUM_VALUE(b));
2941 return result;
2942 }
2943 if (Py_SIZE(a) < 0) {
2944 if (Py_SIZE(b) < 0) {
2945 z = x_add(a, b);
2946 if (z != NULL && Py_SIZE(z) != 0)
2947 Py_SIZE(z) = -(Py_SIZE(z));
2948 }
2949 else
2950 z = x_sub(b, a);
2951 }
2952 else {
2953 if (Py_SIZE(b) < 0)
2954 z = x_sub(a, b);
2955 else
2956 z = x_add(a, b);
2957 }
2958 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002959}
2960
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002961static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002962long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2969 PyObject* r;
2970 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2971 return r;
2972 }
2973 if (Py_SIZE(a) < 0) {
2974 if (Py_SIZE(b) < 0)
2975 z = x_sub(a, b);
2976 else
2977 z = x_add(a, b);
2978 if (z != NULL && Py_SIZE(z) != 0)
2979 Py_SIZE(z) = -(Py_SIZE(z));
2980 }
2981 else {
2982 if (Py_SIZE(b) < 0)
2983 z = x_add(a, b);
2984 else
2985 z = x_sub(a, b);
2986 }
2987 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002988}
2989
Tim Peters5af4e6c2002-08-12 02:31:19 +00002990/* Grade school multiplication, ignoring the signs.
2991 * Returns the absolute value of the product, or NULL if error.
2992 */
2993static PyLongObject *
2994x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 PyLongObject *z;
2997 Py_ssize_t size_a = ABS(Py_SIZE(a));
2998 Py_ssize_t size_b = ABS(Py_SIZE(b));
2999 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 z = _PyLong_New(size_a + size_b);
3002 if (z == NULL)
3003 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3006 if (a == b) {
3007 /* Efficient squaring per HAC, Algorithm 14.16:
3008 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3009 * Gives slightly less than a 2x speedup when a == b,
3010 * via exploiting that each entry in the multiplication
3011 * pyramid appears twice (except for the size_a squares).
3012 */
3013 for (i = 0; i < size_a; ++i) {
3014 twodigits carry;
3015 twodigits f = a->ob_digit[i];
3016 digit *pz = z->ob_digit + (i << 1);
3017 digit *pa = a->ob_digit + i + 1;
3018 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003021 Py_DECREF(z);
3022 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003023 });
Tim Peters0973b992004-08-29 22:16:50 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 carry = *pz + f * f;
3026 *pz++ = (digit)(carry & PyLong_MASK);
3027 carry >>= PyLong_SHIFT;
3028 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 /* Now f is added in twice in each column of the
3031 * pyramid it appears. Same as adding f<<1 once.
3032 */
3033 f <<= 1;
3034 while (pa < paend) {
3035 carry += *pz + *pa++ * f;
3036 *pz++ = (digit)(carry & PyLong_MASK);
3037 carry >>= PyLong_SHIFT;
3038 assert(carry <= (PyLong_MASK << 1));
3039 }
3040 if (carry) {
3041 carry += *pz;
3042 *pz++ = (digit)(carry & PyLong_MASK);
3043 carry >>= PyLong_SHIFT;
3044 }
3045 if (carry)
3046 *pz += (digit)(carry & PyLong_MASK);
3047 assert((carry >> PyLong_SHIFT) == 0);
3048 }
3049 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003050 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 for (i = 0; i < size_a; ++i) {
3052 twodigits carry = 0;
3053 twodigits f = a->ob_digit[i];
3054 digit *pz = z->ob_digit + i;
3055 digit *pb = b->ob_digit;
3056 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003059 Py_DECREF(z);
3060 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003061 });
Tim Peters0973b992004-08-29 22:16:50 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 while (pb < pbend) {
3064 carry += *pz + *pb++ * f;
3065 *pz++ = (digit)(carry & PyLong_MASK);
3066 carry >>= PyLong_SHIFT;
3067 assert(carry <= PyLong_MASK);
3068 }
3069 if (carry)
3070 *pz += (digit)(carry & PyLong_MASK);
3071 assert((carry >> PyLong_SHIFT) == 0);
3072 }
3073 }
3074 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003075}
3076
3077/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003078 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003079 split, and sets low and high such that abs(n) == (high << size) + low,
3080 viewing the shift as being by digits. The sign bit is ignored, and
3081 the return values are >= 0.
3082 Returns 0 on success, -1 on failure.
3083*/
3084static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003085kmul_split(PyLongObject *n,
3086 Py_ssize_t size,
3087 PyLongObject **high,
3088 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 PyLongObject *hi, *lo;
3091 Py_ssize_t size_lo, size_hi;
3092 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003093
Victor Stinner640c35c2013-06-04 23:14:37 +02003094 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 if ((hi = _PyLong_New(size_hi)) == NULL)
3098 return -1;
3099 if ((lo = _PyLong_New(size_lo)) == NULL) {
3100 Py_DECREF(hi);
3101 return -1;
3102 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3105 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 *high = long_normalize(hi);
3108 *low = long_normalize(lo);
3109 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003110}
3111
Tim Peters60004642002-08-12 22:01:34 +00003112static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3113
Tim Peters5af4e6c2002-08-12 02:31:19 +00003114/* Karatsuba multiplication. Ignores the input signs, and returns the
3115 * absolute value of the product (or NULL if error).
3116 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3117 */
3118static PyLongObject *
3119k_mul(PyLongObject *a, PyLongObject *b)
3120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 Py_ssize_t asize = ABS(Py_SIZE(a));
3122 Py_ssize_t bsize = ABS(Py_SIZE(b));
3123 PyLongObject *ah = NULL;
3124 PyLongObject *al = NULL;
3125 PyLongObject *bh = NULL;
3126 PyLongObject *bl = NULL;
3127 PyLongObject *ret = NULL;
3128 PyLongObject *t1, *t2, *t3;
3129 Py_ssize_t shift; /* the number of digits we split off */
3130 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3133 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3134 * Then the original product is
3135 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3136 * By picking X to be a power of 2, "*X" is just shifting, and it's
3137 * been reduced to 3 multiplies on numbers half the size.
3138 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 /* We want to split based on the larger number; fiddle so that b
3141 * is largest.
3142 */
3143 if (asize > bsize) {
3144 t1 = a;
3145 a = b;
3146 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 i = asize;
3149 asize = bsize;
3150 bsize = i;
3151 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 /* Use gradeschool math when either number is too small. */
3154 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3155 if (asize <= i) {
3156 if (asize == 0)
3157 return (PyLongObject *)PyLong_FromLong(0);
3158 else
3159 return x_mul(a, b);
3160 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 /* If a is small compared to b, splitting on b gives a degenerate
3163 * case with ah==0, and Karatsuba may be (even much) less efficient
3164 * than "grade school" then. However, we can still win, by viewing
3165 * b as a string of "big digits", each of width a->ob_size. That
3166 * leads to a sequence of balanced calls to k_mul.
3167 */
3168 if (2 * asize <= bsize)
3169 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 /* Split a & b into hi & lo pieces. */
3172 shift = bsize >> 1;
3173 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3174 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 if (a == b) {
3177 bh = ah;
3178 bl = al;
3179 Py_INCREF(bh);
3180 Py_INCREF(bl);
3181 }
3182 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 /* The plan:
3185 * 1. Allocate result space (asize + bsize digits: that's always
3186 * enough).
3187 * 2. Compute ah*bh, and copy into result at 2*shift.
3188 * 3. Compute al*bl, and copy into result at 0. Note that this
3189 * can't overlap with #2.
3190 * 4. Subtract al*bl from the result, starting at shift. This may
3191 * underflow (borrow out of the high digit), but we don't care:
3192 * we're effectively doing unsigned arithmetic mod
3193 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3194 * borrows and carries out of the high digit can be ignored.
3195 * 5. Subtract ah*bh from the result, starting at shift.
3196 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3197 * at shift.
3198 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 /* 1. Allocate result space. */
3201 ret = _PyLong_New(asize + bsize);
3202 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003203#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 /* Fill with trash, to catch reference to uninitialized digits. */
3205 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003206#endif
Tim Peters44121a62002-08-12 06:17:58 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3209 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3210 assert(Py_SIZE(t1) >= 0);
3211 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3212 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3213 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 /* Zero-out the digits higher than the ah*bh copy. */
3216 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3217 if (i)
3218 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3219 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 /* 3. t2 <- al*bl, and copy into the low digits. */
3222 if ((t2 = k_mul(al, bl)) == NULL) {
3223 Py_DECREF(t1);
3224 goto fail;
3225 }
3226 assert(Py_SIZE(t2) >= 0);
3227 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3228 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 /* Zero out remaining digits. */
3231 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3232 if (i)
3233 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3236 * because it's fresher in cache.
3237 */
3238 i = Py_SIZE(ret) - shift; /* # digits after shift */
3239 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3240 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3243 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3246 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3247 Py_DECREF(ah);
3248 Py_DECREF(al);
3249 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 if (a == b) {
3252 t2 = t1;
3253 Py_INCREF(t2);
3254 }
3255 else if ((t2 = x_add(bh, bl)) == NULL) {
3256 Py_DECREF(t1);
3257 goto fail;
3258 }
3259 Py_DECREF(bh);
3260 Py_DECREF(bl);
3261 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 t3 = k_mul(t1, t2);
3264 Py_DECREF(t1);
3265 Py_DECREF(t2);
3266 if (t3 == NULL) goto fail;
3267 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 /* Add t3. It's not obvious why we can't run out of room here.
3270 * See the (*) comment after this function.
3271 */
3272 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3273 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003276
Mark Dickinson22b20182010-05-10 21:27:53 +00003277 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 Py_XDECREF(ret);
3279 Py_XDECREF(ah);
3280 Py_XDECREF(al);
3281 Py_XDECREF(bh);
3282 Py_XDECREF(bl);
3283 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003284}
3285
Tim Petersd6974a52002-08-13 20:37:51 +00003286/* (*) Why adding t3 can't "run out of room" above.
3287
Tim Petersab86c2b2002-08-15 20:06:00 +00003288Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3289to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003290
Tim Petersab86c2b2002-08-15 20:06:00 +000032911. For any integer i, i = c(i/2) + f(i/2). In particular,
3292 bsize = c(bsize/2) + f(bsize/2).
32932. shift = f(bsize/2)
32943. asize <= bsize
32954. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3296 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003297
Tim Petersab86c2b2002-08-15 20:06:00 +00003298We allocated asize + bsize result digits, and add t3 into them at an offset
3299of shift. This leaves asize+bsize-shift allocated digit positions for t3
3300to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3301asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003302
Tim Petersab86c2b2002-08-15 20:06:00 +00003303bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3304at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003305
Tim Petersab86c2b2002-08-15 20:06:00 +00003306If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3307digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3308most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003309
Tim Petersab86c2b2002-08-15 20:06:00 +00003310The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003311
Tim Petersab86c2b2002-08-15 20:06:00 +00003312 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003313
Tim Petersab86c2b2002-08-15 20:06:00 +00003314and we have asize + c(bsize/2) available digit positions. We need to show
3315this is always enough. An instance of c(bsize/2) cancels out in both, so
3316the question reduces to whether asize digits is enough to hold
3317(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3318then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3319asize 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 +00003320digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003321asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003322c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3323is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3324bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003325
Tim Peters48d52c02002-08-14 17:07:32 +00003326Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3327clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3328ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003329*/
3330
Tim Peters60004642002-08-12 22:01:34 +00003331/* b has at least twice the digits of a, and a is big enough that Karatsuba
3332 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3333 * of slices, each with a->ob_size digits, and multiply the slices by a,
3334 * one at a time. This gives k_mul balanced inputs to work with, and is
3335 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003336 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003337 * single-width slice overlap between successive partial sums).
3338 */
3339static PyLongObject *
3340k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 const Py_ssize_t asize = ABS(Py_SIZE(a));
3343 Py_ssize_t bsize = ABS(Py_SIZE(b));
3344 Py_ssize_t nbdone; /* # of b digits already multiplied */
3345 PyLongObject *ret;
3346 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 assert(asize > KARATSUBA_CUTOFF);
3349 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 /* Allocate result space, and zero it out. */
3352 ret = _PyLong_New(asize + bsize);
3353 if (ret == NULL)
3354 return NULL;
3355 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 /* Successive slices of b are copied into bslice. */
3358 bslice = _PyLong_New(asize);
3359 if (bslice == NULL)
3360 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 nbdone = 0;
3363 while (bsize > 0) {
3364 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003365 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 /* Multiply the next slice of b by a. */
3368 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3369 nbtouse * sizeof(digit));
3370 Py_SIZE(bslice) = nbtouse;
3371 product = k_mul(a, bslice);
3372 if (product == NULL)
3373 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 /* Add into result. */
3376 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3377 product->ob_digit, Py_SIZE(product));
3378 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 bsize -= nbtouse;
3381 nbdone += nbtouse;
3382 }
Tim Peters60004642002-08-12 22:01:34 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 Py_DECREF(bslice);
3385 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003386
Mark Dickinson22b20182010-05-10 21:27:53 +00003387 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 Py_DECREF(ret);
3389 Py_XDECREF(bslice);
3390 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003391}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003392
3393static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003394long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 /* fast path for single-digit multiplication */
3401 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3402 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003403#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003405#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 /* if we don't have long long then we're almost certainly
3407 using 15-bit digits, so v will fit in a long. In the
3408 unlikely event that we're using 30-bit digits on a platform
3409 without long long, a large v will just cause us to fall
3410 through to the general multiplication code below. */
3411 if (v >= LONG_MIN && v <= LONG_MAX)
3412 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003413#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 z = k_mul(a, b);
3417 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003418 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3419 _PyLong_Negate(&z);
3420 if (z == NULL)
3421 return NULL;
3422 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003424}
3425
Guido van Rossume32e0141992-01-19 16:31:05 +00003426/* The / and % operators are now defined in terms of divmod().
3427 The expression a mod b has the value a - b*floor(a/b).
3428 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003429 |a| by |b|, with the sign of a. This is also expressed
3430 as a - b*trunc(a/b), if trunc truncates towards zero.
3431 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 a b a rem b a mod b
3433 13 10 3 3
3434 -13 10 -3 7
3435 13 -10 3 -7
3436 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003437 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003438 have different signs. We then subtract one from the 'div'
3439 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003440
Tim Peters47e52ee2004-08-30 02:44:38 +00003441/* Compute
3442 * *pdiv, *pmod = divmod(v, w)
3443 * NULL can be passed for pdiv or pmod, in which case that part of
3444 * the result is simply thrown away. The caller owns a reference to
3445 * each of these it requests (does not pass NULL for).
3446 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003447static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003448l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 if (long_divrem(v, w, &div, &mod) < 0)
3454 return -1;
3455 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3456 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3457 PyLongObject *temp;
3458 PyLongObject *one;
3459 temp = (PyLongObject *) long_add(mod, w);
3460 Py_DECREF(mod);
3461 mod = temp;
3462 if (mod == NULL) {
3463 Py_DECREF(div);
3464 return -1;
3465 }
3466 one = (PyLongObject *) PyLong_FromLong(1L);
3467 if (one == NULL ||
3468 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3469 Py_DECREF(mod);
3470 Py_DECREF(div);
3471 Py_XDECREF(one);
3472 return -1;
3473 }
3474 Py_DECREF(one);
3475 Py_DECREF(div);
3476 div = temp;
3477 }
3478 if (pdiv != NULL)
3479 *pdiv = div;
3480 else
3481 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 if (pmod != NULL)
3484 *pmod = mod;
3485 else
3486 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003489}
3490
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003491static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003492long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 CHECK_BINOP(a, b);
3497 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3498 div = NULL;
3499 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003500}
3501
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003502/* PyLong/PyLong -> float, with correctly rounded result. */
3503
3504#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3505#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3506
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003507static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003508long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 PyLongObject *a, *b, *x;
3511 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3512 digit mask, low;
3513 int inexact, negate, a_is_small, b_is_small;
3514 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 CHECK_BINOP(v, w);
3517 a = (PyLongObject *)v;
3518 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 /*
3521 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3524 1. choose a suitable integer 'shift'
3525 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3526 3. adjust x for correct rounding
3527 4. convert x to a double dx with the same value
3528 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3533 returns either 0.0 or -0.0, depending on the sign of b. For a and
3534 b both nonzero, ignore signs of a and b, and add the sign back in
3535 at the end. Now write a_bits and b_bits for the bit lengths of a
3536 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3537 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3542 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3543 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3544 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 1. The integer 'shift' is chosen so that x has the right number of
3549 bits for a double, plus two or three extra bits that will be used
3550 in the rounding decisions. Writing a_bits and b_bits for the
3551 number of significant bits in a and b respectively, a
3552 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 This is fine in the usual case, but if a/b is smaller than the
3557 smallest normal float then it can lead to double rounding on an
3558 IEEE 754 platform, giving incorrectly rounded results. So we
3559 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 2. The quantity x is computed by first shifting a (left -shift bits
3564 if shift <= 0, right shift bits if shift > 0) and then dividing by
3565 b. For both the shift and the division, we keep track of whether
3566 the result is inexact, in a flag 'inexact'; this information is
3567 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 With the choice of shift above, together with our assumption that
3570 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3571 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3574 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 For float representability, we need x/2**extra_bits <
3579 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3580 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 To round, we just modify the bottom digit of x in-place; this can
3585 end up giving a digit with value > PyLONG_MASK, but that's not a
3586 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 With the original choices for shift above, extra_bits will always
3589 be 2 or 3. Then rounding under the round-half-to-even rule, we
3590 round up iff the most significant of the extra bits is 1, and
3591 either: (a) the computation of x in step 2 had an inexact result,
3592 or (b) at least one other of the extra bits is 1, or (c) the least
3593 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 4. Conversion to a double is straightforward; all floating-point
3596 operations involved in the conversion are exact, so there's no
3597 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3600 The result will always be exactly representable as a double, except
3601 in the case that it overflows. To avoid dependence on the exact
3602 behaviour of ldexp on overflow, we check for overflow before
3603 applying ldexp. The result of ldexp is adjusted for sign before
3604 returning.
3605 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 /* Reduce to case where a and b are both positive. */
3608 a_size = ABS(Py_SIZE(a));
3609 b_size = ABS(Py_SIZE(b));
3610 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3611 if (b_size == 0) {
3612 PyErr_SetString(PyExc_ZeroDivisionError,
3613 "division by zero");
3614 goto error;
3615 }
3616 if (a_size == 0)
3617 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 /* Fast path for a and b small (exactly representable in a double).
3620 Relies on floating-point division being correctly rounded; results
3621 may be subject to double rounding on x86 machines that operate with
3622 the x87 FPU set to 64-bit precision. */
3623 a_is_small = a_size <= MANT_DIG_DIGITS ||
3624 (a_size == MANT_DIG_DIGITS+1 &&
3625 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3626 b_is_small = b_size <= MANT_DIG_DIGITS ||
3627 (b_size == MANT_DIG_DIGITS+1 &&
3628 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3629 if (a_is_small && b_is_small) {
3630 double da, db;
3631 da = a->ob_digit[--a_size];
3632 while (a_size > 0)
3633 da = da * PyLong_BASE + a->ob_digit[--a_size];
3634 db = b->ob_digit[--b_size];
3635 while (b_size > 0)
3636 db = db * PyLong_BASE + b->ob_digit[--b_size];
3637 result = da / db;
3638 goto success;
3639 }
Tim Peterse2a60002001-09-04 06:17:36 +00003640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 /* Catch obvious cases of underflow and overflow */
3642 diff = a_size - b_size;
3643 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3644 /* Extreme overflow */
3645 goto overflow;
3646 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3647 /* Extreme underflow */
3648 goto underflow_or_zero;
3649 /* Next line is now safe from overflowing a Py_ssize_t */
3650 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3651 bits_in_digit(b->ob_digit[b_size - 1]);
3652 /* Now diff = a_bits - b_bits. */
3653 if (diff > DBL_MAX_EXP)
3654 goto overflow;
3655 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3656 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003659 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 /* x = abs(a * 2**-shift) */
3664 if (shift <= 0) {
3665 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3666 digit rem;
3667 /* x = a << -shift */
3668 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3669 /* In practice, it's probably impossible to end up
3670 here. Both a and b would have to be enormous,
3671 using close to SIZE_T_MAX bytes of memory each. */
3672 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003673 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 goto error;
3675 }
3676 x = _PyLong_New(a_size + shift_digits + 1);
3677 if (x == NULL)
3678 goto error;
3679 for (i = 0; i < shift_digits; i++)
3680 x->ob_digit[i] = 0;
3681 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3682 a_size, -shift % PyLong_SHIFT);
3683 x->ob_digit[a_size + shift_digits] = rem;
3684 }
3685 else {
3686 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3687 digit rem;
3688 /* x = a >> shift */
3689 assert(a_size >= shift_digits);
3690 x = _PyLong_New(a_size - shift_digits);
3691 if (x == NULL)
3692 goto error;
3693 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3694 a_size - shift_digits, shift % PyLong_SHIFT);
3695 /* set inexact if any of the bits shifted out is nonzero */
3696 if (rem)
3697 inexact = 1;
3698 while (!inexact && shift_digits > 0)
3699 if (a->ob_digit[--shift_digits])
3700 inexact = 1;
3701 }
3702 long_normalize(x);
3703 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3706 reference to x, so it's safe to modify it in-place. */
3707 if (b_size == 1) {
3708 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3709 b->ob_digit[0]);
3710 long_normalize(x);
3711 if (rem)
3712 inexact = 1;
3713 }
3714 else {
3715 PyLongObject *div, *rem;
3716 div = x_divrem(x, b, &rem);
3717 Py_DECREF(x);
3718 x = div;
3719 if (x == NULL)
3720 goto error;
3721 if (Py_SIZE(rem))
3722 inexact = 1;
3723 Py_DECREF(rem);
3724 }
3725 x_size = ABS(Py_SIZE(x));
3726 assert(x_size > 0); /* result of division is never zero */
3727 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003730 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 /* Round by directly modifying the low digit of x. */
3734 mask = (digit)1 << (extra_bits - 1);
3735 low = x->ob_digit[0] | inexact;
3736 if (low & mask && low & (3*mask-1))
3737 low += mask;
3738 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 /* Convert x to a double dx; the conversion is exact. */
3741 dx = x->ob_digit[--x_size];
3742 while (x_size > 0)
3743 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3744 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 /* Check whether ldexp result will overflow a double. */
3747 if (shift + x_bits >= DBL_MAX_EXP &&
3748 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3749 goto overflow;
3750 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003751
3752 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003754
3755 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003757
3758 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 PyErr_SetString(PyExc_OverflowError,
3760 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003761 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003763}
3764
3765static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003766long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 CHECK_BINOP(a, b);
3771
3772 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3773 mod = NULL;
3774 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003775}
3776
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003777static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003778long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 PyLongObject *div, *mod;
3781 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3786 return NULL;
3787 }
3788 z = PyTuple_New(2);
3789 if (z != NULL) {
3790 PyTuple_SetItem(z, 0, (PyObject *) div);
3791 PyTuple_SetItem(z, 1, (PyObject *) mod);
3792 }
3793 else {
3794 Py_DECREF(div);
3795 Py_DECREF(mod);
3796 }
3797 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003798}
3799
Tim Peters47e52ee2004-08-30 02:44:38 +00003800/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003801static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003802long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3805 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 PyLongObject *z = NULL; /* accumulated result */
3808 Py_ssize_t i, j, k; /* counters */
3809 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 /* 5-ary values. If the exponent is large enough, table is
3812 * precomputed so that table[i] == a**i % c for i in range(32).
3813 */
3814 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3815 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 /* a, b, c = v, w, x */
3818 CHECK_BINOP(v, w);
3819 a = (PyLongObject*)v; Py_INCREF(a);
3820 b = (PyLongObject*)w; Py_INCREF(b);
3821 if (PyLong_Check(x)) {
3822 c = (PyLongObject *)x;
3823 Py_INCREF(x);
3824 }
3825 else if (x == Py_None)
3826 c = NULL;
3827 else {
3828 Py_DECREF(a);
3829 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003830 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 }
Tim Peters4c483c42001-09-05 06:24:58 +00003832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3834 if (c) {
3835 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003836 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 goto Error;
3838 }
3839 else {
3840 /* else return a float. This works because we know
3841 that this calls float_pow() which converts its
3842 arguments to double. */
3843 Py_DECREF(a);
3844 Py_DECREF(b);
3845 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3846 }
3847 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 if (c) {
3850 /* if modulus == 0:
3851 raise ValueError() */
3852 if (Py_SIZE(c) == 0) {
3853 PyErr_SetString(PyExc_ValueError,
3854 "pow() 3rd argument cannot be 0");
3855 goto Error;
3856 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 /* if modulus < 0:
3859 negativeOutput = True
3860 modulus = -modulus */
3861 if (Py_SIZE(c) < 0) {
3862 negativeOutput = 1;
3863 temp = (PyLongObject *)_PyLong_Copy(c);
3864 if (temp == NULL)
3865 goto Error;
3866 Py_DECREF(c);
3867 c = temp;
3868 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02003869 _PyLong_Negate(&c);
3870 if (c == NULL)
3871 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 /* if modulus == 1:
3875 return 0 */
3876 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3877 z = (PyLongObject *)PyLong_FromLong(0L);
3878 goto Done;
3879 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 /* if base < 0:
3882 base = base % modulus
3883 Having the base positive just makes things easier. */
3884 if (Py_SIZE(a) < 0) {
3885 if (l_divmod(a, c, NULL, &temp) < 0)
3886 goto Error;
3887 Py_DECREF(a);
3888 a = temp;
3889 temp = NULL;
3890 }
3891 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 /* At this point a, b, and c are guaranteed non-negative UNLESS
3894 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 z = (PyLongObject *)PyLong_FromLong(1L);
3897 if (z == NULL)
3898 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 /* Perform a modular reduction, X = X % c, but leave X alone if c
3901 * is NULL.
3902 */
3903#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003904 do { \
3905 if (c != NULL) { \
3906 if (l_divmod(X, c, NULL, &temp) < 0) \
3907 goto Error; \
3908 Py_XDECREF(X); \
3909 X = temp; \
3910 temp = NULL; \
3911 } \
3912 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 /* Multiply two values, then reduce the result:
3915 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003916#define MULT(X, Y, result) \
3917 do { \
3918 temp = (PyLongObject *)long_mul(X, Y); \
3919 if (temp == NULL) \
3920 goto Error; \
3921 Py_XDECREF(result); \
3922 result = temp; \
3923 temp = NULL; \
3924 REDUCE(result); \
3925 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3928 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3929 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3930 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3931 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003934 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003936 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 }
3938 }
3939 }
3940 else {
3941 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3942 Py_INCREF(z); /* still holds 1L */
3943 table[0] = z;
3944 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003945 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3948 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3951 const int index = (bi >> j) & 0x1f;
3952 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003953 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003955 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 }
3957 }
3958 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 if (negativeOutput && (Py_SIZE(z) != 0)) {
3961 temp = (PyLongObject *)long_sub(z, c);
3962 if (temp == NULL)
3963 goto Error;
3964 Py_DECREF(z);
3965 z = temp;
3966 temp = NULL;
3967 }
3968 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003969
Mark Dickinson22b20182010-05-10 21:27:53 +00003970 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02003971 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003973 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3975 for (i = 0; i < 32; ++i)
3976 Py_XDECREF(table[i]);
3977 }
3978 Py_DECREF(a);
3979 Py_DECREF(b);
3980 Py_XDECREF(c);
3981 Py_XDECREF(temp);
3982 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003983}
3984
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003985static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003986long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 /* Implement ~x as -(x+1) */
3989 PyLongObject *x;
3990 PyLongObject *w;
3991 if (ABS(Py_SIZE(v)) <=1)
3992 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3993 w = (PyLongObject *)PyLong_FromLong(1L);
3994 if (w == NULL)
3995 return NULL;
3996 x = (PyLongObject *) long_add(v, w);
3997 Py_DECREF(w);
3998 if (x == NULL)
3999 return NULL;
4000 Py_SIZE(x) = -(Py_SIZE(x));
4001 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004002}
4003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004004static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004005long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 PyLongObject *z;
4008 if (ABS(Py_SIZE(v)) <= 1)
4009 return PyLong_FromLong(-MEDIUM_VALUE(v));
4010 z = (PyLongObject *)_PyLong_Copy(v);
4011 if (z != NULL)
4012 Py_SIZE(z) = -(Py_SIZE(v));
4013 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004014}
4015
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004016static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004017long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 if (Py_SIZE(v) < 0)
4020 return long_neg(v);
4021 else
4022 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004023}
4024
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004025static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004026long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004029}
4030
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004031static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004032long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 PyLongObject *z = NULL;
4035 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4036 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 if (Py_SIZE(a) < 0) {
4041 /* Right shifting negative numbers is harder */
4042 PyLongObject *a1, *a2;
4043 a1 = (PyLongObject *) long_invert(a);
4044 if (a1 == NULL)
4045 goto rshift_error;
4046 a2 = (PyLongObject *) long_rshift(a1, b);
4047 Py_DECREF(a1);
4048 if (a2 == NULL)
4049 goto rshift_error;
4050 z = (PyLongObject *) long_invert(a2);
4051 Py_DECREF(a2);
4052 }
4053 else {
4054 shiftby = PyLong_AsSsize_t((PyObject *)b);
4055 if (shiftby == -1L && PyErr_Occurred())
4056 goto rshift_error;
4057 if (shiftby < 0) {
4058 PyErr_SetString(PyExc_ValueError,
4059 "negative shift count");
4060 goto rshift_error;
4061 }
4062 wordshift = shiftby / PyLong_SHIFT;
4063 newsize = ABS(Py_SIZE(a)) - wordshift;
4064 if (newsize <= 0)
4065 return PyLong_FromLong(0);
4066 loshift = shiftby % PyLong_SHIFT;
4067 hishift = PyLong_SHIFT - loshift;
4068 lomask = ((digit)1 << hishift) - 1;
4069 himask = PyLong_MASK ^ lomask;
4070 z = _PyLong_New(newsize);
4071 if (z == NULL)
4072 goto rshift_error;
4073 if (Py_SIZE(a) < 0)
4074 Py_SIZE(z) = -(Py_SIZE(z));
4075 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4076 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4077 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004078 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 }
4080 z = long_normalize(z);
4081 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004082 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004084
Guido van Rossumc6913e71991-11-19 20:26:46 +00004085}
4086
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004087static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004088long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 /* This version due to Tim Peters */
4091 PyLongObject *a = (PyLongObject*)v;
4092 PyLongObject *b = (PyLongObject*)w;
4093 PyLongObject *z = NULL;
4094 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4095 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 shiftby = PyLong_AsSsize_t((PyObject *)b);
4100 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004101 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 if (shiftby < 0) {
4103 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004104 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 }
4106 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4107 wordshift = shiftby / PyLong_SHIFT;
4108 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 oldsize = ABS(Py_SIZE(a));
4111 newsize = oldsize + wordshift;
4112 if (remshift)
4113 ++newsize;
4114 z = _PyLong_New(newsize);
4115 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004116 return NULL;
4117 if (Py_SIZE(a) < 0) {
4118 assert(Py_REFCNT(z) == 1);
4119 Py_SIZE(z) = -Py_SIZE(z);
4120 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 for (i = 0; i < wordshift; i++)
4122 z->ob_digit[i] = 0;
4123 accum = 0;
4124 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4125 accum |= (twodigits)a->ob_digit[j] << remshift;
4126 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4127 accum >>= PyLong_SHIFT;
4128 }
4129 if (remshift)
4130 z->ob_digit[newsize-1] = (digit)accum;
4131 else
4132 assert(!accum);
4133 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004135}
4136
Mark Dickinson27a87a22009-10-25 20:43:34 +00004137/* Compute two's complement of digit vector a[0:m], writing result to
4138 z[0:m]. The digit vector a need not be normalized, but should not
4139 be entirely zero. a and z may point to the same digit vector. */
4140
4141static void
4142v_complement(digit *z, digit *a, Py_ssize_t m)
4143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 Py_ssize_t i;
4145 digit carry = 1;
4146 for (i = 0; i < m; ++i) {
4147 carry += a[i] ^ PyLong_MASK;
4148 z[i] = carry & PyLong_MASK;
4149 carry >>= PyLong_SHIFT;
4150 }
4151 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004152}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004153
4154/* Bitwise and/xor/or operations */
4155
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004156static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004157long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004158 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004159 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 int nega, negb, negz;
4162 Py_ssize_t size_a, size_b, size_z, i;
4163 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 /* Bitwise operations for negative numbers operate as though
4166 on a two's complement representation. So convert arguments
4167 from sign-magnitude to two's complement, and convert the
4168 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 /* If a is negative, replace it by its two's complement. */
4171 size_a = ABS(Py_SIZE(a));
4172 nega = Py_SIZE(a) < 0;
4173 if (nega) {
4174 z = _PyLong_New(size_a);
4175 if (z == NULL)
4176 return NULL;
4177 v_complement(z->ob_digit, a->ob_digit, size_a);
4178 a = z;
4179 }
4180 else
4181 /* Keep reference count consistent. */
4182 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 /* Same for b. */
4185 size_b = ABS(Py_SIZE(b));
4186 negb = Py_SIZE(b) < 0;
4187 if (negb) {
4188 z = _PyLong_New(size_b);
4189 if (z == NULL) {
4190 Py_DECREF(a);
4191 return NULL;
4192 }
4193 v_complement(z->ob_digit, b->ob_digit, size_b);
4194 b = z;
4195 }
4196 else
4197 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 /* Swap a and b if necessary to ensure size_a >= size_b. */
4200 if (size_a < size_b) {
4201 z = a; a = b; b = z;
4202 size_z = size_a; size_a = size_b; size_b = size_z;
4203 negz = nega; nega = negb; negb = negz;
4204 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 /* JRH: The original logic here was to allocate the result value (z)
4207 as the longer of the two operands. However, there are some cases
4208 where the result is guaranteed to be shorter than that: AND of two
4209 positives, OR of two negatives: use the shorter number. AND with
4210 mixed signs: use the positive number. OR with mixed signs: use the
4211 negative number.
4212 */
4213 switch (op) {
4214 case '^':
4215 negz = nega ^ negb;
4216 size_z = size_a;
4217 break;
4218 case '&':
4219 negz = nega & negb;
4220 size_z = negb ? size_a : size_b;
4221 break;
4222 case '|':
4223 negz = nega | negb;
4224 size_z = negb ? size_b : size_a;
4225 break;
4226 default:
4227 PyErr_BadArgument();
4228 return NULL;
4229 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 /* We allow an extra digit if z is negative, to make sure that
4232 the final two's complement of z doesn't overflow. */
4233 z = _PyLong_New(size_z + negz);
4234 if (z == NULL) {
4235 Py_DECREF(a);
4236 Py_DECREF(b);
4237 return NULL;
4238 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004240 /* Compute digits for overlap of a and b. */
4241 switch(op) {
4242 case '&':
4243 for (i = 0; i < size_b; ++i)
4244 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4245 break;
4246 case '|':
4247 for (i = 0; i < size_b; ++i)
4248 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4249 break;
4250 case '^':
4251 for (i = 0; i < size_b; ++i)
4252 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4253 break;
4254 default:
4255 PyErr_BadArgument();
4256 return NULL;
4257 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 /* Copy any remaining digits of a, inverting if necessary. */
4260 if (op == '^' && negb)
4261 for (; i < size_z; ++i)
4262 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4263 else if (i < size_z)
4264 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4265 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 /* Complement result if negative. */
4268 if (negz) {
4269 Py_SIZE(z) = -(Py_SIZE(z));
4270 z->ob_digit[size_z] = PyLong_MASK;
4271 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4272 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 Py_DECREF(a);
4275 Py_DECREF(b);
4276 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004277}
4278
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004279static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004280long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 PyObject *c;
4283 CHECK_BINOP(a, b);
4284 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4285 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004286}
4287
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004288static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004289long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004291 PyObject *c;
4292 CHECK_BINOP(a, b);
4293 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4294 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004295}
4296
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004297static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004298long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 PyObject *c;
4301 CHECK_BINOP(a, b);
4302 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4303 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004304}
4305
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004306static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004307long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 if (PyLong_CheckExact(v))
4310 Py_INCREF(v);
4311 else
4312 v = _PyLong_Copy((PyLongObject *)v);
4313 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004314}
4315
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004316static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004317long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 double result;
4320 result = PyLong_AsDouble(v);
4321 if (result == -1.0 && PyErr_Occurred())
4322 return NULL;
4323 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004324}
4325
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004326static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004327long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004328
Tim Peters6d6c1a32001-08-02 04:15:00 +00004329static PyObject *
4330long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4331{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004332 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004333 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 if (type != &PyLong_Type)
4337 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004338 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4339 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004341 if (x == NULL) {
4342 if (obase != NULL) {
4343 PyErr_SetString(PyExc_TypeError,
4344 "int() missing string argument");
4345 return NULL;
4346 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004348 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004349 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004351
Gregory P. Smitha689e522012-12-25 22:38:32 -08004352 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004353 if (base == -1 && PyErr_Occurred())
4354 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004355 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004356 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004357 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004358 return NULL;
4359 }
4360
4361 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004362 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 if (PyByteArray_Check(x))
4366 string = PyByteArray_AS_STRING(x);
4367 else
4368 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004369 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 }
4371 else {
4372 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004373 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 return NULL;
4375 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004376}
4377
Serhiy Storchaka95949422013-08-27 19:40:23 +03004378/* Wimpy, slow approach to tp_new calls for subtypes of int:
4379 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004380 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004381 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004382*/
4383static PyObject *
4384long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 PyLongObject *tmp, *newobj;
4387 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 assert(PyType_IsSubtype(type, &PyLong_Type));
4390 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4391 if (tmp == NULL)
4392 return NULL;
4393 assert(PyLong_CheckExact(tmp));
4394 n = Py_SIZE(tmp);
4395 if (n < 0)
4396 n = -n;
4397 newobj = (PyLongObject *)type->tp_alloc(type, n);
4398 if (newobj == NULL) {
4399 Py_DECREF(tmp);
4400 return NULL;
4401 }
4402 assert(PyLong_Check(newobj));
4403 Py_SIZE(newobj) = Py_SIZE(tmp);
4404 for (i = 0; i < n; i++)
4405 newobj->ob_digit[i] = tmp->ob_digit[i];
4406 Py_DECREF(tmp);
4407 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004408}
4409
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004410static PyObject *
4411long_getnewargs(PyLongObject *v)
4412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004414}
4415
Guido van Rossumb43daf72007-08-01 18:08:08 +00004416static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004417long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004419}
4420
4421static PyObject *
4422long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004424}
4425
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004426static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004427long__format__(PyObject *self, PyObject *args)
4428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004430 _PyUnicodeWriter writer;
4431 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4434 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004435
Victor Stinner8f674cc2013-04-17 23:02:17 +02004436 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004437 ret = _PyLong_FormatAdvancedWriter(
4438 &writer,
4439 self,
4440 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4441 if (ret == -1) {
4442 _PyUnicodeWriter_Dealloc(&writer);
4443 return NULL;
4444 }
4445 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004446}
4447
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004448/* Return a pair (q, r) such that a = b * q + r, and
4449 abs(r) <= abs(b)/2, with equality possible only if q is even.
4450 In other words, q == a / b, rounded to the nearest integer using
4451 round-half-to-even. */
4452
4453PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004454_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004455{
4456 PyLongObject *quo = NULL, *rem = NULL;
4457 PyObject *one = NULL, *twice_rem, *result, *temp;
4458 int cmp, quo_is_odd, quo_is_neg;
4459
4460 /* Equivalent Python code:
4461
4462 def divmod_near(a, b):
4463 q, r = divmod(a, b)
4464 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4465 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4466 # positive, 2 * r < b if b negative.
4467 greater_than_half = 2*r > b if b > 0 else 2*r < b
4468 exactly_half = 2*r == b
4469 if greater_than_half or exactly_half and q % 2 == 1:
4470 q += 1
4471 r -= b
4472 return q, r
4473
4474 */
4475 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4476 PyErr_SetString(PyExc_TypeError,
4477 "non-integer arguments in division");
4478 return NULL;
4479 }
4480
4481 /* Do a and b have different signs? If so, quotient is negative. */
4482 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4483
4484 one = PyLong_FromLong(1L);
4485 if (one == NULL)
4486 return NULL;
4487
4488 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4489 goto error;
4490
4491 /* compare twice the remainder with the divisor, to see
4492 if we need to adjust the quotient and remainder */
4493 twice_rem = long_lshift((PyObject *)rem, one);
4494 if (twice_rem == NULL)
4495 goto error;
4496 if (quo_is_neg) {
4497 temp = long_neg((PyLongObject*)twice_rem);
4498 Py_DECREF(twice_rem);
4499 twice_rem = temp;
4500 if (twice_rem == NULL)
4501 goto error;
4502 }
4503 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4504 Py_DECREF(twice_rem);
4505
4506 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4507 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4508 /* fix up quotient */
4509 if (quo_is_neg)
4510 temp = long_sub(quo, (PyLongObject *)one);
4511 else
4512 temp = long_add(quo, (PyLongObject *)one);
4513 Py_DECREF(quo);
4514 quo = (PyLongObject *)temp;
4515 if (quo == NULL)
4516 goto error;
4517 /* and remainder */
4518 if (quo_is_neg)
4519 temp = long_add(rem, (PyLongObject *)b);
4520 else
4521 temp = long_sub(rem, (PyLongObject *)b);
4522 Py_DECREF(rem);
4523 rem = (PyLongObject *)temp;
4524 if (rem == NULL)
4525 goto error;
4526 }
4527
4528 result = PyTuple_New(2);
4529 if (result == NULL)
4530 goto error;
4531
4532 /* PyTuple_SET_ITEM steals references */
4533 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4534 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4535 Py_DECREF(one);
4536 return result;
4537
4538 error:
4539 Py_XDECREF(quo);
4540 Py_XDECREF(rem);
4541 Py_XDECREF(one);
4542 return NULL;
4543}
4544
Eric Smith8c663262007-08-25 02:26:07 +00004545static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004546long_round(PyObject *self, PyObject *args)
4547{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004548 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004549
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004550 /* To round an integer m to the nearest 10**n (n positive), we make use of
4551 * the divmod_near operation, defined by:
4552 *
4553 * divmod_near(a, b) = (q, r)
4554 *
4555 * where q is the nearest integer to the quotient a / b (the
4556 * nearest even integer in the case of a tie) and r == a - q * b.
4557 * Hence q * b = a - r is the nearest multiple of b to a,
4558 * preferring even multiples in the case of a tie.
4559 *
4560 * So the nearest multiple of 10**n to m is:
4561 *
4562 * m - divmod_near(m, 10**n)[1].
4563 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4565 return NULL;
4566 if (o_ndigits == NULL)
4567 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004568
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004569 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 if (ndigits == NULL)
4571 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004572
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004573 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 if (Py_SIZE(ndigits) >= 0) {
4575 Py_DECREF(ndigits);
4576 return long_long(self);
4577 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004578
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004579 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4580 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004582 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004584 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004585
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004586 result = PyLong_FromLong(10L);
4587 if (result == NULL) {
4588 Py_DECREF(ndigits);
4589 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004591
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004592 temp = long_pow(result, ndigits, Py_None);
4593 Py_DECREF(ndigits);
4594 Py_DECREF(result);
4595 result = temp;
4596 if (result == NULL)
4597 return NULL;
4598
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004599 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004600 Py_DECREF(result);
4601 result = temp;
4602 if (result == NULL)
4603 return NULL;
4604
4605 temp = long_sub((PyLongObject *)self,
4606 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4607 Py_DECREF(result);
4608 result = temp;
4609
4610 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004611}
4612
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004613static PyObject *
4614long_sizeof(PyLongObject *v)
4615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4619 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004620}
4621
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004622static PyObject *
4623long_bit_length(PyLongObject *v)
4624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 PyLongObject *result, *x, *y;
4626 Py_ssize_t ndigits, msd_bits = 0;
4627 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 assert(v != NULL);
4630 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 ndigits = ABS(Py_SIZE(v));
4633 if (ndigits == 0)
4634 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 msd = v->ob_digit[ndigits-1];
4637 while (msd >= 32) {
4638 msd_bits += 6;
4639 msd >>= 6;
4640 }
4641 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4644 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 /* expression above may overflow; use Python integers instead */
4647 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4648 if (result == NULL)
4649 return NULL;
4650 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4651 if (x == NULL)
4652 goto error;
4653 y = (PyLongObject *)long_mul(result, x);
4654 Py_DECREF(x);
4655 if (y == NULL)
4656 goto error;
4657 Py_DECREF(result);
4658 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4661 if (x == NULL)
4662 goto error;
4663 y = (PyLongObject *)long_add(result, x);
4664 Py_DECREF(x);
4665 if (y == NULL)
4666 goto error;
4667 Py_DECREF(result);
4668 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004671
Mark Dickinson22b20182010-05-10 21:27:53 +00004672 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 Py_DECREF(result);
4674 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004675}
4676
4677PyDoc_STRVAR(long_bit_length_doc,
4678"int.bit_length() -> int\n\
4679\n\
4680Number of bits necessary to represent self in binary.\n\
4681>>> bin(37)\n\
4682'0b100101'\n\
4683>>> (37).bit_length()\n\
46846");
4685
Christian Heimes53876d92008-04-19 00:31:39 +00004686#if 0
4687static PyObject *
4688long_is_finite(PyObject *v)
4689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004691}
4692#endif
4693
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004694
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004695static PyObject *
4696long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 PyObject *byteorder_str;
4699 PyObject *is_signed_obj = NULL;
4700 Py_ssize_t length;
4701 int little_endian;
4702 int is_signed;
4703 PyObject *bytes;
4704 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4707 &length, &byteorder_str,
4708 &is_signed_obj))
4709 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 if (args != NULL && Py_SIZE(args) > 2) {
4712 PyErr_SetString(PyExc_TypeError,
4713 "'signed' is a keyword-only argument");
4714 return NULL;
4715 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4718 little_endian = 1;
4719 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4720 little_endian = 0;
4721 else {
4722 PyErr_SetString(PyExc_ValueError,
4723 "byteorder must be either 'little' or 'big'");
4724 return NULL;
4725 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 if (is_signed_obj != NULL) {
4728 int cmp = PyObject_IsTrue(is_signed_obj);
4729 if (cmp < 0)
4730 return NULL;
4731 is_signed = cmp ? 1 : 0;
4732 }
4733 else {
4734 /* If the signed argument was omitted, use False as the
4735 default. */
4736 is_signed = 0;
4737 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 if (length < 0) {
4740 PyErr_SetString(PyExc_ValueError,
4741 "length argument must be non-negative");
4742 return NULL;
4743 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 bytes = PyBytes_FromStringAndSize(NULL, length);
4746 if (bytes == NULL)
4747 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004749 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4750 length, little_endian, is_signed) < 0) {
4751 Py_DECREF(bytes);
4752 return NULL;
4753 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004755 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004756}
4757
Mark Dickinson078c2532010-01-30 18:06:17 +00004758PyDoc_STRVAR(long_to_bytes_doc,
4759"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004760\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004761Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004762\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004764raised if the integer is not representable with the given number of\n\
4765bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004766\n\
4767The byteorder argument determines the byte order used to represent the\n\
4768integer. If byteorder is 'big', the most significant byte is at the\n\
4769beginning of the byte array. If byteorder is 'little', the most\n\
4770significant byte is at the end of the byte array. To request the native\n\
4771byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4772\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004773The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004775is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004776
4777static PyObject *
4778long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 PyObject *byteorder_str;
4781 PyObject *is_signed_obj = NULL;
4782 int little_endian;
4783 int is_signed;
4784 PyObject *obj;
4785 PyObject *bytes;
4786 PyObject *long_obj;
4787 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4790 &obj, &byteorder_str,
4791 &is_signed_obj))
4792 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004794 if (args != NULL && Py_SIZE(args) > 2) {
4795 PyErr_SetString(PyExc_TypeError,
4796 "'signed' is a keyword-only argument");
4797 return NULL;
4798 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4801 little_endian = 1;
4802 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4803 little_endian = 0;
4804 else {
4805 PyErr_SetString(PyExc_ValueError,
4806 "byteorder must be either 'little' or 'big'");
4807 return NULL;
4808 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 if (is_signed_obj != NULL) {
4811 int cmp = PyObject_IsTrue(is_signed_obj);
4812 if (cmp < 0)
4813 return NULL;
4814 is_signed = cmp ? 1 : 0;
4815 }
4816 else {
4817 /* If the signed argument was omitted, use False as the
4818 default. */
4819 is_signed = 0;
4820 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004822 bytes = PyObject_Bytes(obj);
4823 if (bytes == NULL)
4824 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 long_obj = _PyLong_FromByteArray(
4827 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4828 little_endian, is_signed);
4829 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 /* If from_bytes() was used on subclass, allocate new subclass
Serhiy Storchaka95949422013-08-27 19:40:23 +03004832 * instance, initialize it with decoded int value and return it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004833 */
4834 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4835 PyLongObject *newobj;
4836 int i;
4837 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 newobj = (PyLongObject *)type->tp_alloc(type, n);
4840 if (newobj == NULL) {
4841 Py_DECREF(long_obj);
4842 return NULL;
4843 }
4844 assert(PyLong_Check(newobj));
4845 Py_SIZE(newobj) = Py_SIZE(long_obj);
4846 for (i = 0; i < n; i++) {
4847 newobj->ob_digit[i] =
4848 ((PyLongObject *)long_obj)->ob_digit[i];
4849 }
4850 Py_DECREF(long_obj);
4851 return (PyObject *)newobj;
4852 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004855}
4856
Mark Dickinson078c2532010-01-30 18:06:17 +00004857PyDoc_STRVAR(long_from_bytes_doc,
4858"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4859\n\
4860Return the integer represented by the given array of bytes.\n\
4861\n\
4862The bytes argument must either support the buffer protocol or be an\n\
4863iterable object producing bytes. Bytes and bytearray are examples of\n\
4864built-in objects that support the buffer protocol.\n\
4865\n\
4866The byteorder argument determines the byte order used to represent the\n\
4867integer. If byteorder is 'big', the most significant byte is at the\n\
4868beginning of the byte array. If byteorder is 'little', the most\n\
4869significant byte is at the end of the byte array. To request the native\n\
4870byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4871\n\
4872The signed keyword-only argument indicates whether two's complement is\n\
4873used to represent the integer.");
4874
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004875static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004876 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4877 "Returns self, the complex conjugate of any int."},
4878 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4879 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004880#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004881 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4882 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004883#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004884 {"to_bytes", (PyCFunction)long_to_bytes,
4885 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4886 {"from_bytes", (PyCFunction)long_from_bytes,
4887 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4888 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4889 "Truncating an Integral returns itself."},
4890 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4891 "Flooring an Integral returns itself."},
4892 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4893 "Ceiling of an Integral returns itself."},
4894 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4895 "Rounding an Integral returns itself.\n"
4896 "Rounding with an ndigits argument also returns an integer."},
4897 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4898 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4899 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4900 "Returns size in memory, in bytes"},
4901 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004902};
4903
Guido van Rossumb43daf72007-08-01 18:08:08 +00004904static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004905 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004906 (getter)long_long, (setter)NULL,
4907 "the real part of a complex number",
4908 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004909 {"imag",
4910 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004911 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004912 NULL},
4913 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004914 (getter)long_long, (setter)NULL,
4915 "the numerator of a rational number in lowest terms",
4916 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004917 {"denominator",
4918 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004919 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004920 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004921 {NULL} /* Sentinel */
4922};
4923
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004924PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004925"int(x=0) -> integer\n\
4926int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004927\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004928Convert a number or string to an integer, or return 0 if no arguments\n\
4929are given. If x is a number, return x.__int__(). For floating point\n\
4930numbers, this truncates towards zero.\n\
4931\n\
4932If x is not a number or if base is given, then x must be a string,\n\
4933bytes, or bytearray instance representing an integer literal in the\n\
4934given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4935by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4936Base 0 means to interpret the base from the string as an integer literal.\n\
4937>>> int('0b100', base=0)\n\
49384");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004939
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004940static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004941 (binaryfunc)long_add, /*nb_add*/
4942 (binaryfunc)long_sub, /*nb_subtract*/
4943 (binaryfunc)long_mul, /*nb_multiply*/
4944 long_mod, /*nb_remainder*/
4945 long_divmod, /*nb_divmod*/
4946 long_pow, /*nb_power*/
4947 (unaryfunc)long_neg, /*nb_negative*/
4948 (unaryfunc)long_long, /*tp_positive*/
4949 (unaryfunc)long_abs, /*tp_absolute*/
4950 (inquiry)long_bool, /*tp_bool*/
4951 (unaryfunc)long_invert, /*nb_invert*/
4952 long_lshift, /*nb_lshift*/
4953 (binaryfunc)long_rshift, /*nb_rshift*/
4954 long_and, /*nb_and*/
4955 long_xor, /*nb_xor*/
4956 long_or, /*nb_or*/
4957 long_long, /*nb_int*/
4958 0, /*nb_reserved*/
4959 long_float, /*nb_float*/
4960 0, /* nb_inplace_add */
4961 0, /* nb_inplace_subtract */
4962 0, /* nb_inplace_multiply */
4963 0, /* nb_inplace_remainder */
4964 0, /* nb_inplace_power */
4965 0, /* nb_inplace_lshift */
4966 0, /* nb_inplace_rshift */
4967 0, /* nb_inplace_and */
4968 0, /* nb_inplace_xor */
4969 0, /* nb_inplace_or */
4970 long_div, /* nb_floor_divide */
4971 long_true_divide, /* nb_true_divide */
4972 0, /* nb_inplace_floor_divide */
4973 0, /* nb_inplace_true_divide */
4974 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004975};
4976
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004977PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004978 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4979 "int", /* tp_name */
4980 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4981 sizeof(digit), /* tp_itemsize */
4982 long_dealloc, /* tp_dealloc */
4983 0, /* tp_print */
4984 0, /* tp_getattr */
4985 0, /* tp_setattr */
4986 0, /* tp_reserved */
4987 long_to_decimal_string, /* tp_repr */
4988 &long_as_number, /* tp_as_number */
4989 0, /* tp_as_sequence */
4990 0, /* tp_as_mapping */
4991 (hashfunc)long_hash, /* tp_hash */
4992 0, /* tp_call */
4993 long_to_decimal_string, /* tp_str */
4994 PyObject_GenericGetAttr, /* tp_getattro */
4995 0, /* tp_setattro */
4996 0, /* tp_as_buffer */
4997 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4998 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4999 long_doc, /* tp_doc */
5000 0, /* tp_traverse */
5001 0, /* tp_clear */
5002 long_richcompare, /* tp_richcompare */
5003 0, /* tp_weaklistoffset */
5004 0, /* tp_iter */
5005 0, /* tp_iternext */
5006 long_methods, /* tp_methods */
5007 0, /* tp_members */
5008 long_getset, /* tp_getset */
5009 0, /* tp_base */
5010 0, /* tp_dict */
5011 0, /* tp_descr_get */
5012 0, /* tp_descr_set */
5013 0, /* tp_dictoffset */
5014 0, /* tp_init */
5015 0, /* tp_alloc */
5016 long_new, /* tp_new */
5017 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005018};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005019
Mark Dickinsonbd792642009-03-18 20:06:12 +00005020static PyTypeObject Int_InfoType;
5021
5022PyDoc_STRVAR(int_info__doc__,
5023"sys.int_info\n\
5024\n\
5025A struct sequence that holds information about Python's\n\
5026internal representation of integers. The attributes are read only.");
5027
5028static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005030 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005032};
5033
5034static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005035 "sys.int_info", /* name */
5036 int_info__doc__, /* doc */
5037 int_info_fields, /* fields */
5038 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005039};
5040
5041PyObject *
5042PyLong_GetInfo(void)
5043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 PyObject* int_info;
5045 int field = 0;
5046 int_info = PyStructSequence_New(&Int_InfoType);
5047 if (int_info == NULL)
5048 return NULL;
5049 PyStructSequence_SET_ITEM(int_info, field++,
5050 PyLong_FromLong(PyLong_SHIFT));
5051 PyStructSequence_SET_ITEM(int_info, field++,
5052 PyLong_FromLong(sizeof(digit)));
5053 if (PyErr_Occurred()) {
5054 Py_CLEAR(int_info);
5055 return NULL;
5056 }
5057 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005058}
5059
Guido van Rossumddefaf32007-01-14 03:31:43 +00005060int
5061_PyLong_Init(void)
5062{
5063#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 int ival, size;
5065 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5068 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5069 if (Py_TYPE(v) == &PyLong_Type) {
5070 /* The element is already initialized, most likely
5071 * the Python interpreter was initialized before.
5072 */
5073 Py_ssize_t refcnt;
5074 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5077 _Py_NewReference(op);
5078 /* _Py_NewReference sets the ref count to 1 but
5079 * the ref count might be larger. Set the refcnt
5080 * to the original refcnt + 1 */
5081 Py_REFCNT(op) = refcnt + 1;
5082 assert(Py_SIZE(op) == size);
5083 assert(v->ob_digit[0] == abs(ival));
5084 }
5085 else {
5086 PyObject_INIT(v, &PyLong_Type);
5087 }
5088 Py_SIZE(v) = size;
5089 v->ob_digit[0] = abs(ival);
5090 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005091#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005093 if (Int_InfoType.tp_name == NULL) {
5094 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5095 return 0;
5096 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005099}
5100
5101void
5102PyLong_Fini(void)
5103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 /* Integers are currently statically allocated. Py_DECREF is not
5105 needed, but Python must forget about the reference or multiple
5106 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005107#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 int i;
5109 PyLongObject *v = small_ints;
5110 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5111 _Py_DEC_REFTOTAL;
5112 _Py_ForgetReference((PyObject*)v);
5113 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005114#endif
5115}