blob: bbf7e7183eb66d5cdfdb73bc9023d5ed05b54be6 [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
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010033Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050039 PyObject *v;
Benjamin Peterson041c38a2014-03-14 21:47:23 -050040 assert(-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS);
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050041 v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000043#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 if (ival >= 0)
45 quick_int_allocs++;
46 else
47 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000050}
51#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
53 return get_small_int((sdigit)ival); \
54 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000057maybe_small_long(PyLongObject *v)
58{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020059 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 sdigit ival = MEDIUM_VALUE(v);
61 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
62 Py_DECREF(v);
63 return (PyLongObject *)get_small_int(ival);
64 }
65 }
66 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000067}
Guido van Rossumddefaf32007-01-14 03:31:43 +000068#else
69#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000070#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000071#endif
72
Serhiy Storchaka95949422013-08-27 19:40:23 +030073/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000074 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020075Py_LOCAL_INLINE(void)
76_PyLong_Negate(PyLongObject **x_p)
77{
78 PyLongObject *x;
79
80 x = (PyLongObject *)*x_p;
81 if (Py_REFCNT(x) == 1) {
82 Py_SIZE(x) = -Py_SIZE(x);
83 return;
84 }
85
86 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
87 Py_DECREF(x);
88}
89
Serhiy Storchaka95949422013-08-27 19:40:23 +030090/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000091 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030092 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000093 */
Tim Peters0973b992004-08-29 22:16:50 +000094#define KARATSUBA_CUTOFF 70
95#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000096
Tim Peters47e52ee2004-08-30 02:44:38 +000097/* For exponentiation, use the binary left-to-right algorithm
98 * unless the exponent contains more than FIVEARY_CUTOFF digits.
99 * In that case, do 5 bits at a time. The potential drawback is that
100 * a table of 2**5 intermediate results is computed.
101 */
102#define FIVEARY_CUTOFF 8
103
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000104#define SIGCHECK(PyTryBlock) \
105 do { \
106 if (PyErr_CheckSignals()) PyTryBlock \
107 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000108
Serhiy Storchaka95949422013-08-27 19:40:23 +0300109/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000110 Doesn't attempt to free the storage--in most cases, due to the nature
111 of the algorithms used, this could save at most be one word anyway. */
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200114long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000115{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200116 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 while (i > 0 && v->ob_digit[i-1] == 0)
120 --i;
121 if (i != j)
122 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
123 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000124}
125
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200126/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
127 using the nb_int slot, if available. Raise TypeError if either the
128 nb_int slot is not available or the result of the call to nb_int
129 returns something not of type int.
130*/
131PyLongObject *
132_PyLong_FromNbInt(PyObject *integral)
133{
134 PyNumberMethods *nb;
135 PyObject *result;
136
137 /* Fast path for the case that we already have an int. */
138 if (PyLong_CheckExact(integral)) {
139 Py_INCREF(integral);
140 return (PyLongObject *)integral;
141 }
142
143 nb = Py_TYPE(integral)->tp_as_number;
144 if (nb == NULL || nb->nb_int == NULL) {
145 PyErr_Format(PyExc_TypeError,
146 "an integer is required (got type %.200s)",
147 Py_TYPE(integral)->tp_name);
148 return NULL;
149 }
150
151 /* Convert using the nb_int slot, which should return something
152 of exact type int. */
153 result = nb->nb_int(integral);
154 if (!result || PyLong_CheckExact(result))
155 return (PyLongObject *)result;
156 if (!PyLong_Check(result)) {
157 PyErr_Format(PyExc_TypeError,
158 "__int__ returned non-int (type %.200s)",
159 result->ob_type->tp_name);
160 Py_DECREF(result);
161 return NULL;
162 }
163 /* Issue #17576: warn if 'result' not of exact type int. */
164 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
165 "__int__ returned non-int (type %.200s). "
166 "The ability to return an instance of a strict subclass of int "
167 "is deprecated, and may be removed in a future version of Python.",
168 result->ob_type->tp_name)) {
169 Py_DECREF(result);
170 return NULL;
171 }
172 return (PyLongObject *)result;
173}
174
175
Serhiy Storchaka95949422013-08-27 19:40:23 +0300176/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177 Return NULL and set exception if we run out of memory. */
178
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000179#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000181
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000182PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000183_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyLongObject *result;
186 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
187 sizeof(digit)*size. Previous incarnations of this code used
188 sizeof(PyVarObject) instead of the offsetof, but this risks being
189 incorrect in the presence of padding between the PyVarObject header
190 and the digits. */
191 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
192 PyErr_SetString(PyExc_OverflowError,
193 "too many digits in integer");
194 return NULL;
195 }
196 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
197 size*sizeof(digit));
198 if (!result) {
199 PyErr_NoMemory();
200 return NULL;
201 }
202 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000203}
204
Tim Peters64b5ce32001-09-10 20:52:51 +0000205PyObject *
206_PyLong_Copy(PyLongObject *src)
207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 PyLongObject *result;
209 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 assert(src != NULL);
212 i = Py_SIZE(src);
213 if (i < 0)
214 i = -(i);
215 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100216 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 CHECK_SMALL_INT(ival);
218 }
219 result = _PyLong_New(i);
220 if (result != NULL) {
221 Py_SIZE(result) = Py_SIZE(src);
222 while (--i >= 0)
223 result->ob_digit[i] = src->ob_digit[i];
224 }
225 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000226}
227
Serhiy Storchaka95949422013-08-27 19:40:23 +0300228/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000229
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000230PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000231PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 PyLongObject *v;
234 unsigned long abs_ival;
235 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
236 int ndigits = 0;
237 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (ival < 0) {
242 /* negate: can't write this as abs_ival = -ival since that
243 invokes undefined behaviour when ival is LONG_MIN */
244 abs_ival = 0U-(unsigned long)ival;
245 sign = -1;
246 }
247 else {
248 abs_ival = (unsigned long)ival;
249 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 /* Fast path for single-digit ints */
252 if (!(abs_ival >> PyLong_SHIFT)) {
253 v = _PyLong_New(1);
254 if (v) {
255 Py_SIZE(v) = sign;
256 v->ob_digit[0] = Py_SAFE_DOWNCAST(
257 abs_ival, unsigned long, digit);
258 }
259 return (PyObject*)v;
260 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000261
Mark Dickinson249b8982009-04-27 19:41:00 +0000262#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 /* 2 digits */
264 if (!(abs_ival >> 2*PyLong_SHIFT)) {
265 v = _PyLong_New(2);
266 if (v) {
267 Py_SIZE(v) = 2*sign;
268 v->ob_digit[0] = Py_SAFE_DOWNCAST(
269 abs_ival & PyLong_MASK, unsigned long, digit);
270 v->ob_digit[1] = Py_SAFE_DOWNCAST(
271 abs_ival >> PyLong_SHIFT, unsigned long, digit);
272 }
273 return (PyObject*)v;
274 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000275#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 /* Larger numbers: loop to determine number of digits */
278 t = abs_ival;
279 while (t) {
280 ++ndigits;
281 t >>= PyLong_SHIFT;
282 }
283 v = _PyLong_New(ndigits);
284 if (v != NULL) {
285 digit *p = v->ob_digit;
286 Py_SIZE(v) = ndigits*sign;
287 t = abs_ival;
288 while (t) {
289 *p++ = Py_SAFE_DOWNCAST(
290 t & PyLong_MASK, unsigned long, digit);
291 t >>= PyLong_SHIFT;
292 }
293 }
294 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000295}
296
Serhiy Storchaka95949422013-08-27 19:40:23 +0300297/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000298
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000300PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 PyLongObject *v;
303 unsigned long t;
304 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (ival < PyLong_BASE)
307 return PyLong_FromLong(ival);
308 /* Count the number of Python digits. */
309 t = (unsigned long)ival;
310 while (t) {
311 ++ndigits;
312 t >>= PyLong_SHIFT;
313 }
314 v = _PyLong_New(ndigits);
315 if (v != NULL) {
316 digit *p = v->ob_digit;
317 Py_SIZE(v) = ndigits;
318 while (ival) {
319 *p++ = (digit)(ival & PyLong_MASK);
320 ival >>= PyLong_SHIFT;
321 }
322 }
323 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000324}
325
Serhiy Storchaka95949422013-08-27 19:40:23 +0300326/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000327
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyLongObject *v;
332 double frac;
333 int i, ndig, expo, neg;
334 neg = 0;
335 if (Py_IS_INFINITY(dval)) {
336 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000337 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 return NULL;
339 }
340 if (Py_IS_NAN(dval)) {
341 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000342 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return NULL;
344 }
345 if (dval < 0.0) {
346 neg = 1;
347 dval = -dval;
348 }
349 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
350 if (expo <= 0)
351 return PyLong_FromLong(0L);
352 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
353 v = _PyLong_New(ndig);
354 if (v == NULL)
355 return NULL;
356 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
357 for (i = ndig; --i >= 0; ) {
358 digit bits = (digit)frac;
359 v->ob_digit[i] = bits;
360 frac = frac - (double)bits;
361 frac = ldexp(frac, PyLong_SHIFT);
362 }
363 if (neg)
364 Py_SIZE(v) = -(Py_SIZE(v));
365 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000366}
367
Thomas Wouters89f507f2006-12-13 04:49:30 +0000368/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
369 * anything about what happens when a signed integer operation overflows,
370 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700371 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000372 * (unsigned long)LONG_MAX, and for the smallest negative signed long
373 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
374 * However, some other compilers warn about applying unary minus to an
375 * unsigned operand. Hence the weird "0-".
376 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
378#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000379
Serhiy Storchaka95949422013-08-27 19:40:23 +0300380/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100381 method.
382
383 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
384 the result. Otherwise *overflow is 0.
385
386 For other errors (e.g., TypeError), return -1 and set an error condition.
387 In this case *overflow will be 0.
388*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000389
390long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000391PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200394 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 unsigned long x, prev;
396 long res;
397 Py_ssize_t i;
398 int sign;
399 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 *overflow = 0;
402 if (vv == NULL) {
403 PyErr_BadInternalCall();
404 return -1;
405 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000406
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200407 if (PyLong_Check(vv)) {
408 v = (PyLongObject *)vv;
409 }
410 else {
411 v = _PyLong_FromNbInt(vv);
412 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 return -1;
414 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 switch (i) {
421 case -1:
422 res = -(sdigit)v->ob_digit[0];
423 break;
424 case 0:
425 res = 0;
426 break;
427 case 1:
428 res = v->ob_digit[0];
429 break;
430 default:
431 sign = 1;
432 x = 0;
433 if (i < 0) {
434 sign = -1;
435 i = -(i);
436 }
437 while (--i >= 0) {
438 prev = x;
439 x = (x << PyLong_SHIFT) | v->ob_digit[i];
440 if ((x >> PyLong_SHIFT) != prev) {
441 *overflow = sign;
442 goto exit;
443 }
444 }
445 /* Haven't lost any bits, but casting to long requires extra
446 * care (see comment above).
447 */
448 if (x <= (unsigned long)LONG_MAX) {
449 res = (long)x * sign;
450 }
451 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
452 res = LONG_MIN;
453 }
454 else {
455 *overflow = sign;
456 /* res is already set to -1 */
457 }
458 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000459 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200461 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 }
463 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000464}
465
Serhiy Storchaka95949422013-08-27 19:40:23 +0300466/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100467 method. Return -1 and set an error if overflow occurs. */
468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000470PyLong_AsLong(PyObject *obj)
471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 int overflow;
473 long result = PyLong_AsLongAndOverflow(obj, &overflow);
474 if (overflow) {
475 /* XXX: could be cute and give a different
476 message for overflow == -1 */
477 PyErr_SetString(PyExc_OverflowError,
478 "Python int too large to convert to C long");
479 }
480 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000481}
482
Serhiy Storchaka95949422013-08-27 19:40:23 +0300483/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200484 method. Return -1 and set an error if overflow occurs. */
485
486int
487_PyLong_AsInt(PyObject *obj)
488{
489 int overflow;
490 long result = PyLong_AsLongAndOverflow(obj, &overflow);
491 if (overflow || result > INT_MAX || result < INT_MIN) {
492 /* XXX: could be cute and give a different
493 message for overflow == -1 */
494 PyErr_SetString(PyExc_OverflowError,
495 "Python int too large to convert to C int");
496 return -1;
497 }
498 return (int)result;
499}
500
Serhiy Storchaka95949422013-08-27 19:40:23 +0300501/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000502 Returns -1 and sets an error condition if overflow occurs. */
503
504Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000505PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200506 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 size_t x, prev;
508 Py_ssize_t i;
509 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (vv == NULL) {
512 PyErr_BadInternalCall();
513 return -1;
514 }
515 if (!PyLong_Check(vv)) {
516 PyErr_SetString(PyExc_TypeError, "an integer is required");
517 return -1;
518 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 v = (PyLongObject *)vv;
521 i = Py_SIZE(v);
522 switch (i) {
523 case -1: return -(sdigit)v->ob_digit[0];
524 case 0: return 0;
525 case 1: return v->ob_digit[0];
526 }
527 sign = 1;
528 x = 0;
529 if (i < 0) {
530 sign = -1;
531 i = -(i);
532 }
533 while (--i >= 0) {
534 prev = x;
535 x = (x << PyLong_SHIFT) | v->ob_digit[i];
536 if ((x >> PyLong_SHIFT) != prev)
537 goto overflow;
538 }
539 /* Haven't lost any bits, but casting to a signed type requires
540 * extra care (see comment above).
541 */
542 if (x <= (size_t)PY_SSIZE_T_MAX) {
543 return (Py_ssize_t)x * sign;
544 }
545 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
546 return PY_SSIZE_T_MIN;
547 }
548 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000549
Mark Dickinson22b20182010-05-10 21:27:53 +0000550 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyErr_SetString(PyExc_OverflowError,
552 "Python int too large to convert to C ssize_t");
553 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000554}
555
Serhiy Storchaka95949422013-08-27 19:40:23 +0300556/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000557 Returns -1 and sets an error condition if overflow occurs. */
558
559unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000560PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000561{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200562 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 unsigned long x, prev;
564 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (vv == NULL) {
567 PyErr_BadInternalCall();
568 return (unsigned long)-1;
569 }
570 if (!PyLong_Check(vv)) {
571 PyErr_SetString(PyExc_TypeError, "an integer is required");
572 return (unsigned long)-1;
573 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 v = (PyLongObject *)vv;
576 i = Py_SIZE(v);
577 x = 0;
578 if (i < 0) {
579 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000580 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return (unsigned long) -1;
582 }
583 switch (i) {
584 case 0: return 0;
585 case 1: return v->ob_digit[0];
586 }
587 while (--i >= 0) {
588 prev = x;
589 x = (x << PyLong_SHIFT) | v->ob_digit[i];
590 if ((x >> PyLong_SHIFT) != prev) {
591 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100592 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000593 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return (unsigned long) -1;
595 }
596 }
597 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000598}
599
Serhiy Storchaka95949422013-08-27 19:40:23 +0300600/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200601 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000602
603size_t
604PyLong_AsSize_t(PyObject *vv)
605{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200606 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 size_t x, prev;
608 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (vv == NULL) {
611 PyErr_BadInternalCall();
612 return (size_t) -1;
613 }
614 if (!PyLong_Check(vv)) {
615 PyErr_SetString(PyExc_TypeError, "an integer is required");
616 return (size_t)-1;
617 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 v = (PyLongObject *)vv;
620 i = Py_SIZE(v);
621 x = 0;
622 if (i < 0) {
623 PyErr_SetString(PyExc_OverflowError,
624 "can't convert negative value to size_t");
625 return (size_t) -1;
626 }
627 switch (i) {
628 case 0: return 0;
629 case 1: return v->ob_digit[0];
630 }
631 while (--i >= 0) {
632 prev = x;
633 x = (x << PyLong_SHIFT) | v->ob_digit[i];
634 if ((x >> PyLong_SHIFT) != prev) {
635 PyErr_SetString(PyExc_OverflowError,
636 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200637 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 }
639 }
640 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000641}
642
Serhiy Storchaka95949422013-08-27 19:40:23 +0300643/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000644 Returns -1 and sets an error condition if an error occurs. */
645
Guido van Rossumddefaf32007-01-14 03:31:43 +0000646static unsigned long
647_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000648{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200649 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 unsigned long x;
651 Py_ssize_t i;
652 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (vv == NULL || !PyLong_Check(vv)) {
655 PyErr_BadInternalCall();
656 return (unsigned long) -1;
657 }
658 v = (PyLongObject *)vv;
659 i = Py_SIZE(v);
660 switch (i) {
661 case 0: return 0;
662 case 1: return v->ob_digit[0];
663 }
664 sign = 1;
665 x = 0;
666 if (i < 0) {
667 sign = -1;
668 i = -i;
669 }
670 while (--i >= 0) {
671 x = (x << PyLong_SHIFT) | v->ob_digit[i];
672 }
673 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000674}
675
Guido van Rossumddefaf32007-01-14 03:31:43 +0000676unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200677PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyLongObject *lo;
680 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000681
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200682 if (op == NULL) {
683 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 return (unsigned long)-1;
685 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000686
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200687 if (PyLong_Check(op)) {
688 return _PyLong_AsUnsignedLongMask(op);
689 }
690
691 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (lo == NULL)
693 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200694
695 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
696 Py_DECREF(lo);
697 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000698}
699
Tim Peters5b8132f2003-01-31 15:52:05 +0000700int
701_PyLong_Sign(PyObject *vv)
702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 assert(v != NULL);
706 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000709}
710
Tim Petersbaefd9e2003-01-28 20:37:45 +0000711size_t
712_PyLong_NumBits(PyObject *vv)
713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyLongObject *v = (PyLongObject *)vv;
715 size_t result = 0;
716 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 assert(v != NULL);
719 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200720 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
722 if (ndigits > 0) {
723 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700724 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100726 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 do {
728 ++result;
729 if (result == 0)
730 goto Overflow;
731 msd >>= 1;
732 } while (msd);
733 }
734 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000735
Mark Dickinson22b20182010-05-10 21:27:53 +0000736 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
738 "to express in a platform size_t");
739 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000740}
741
Tim Peters2a9b3672001-06-11 21:23:58 +0000742PyObject *
743_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000745{
Mark Dickinson22b20182010-05-10 21:27:53 +0000746 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 int incr; /* direction to move pstartbyte */
748 const unsigned char* pendbyte; /* MSB of bytes */
749 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300750 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 PyLongObject* v; /* result */
752 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (n == 0)
755 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (little_endian) {
758 pstartbyte = bytes;
759 pendbyte = bytes + n - 1;
760 incr = 1;
761 }
762 else {
763 pstartbyte = bytes + n - 1;
764 pendbyte = bytes;
765 incr = -1;
766 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (is_signed)
769 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200772 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 is positive, and leading 0xff bytes if negative. */
774 {
775 size_t i;
776 const unsigned char* p = pendbyte;
777 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000778 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000781 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 break;
783 }
784 numsignificantbytes = n - i;
785 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
786 actually has 2 significant bytes. OTOH, 0xff0001 ==
787 -0x00ffff, so we wouldn't *need* to bump it there; but we
788 do for 0xffff = -0x0001. To be safe without bothering to
789 check every case, bump it regardless. */
790 if (is_signed && numsignificantbytes < n)
791 ++numsignificantbytes;
792 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000793
Serhiy Storchaka95949422013-08-27 19:40:23 +0300794 /* How many Python int digits do we need? We have
795 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
797 /* catch overflow before it happens */
798 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
799 PyErr_SetString(PyExc_OverflowError,
800 "byte array too long to convert to int");
801 return NULL;
802 }
803 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
804 v = _PyLong_New(ndigits);
805 if (v == NULL)
806 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 /* Copy the bits over. The tricky parts are computing 2's-comp on
809 the fly for signed numbers, and dealing with the mismatch between
810 8-bit bytes and (probably) 15-bit Python digits.*/
811 {
812 size_t i;
813 twodigits carry = 1; /* for 2's-comp calculation */
814 twodigits accum = 0; /* sliding register */
815 unsigned int accumbits = 0; /* number of bits in accum */
816 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
819 twodigits thisbyte = *p;
820 /* Compute correction for 2's comp, if needed. */
821 if (is_signed) {
822 thisbyte = (0xff ^ thisbyte) + carry;
823 carry = thisbyte >> 8;
824 thisbyte &= 0xff;
825 }
826 /* Because we're going LSB to MSB, thisbyte is
827 more significant than what's already in accum,
828 so needs to be prepended to accum. */
829 accum |= (twodigits)thisbyte << accumbits;
830 accumbits += 8;
831 if (accumbits >= PyLong_SHIFT) {
832 /* There's enough to fill a Python digit. */
833 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000834 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 ++idigit;
836 accum >>= PyLong_SHIFT;
837 accumbits -= PyLong_SHIFT;
838 assert(accumbits < PyLong_SHIFT);
839 }
840 }
841 assert(accumbits < PyLong_SHIFT);
842 if (accumbits) {
843 assert(idigit < ndigits);
844 v->ob_digit[idigit] = (digit)accum;
845 ++idigit;
846 }
847 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 Py_SIZE(v) = is_signed ? -idigit : idigit;
850 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000851}
852
853int
854_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 unsigned char* bytes, size_t n,
856 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000859 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000861 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
863 digit carry; /* for computing 2's-comp */
864 size_t j; /* # bytes filled */
865 unsigned char* p; /* pointer to next byte in bytes */
866 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (Py_SIZE(v) < 0) {
871 ndigits = -(Py_SIZE(v));
872 if (!is_signed) {
873 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000874 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return -1;
876 }
877 do_twos_comp = 1;
878 }
879 else {
880 ndigits = Py_SIZE(v);
881 do_twos_comp = 0;
882 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (little_endian) {
885 p = bytes;
886 pincr = 1;
887 }
888 else {
889 p = bytes + n - 1;
890 pincr = -1;
891 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 /* Copy over all the Python digits.
894 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300895 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 normalized. */
897 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
898 j = 0;
899 accum = 0;
900 accumbits = 0;
901 carry = do_twos_comp ? 1 : 0;
902 for (i = 0; i < ndigits; ++i) {
903 digit thisdigit = v->ob_digit[i];
904 if (do_twos_comp) {
905 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
906 carry = thisdigit >> PyLong_SHIFT;
907 thisdigit &= PyLong_MASK;
908 }
909 /* Because we're going LSB to MSB, thisdigit is more
910 significant than what's already in accum, so needs to be
911 prepended to accum. */
912 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* The most-significant digit may be (probably is) at least
915 partly empty. */
916 if (i == ndigits - 1) {
917 /* Count # of sign bits -- they needn't be stored,
918 * although for signed conversion we need later to
919 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000920 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 while (s != 0) {
922 s >>= 1;
923 accumbits++;
924 }
925 }
926 else
927 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Store as many bytes as possible. */
930 while (accumbits >= 8) {
931 if (j >= n)
932 goto Overflow;
933 ++j;
934 *p = (unsigned char)(accum & 0xff);
935 p += pincr;
936 accumbits -= 8;
937 accum >>= 8;
938 }
939 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Store the straggler (if any). */
942 assert(accumbits < 8);
943 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
944 if (accumbits > 0) {
945 if (j >= n)
946 goto Overflow;
947 ++j;
948 if (do_twos_comp) {
949 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300950 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 infinite supply of sign bits). */
952 accum |= (~(twodigits)0) << accumbits;
953 }
954 *p = (unsigned char)(accum & 0xff);
955 p += pincr;
956 }
957 else if (j == n && n > 0 && is_signed) {
958 /* The main loop filled the byte array exactly, so the code
959 just above didn't get to ensure there's a sign bit, and the
960 loop below wouldn't add one either. Make sure a sign bit
961 exists. */
962 unsigned char msb = *(p - pincr);
963 int sign_bit_set = msb >= 0x80;
964 assert(accumbits == 0);
965 if (sign_bit_set == do_twos_comp)
966 return 0;
967 else
968 goto Overflow;
969 }
Tim Peters05607ad2001-06-13 21:01:27 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Fill remaining bytes with copies of the sign bit. */
972 {
973 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
974 for ( ; j < n; ++j, p += pincr)
975 *p = signbyte;
976 }
Tim Peters05607ad2001-06-13 21:01:27 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000979
Mark Dickinson22b20182010-05-10 21:27:53 +0000980 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
982 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000983
Tim Peters2a9b3672001-06-11 21:23:58 +0000984}
985
Serhiy Storchaka95949422013-08-27 19:40:23 +0300986/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000987
988PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000989PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000990{
Mark Dickinson91044792012-10-18 19:21:43 +0100991#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -0700992 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100993#else
994
Tim Peters70128a12001-06-16 08:48:40 +0000995#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700996# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000997#endif
Benjamin Petersonca470632016-09-06 13:47:26 -0700998 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100999#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001000
Guido van Rossum78694d91998-09-18 14:14:13 +00001001}
1002
Serhiy Storchaka95949422013-08-27 19:40:23 +03001003/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001004
1005void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001006PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001007{
Tim Peters70128a12001-06-16 08:48:40 +00001008#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1012 x = PyLong_AsLong(vv);
1013 else
1014 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001015#else
Tim Peters70128a12001-06-16 08:48:40 +00001016
Tim Peters70128a12001-06-16 08:48:40 +00001017#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001018# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001019#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001020 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1023 x = PyLong_AsLongLong(vv);
1024 else
1025 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001026
1027#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (x == -1 && PyErr_Occurred())
1030 return NULL;
1031 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001032}
1033
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001034/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001035 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001036 */
1037
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001038#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001039
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001040/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001041
1042PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001043PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001046 unsigned long long abs_ival;
1047 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 int ndigits = 0;
1049 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 CHECK_SMALL_INT(ival);
1052 if (ival < 0) {
1053 /* avoid signed overflow on negation; see comments
1054 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001055 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 negative = 1;
1057 }
1058 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001059 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 /* Count the number of Python digits.
1063 We used to pick 5 ("big enough for anything"), but that's a
1064 waste of time and space given that 5*15 = 75 bits are rarely
1065 needed. */
1066 t = abs_ival;
1067 while (t) {
1068 ++ndigits;
1069 t >>= PyLong_SHIFT;
1070 }
1071 v = _PyLong_New(ndigits);
1072 if (v != NULL) {
1073 digit *p = v->ob_digit;
1074 Py_SIZE(v) = negative ? -ndigits : ndigits;
1075 t = abs_ival;
1076 while (t) {
1077 *p++ = (digit)(t & PyLong_MASK);
1078 t >>= PyLong_SHIFT;
1079 }
1080 }
1081 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001082}
1083
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001084/* Create a new int object from a C unsigned long long int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001085
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001086PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001087PyLong_FromUnsignedLongLong(unsigned long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001090 unsigned long long t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (ival < PyLong_BASE)
1094 return PyLong_FromLong((long)ival);
1095 /* Count the number of Python digits. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001096 t = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 while (t) {
1098 ++ndigits;
1099 t >>= PyLong_SHIFT;
1100 }
1101 v = _PyLong_New(ndigits);
1102 if (v != NULL) {
1103 digit *p = v->ob_digit;
1104 Py_SIZE(v) = ndigits;
1105 while (ival) {
1106 *p++ = (digit)(ival & PyLong_MASK);
1107 ival >>= PyLong_SHIFT;
1108 }
1109 }
1110 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001111}
1112
Serhiy Storchaka95949422013-08-27 19:40:23 +03001113/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114
1115PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001116PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 PyLongObject *v;
1119 size_t abs_ival;
1120 size_t t; /* unsigned so >> doesn't propagate sign bit */
1121 int ndigits = 0;
1122 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 CHECK_SMALL_INT(ival);
1125 if (ival < 0) {
1126 /* avoid signed overflow when ival = SIZE_T_MIN */
1127 abs_ival = (size_t)(-1-ival)+1;
1128 negative = 1;
1129 }
1130 else {
1131 abs_ival = (size_t)ival;
1132 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 /* Count the number of Python digits. */
1135 t = abs_ival;
1136 while (t) {
1137 ++ndigits;
1138 t >>= PyLong_SHIFT;
1139 }
1140 v = _PyLong_New(ndigits);
1141 if (v != NULL) {
1142 digit *p = v->ob_digit;
1143 Py_SIZE(v) = negative ? -ndigits : ndigits;
1144 t = abs_ival;
1145 while (t) {
1146 *p++ = (digit)(t & PyLong_MASK);
1147 t >>= PyLong_SHIFT;
1148 }
1149 }
1150 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001151}
1152
Serhiy Storchaka95949422013-08-27 19:40:23 +03001153/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001154
1155PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001156PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 PyLongObject *v;
1159 size_t t;
1160 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (ival < PyLong_BASE)
1163 return PyLong_FromLong((long)ival);
1164 /* Count the number of Python digits. */
1165 t = ival;
1166 while (t) {
1167 ++ndigits;
1168 t >>= PyLong_SHIFT;
1169 }
1170 v = _PyLong_New(ndigits);
1171 if (v != NULL) {
1172 digit *p = v->ob_digit;
1173 Py_SIZE(v) = ndigits;
1174 while (ival) {
1175 *p++ = (digit)(ival & PyLong_MASK);
1176 ival >>= PyLong_SHIFT;
1177 }
1178 }
1179 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001180}
1181
Serhiy Storchaka95949422013-08-27 19:40:23 +03001182/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001183 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001184
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001185long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001186PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001189 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001191 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (vv == NULL) {
1194 PyErr_BadInternalCall();
1195 return -1;
1196 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001197
1198 if (PyLong_Check(vv)) {
1199 v = (PyLongObject *)vv;
1200 }
1201 else {
1202 v = _PyLong_FromNbInt(vv);
1203 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001205 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001207
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001208 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001210 case -1:
1211 bytes = -(sdigit)v->ob_digit[0];
1212 break;
1213 case 0:
1214 bytes = 0;
1215 break;
1216 case 1:
1217 bytes = v->ob_digit[0];
1218 break;
1219 default:
1220 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001221 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001223 if (do_decref) {
1224 Py_DECREF(v);
1225 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001226
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001227 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001229 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 else
1231 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001232}
1233
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001234/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001235 Return -1 and set an error if overflow occurs. */
1236
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001237unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001238PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001241 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001243
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001244 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001246 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001248 if (!PyLong_Check(vv)) {
1249 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001250 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001251 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 v = (PyLongObject*)vv;
1254 switch(Py_SIZE(v)) {
1255 case 0: return 0;
1256 case 1: return v->ob_digit[0];
1257 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001258
Mark Dickinson22b20182010-05-10 21:27:53 +00001259 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001260 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001261
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001262 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001264 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 else
1266 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001267}
Tim Petersd1a7da62001-06-13 00:35:57 +00001268
Serhiy Storchaka95949422013-08-27 19:40:23 +03001269/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001270 Returns -1 and sets an error condition if an error occurs. */
1271
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001272static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001273_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001274{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001275 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001276 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 Py_ssize_t i;
1278 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (vv == NULL || !PyLong_Check(vv)) {
1281 PyErr_BadInternalCall();
1282 return (unsigned long) -1;
1283 }
1284 v = (PyLongObject *)vv;
1285 switch(Py_SIZE(v)) {
1286 case 0: return 0;
1287 case 1: return v->ob_digit[0];
1288 }
1289 i = Py_SIZE(v);
1290 sign = 1;
1291 x = 0;
1292 if (i < 0) {
1293 sign = -1;
1294 i = -i;
1295 }
1296 while (--i >= 0) {
1297 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1298 }
1299 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001300}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001301
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001302unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001303PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001306 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001307
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001308 if (op == NULL) {
1309 PyErr_BadInternalCall();
1310 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001312
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001313 if (PyLong_Check(op)) {
1314 return _PyLong_AsUnsignedLongLongMask(op);
1315 }
1316
1317 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001319 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001320
1321 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1322 Py_DECREF(lo);
1323 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001324}
Tim Petersd1a7da62001-06-13 00:35:57 +00001325
Serhiy Storchaka95949422013-08-27 19:40:23 +03001326/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001327 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001328
Mark Dickinson8d48b432011-10-23 20:47:14 +01001329 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1330 the result. Otherwise *overflow is 0.
1331
1332 For other errors (e.g., TypeError), return -1 and set an error condition.
1333 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001334*/
1335
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001336long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001337PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001340 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001341 unsigned long long x, prev;
1342 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 Py_ssize_t i;
1344 int sign;
1345 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 *overflow = 0;
1348 if (vv == NULL) {
1349 PyErr_BadInternalCall();
1350 return -1;
1351 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001352
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001353 if (PyLong_Check(vv)) {
1354 v = (PyLongObject *)vv;
1355 }
1356 else {
1357 v = _PyLong_FromNbInt(vv);
1358 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 return -1;
1360 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 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 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001394 if (x <= (unsigned long long)PY_LLONG_MAX) {
1395 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 }
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) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001407 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 }
1409 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001410}
1411
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001412#define CHECK_BINOP(v,w) \
1413 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001414 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1415 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001416 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001417
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001418/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1419 2**k if d is nonzero, else 0. */
1420
1421static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1423 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001424};
1425
1426static int
1427bits_in_digit(digit d)
1428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 int d_bits = 0;
1430 while (d >= 32) {
1431 d_bits += 6;
1432 d >>= 6;
1433 }
1434 d_bits += (int)BitLengthTable[d];
1435 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001436}
1437
Tim Peters877a2122002-08-12 05:09:36 +00001438/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1439 * is modified in place, by adding y to it. Carries are propagated as far as
1440 * x[m-1], and the remaining carry (0 or 1) is returned.
1441 */
1442static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001443v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 Py_ssize_t i;
1446 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 assert(m >= n);
1449 for (i = 0; i < n; ++i) {
1450 carry += x[i] + y[i];
1451 x[i] = carry & PyLong_MASK;
1452 carry >>= PyLong_SHIFT;
1453 assert((carry & 1) == carry);
1454 }
1455 for (; carry && i < m; ++i) {
1456 carry += x[i];
1457 x[i] = carry & PyLong_MASK;
1458 carry >>= PyLong_SHIFT;
1459 assert((carry & 1) == carry);
1460 }
1461 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001462}
1463
1464/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1465 * is modified in place, by subtracting y from it. Borrows are propagated as
1466 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1467 */
1468static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001469v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 Py_ssize_t i;
1472 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 assert(m >= n);
1475 for (i = 0; i < n; ++i) {
1476 borrow = x[i] - y[i] - borrow;
1477 x[i] = borrow & PyLong_MASK;
1478 borrow >>= PyLong_SHIFT;
1479 borrow &= 1; /* keep only 1 sign bit */
1480 }
1481 for (; borrow && i < m; ++i) {
1482 borrow = x[i] - borrow;
1483 x[i] = borrow & PyLong_MASK;
1484 borrow >>= PyLong_SHIFT;
1485 borrow &= 1;
1486 }
1487 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001488}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001489
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001490/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1491 * result in z[0:m], and return the d bits shifted out of the top.
1492 */
1493static digit
1494v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 Py_ssize_t i;
1497 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 assert(0 <= d && d < PyLong_SHIFT);
1500 for (i=0; i < m; i++) {
1501 twodigits acc = (twodigits)a[i] << d | carry;
1502 z[i] = (digit)acc & PyLong_MASK;
1503 carry = (digit)(acc >> PyLong_SHIFT);
1504 }
1505 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001506}
1507
1508/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1509 * result in z[0:m], and return the d bits shifted out of the bottom.
1510 */
1511static digit
1512v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 Py_ssize_t i;
1515 digit carry = 0;
1516 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 assert(0 <= d && d < PyLong_SHIFT);
1519 for (i=m; i-- > 0;) {
1520 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1521 carry = (digit)acc & mask;
1522 z[i] = (digit)(acc >> d);
1523 }
1524 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001525}
1526
Tim Peters212e6142001-07-14 12:23:19 +00001527/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1528 in pout, and returning the remainder. pin and pout point at the LSD.
1529 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001530 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001531 immutable. */
1532
1533static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001534inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 assert(n > 0 && n <= PyLong_MASK);
1539 pin += size;
1540 pout += size;
1541 while (--size >= 0) {
1542 digit hi;
1543 rem = (rem << PyLong_SHIFT) | *--pin;
1544 *--pout = hi = (digit)(rem / n);
1545 rem -= (twodigits)hi * n;
1546 }
1547 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001548}
1549
Serhiy Storchaka95949422013-08-27 19:40:23 +03001550/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001551 (as function result) and the remainder (through *prem).
1552 The sign of a is ignored; n should not be zero. */
1553
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001554static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001555divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001556{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001557 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 assert(n > 0 && n <= PyLong_MASK);
1561 z = _PyLong_New(size);
1562 if (z == NULL)
1563 return NULL;
1564 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1565 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001566}
1567
Serhiy Storchaka95949422013-08-27 19:40:23 +03001568/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001569 string. (Return value is non-shared so that callers can modify the
1570 returned value if necessary.) */
1571
Victor Stinnerd3f08822012-05-29 12:57:52 +02001572static int
1573long_to_decimal_string_internal(PyObject *aa,
1574 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001575 _PyUnicodeWriter *writer,
1576 _PyBytesWriter *bytes_writer,
1577 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001580 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 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;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001584 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001585 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 a = (PyLongObject *)aa;
1588 if (a == NULL || !PyLong_Check(a)) {
1589 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001590 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001592 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 /* quick and dirty upper bound for the number of digits
1596 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 But log2(a) < size_a * PyLong_SHIFT, and
1601 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001602 > 3.3 * _PyLong_DECIMAL_SHIFT
1603
1604 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1605 size_a + size_a / d < size_a + size_a / floor(d),
1606 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1607 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001609 d = (33 * _PyLong_DECIMAL_SHIFT) /
1610 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1611 assert(size_a < PY_SSIZE_T_MAX/2);
1612 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 scratch = _PyLong_New(size);
1614 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001615 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 /* convert array of base _PyLong_BASE digits in pin to an array of
1618 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1619 Volume 2 (3rd edn), section 4.4, Method 1b). */
1620 pin = a->ob_digit;
1621 pout = scratch->ob_digit;
1622 size = 0;
1623 for (i = size_a; --i >= 0; ) {
1624 digit hi = pin[i];
1625 for (j = 0; j < size; j++) {
1626 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1627 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1628 pout[j] = (digit)(z - (twodigits)hi *
1629 _PyLong_DECIMAL_BASE);
1630 }
1631 while (hi) {
1632 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1633 hi /= _PyLong_DECIMAL_BASE;
1634 }
1635 /* check for keyboard interrupt */
1636 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001637 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001638 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001639 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 }
1641 /* pout should have at least one digit, so that the case when a = 0
1642 works correctly */
1643 if (size == 0)
1644 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* calculate exact length of output string, and allocate */
1647 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1648 tenpow = 10;
1649 rem = pout[size-1];
1650 while (rem >= tenpow) {
1651 tenpow *= 10;
1652 strlen++;
1653 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001654 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001655 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1656 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001657 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001658 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001659 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001661 else if (bytes_writer) {
1662 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1663 if (*bytes_str == NULL) {
1664 Py_DECREF(scratch);
1665 return -1;
1666 }
1667 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001668 else {
1669 str = PyUnicode_New(strlen, '9');
1670 if (str == NULL) {
1671 Py_DECREF(scratch);
1672 return -1;
1673 }
1674 kind = PyUnicode_KIND(str);
1675 }
1676
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001677#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001678 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001679 /* pout[0] through pout[size-2] contribute exactly \
1680 _PyLong_DECIMAL_SHIFT digits each */ \
1681 for (i=0; i < size - 1; i++) { \
1682 rem = pout[i]; \
1683 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1684 *--p = '0' + rem % 10; \
1685 rem /= 10; \
1686 } \
1687 } \
1688 /* pout[size-1]: always produce at least one decimal digit */ \
1689 rem = pout[i]; \
1690 do { \
1691 *--p = '0' + rem % 10; \
1692 rem /= 10; \
1693 } while (rem != 0); \
1694 \
1695 /* and sign */ \
1696 if (negative) \
1697 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001698 } while (0)
1699
1700#define WRITE_UNICODE_DIGITS(TYPE) \
1701 do { \
1702 if (writer) \
1703 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1704 else \
1705 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1706 \
1707 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001708 \
1709 /* check we've counted correctly */ \
1710 if (writer) \
1711 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1712 else \
1713 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1714 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001717 if (bytes_writer) {
1718 char *p = *bytes_str + strlen;
1719 WRITE_DIGITS(p);
1720 assert(p == *bytes_str);
1721 }
1722 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001723 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001724 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001726 else if (kind == PyUnicode_2BYTE_KIND) {
1727 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001728 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001729 }
1730 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001731 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001732 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001733 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001734 }
1735#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001736#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001739 if (writer) {
1740 writer->pos += strlen;
1741 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001742 else if (bytes_writer) {
1743 (*bytes_str) += strlen;
1744 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001745 else {
1746 assert(_PyUnicode_CheckConsistency(str, 1));
1747 *p_output = (PyObject *)str;
1748 }
1749 return 0;
1750}
1751
1752static PyObject *
1753long_to_decimal_string(PyObject *aa)
1754{
1755 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001756 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001757 return NULL;
1758 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001759}
1760
Serhiy Storchaka95949422013-08-27 19:40:23 +03001761/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001762 which should be one of 2, 8 or 16. Return a string object.
1763 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1764 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001765
Victor Stinnerd3f08822012-05-29 12:57:52 +02001766static int
1767long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001768 PyObject **p_output, _PyUnicodeWriter *writer,
1769 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001770{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001771 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001772 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001773 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001775 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001776 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001778
Victor Stinnerd3f08822012-05-29 12:57:52 +02001779 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 if (a == NULL || !PyLong_Check(a)) {
1781 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001782 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001784 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001785 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 /* Compute a rough upper bound for the length of the string */
1788 switch (base) {
1789 case 16:
1790 bits = 4;
1791 break;
1792 case 8:
1793 bits = 3;
1794 break;
1795 case 2:
1796 bits = 1;
1797 break;
1798 default:
1799 assert(0); /* shouldn't ever get here */
1800 bits = 0; /* to silence gcc warning */
1801 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001802
Mark Dickinsone2846542012-04-20 21:21:24 +01001803 /* Compute exact length 'sz' of output string. */
1804 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001805 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001806 }
1807 else {
1808 Py_ssize_t size_a_in_bits;
1809 /* Ensure overflow doesn't occur during computation of sz. */
1810 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1811 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001812 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001813 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001814 }
1815 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1816 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001817 /* Allow 1 character for a '-' sign. */
1818 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1819 }
1820 if (alternate) {
1821 /* 2 characters for prefix */
1822 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001823 }
1824
Victor Stinnerd3f08822012-05-29 12:57:52 +02001825 if (writer) {
1826 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1827 return -1;
1828 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001830 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001831 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1832 if (*bytes_str == NULL)
1833 return -1;
1834 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001836 v = PyUnicode_New(sz, 'x');
1837 if (v == NULL)
1838 return -1;
1839 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001841
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001842#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001843 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001844 if (size_a == 0) { \
1845 *--p = '0'; \
1846 } \
1847 else { \
1848 /* JRH: special case for power-of-2 bases */ \
1849 twodigits accum = 0; \
1850 int accumbits = 0; /* # of bits in accum */ \
1851 Py_ssize_t i; \
1852 for (i = 0; i < size_a; ++i) { \
1853 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1854 accumbits += PyLong_SHIFT; \
1855 assert(accumbits >= bits); \
1856 do { \
1857 char cdigit; \
1858 cdigit = (char)(accum & (base - 1)); \
1859 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1860 *--p = cdigit; \
1861 accumbits -= bits; \
1862 accum >>= bits; \
1863 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1864 } \
1865 } \
1866 \
1867 if (alternate) { \
1868 if (base == 16) \
1869 *--p = 'x'; \
1870 else if (base == 8) \
1871 *--p = 'o'; \
1872 else /* (base == 2) */ \
1873 *--p = 'b'; \
1874 *--p = '0'; \
1875 } \
1876 if (negative) \
1877 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001878 } while (0)
1879
1880#define WRITE_UNICODE_DIGITS(TYPE) \
1881 do { \
1882 if (writer) \
1883 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1884 else \
1885 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1886 \
1887 WRITE_DIGITS(p); \
1888 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001889 if (writer) \
1890 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1891 else \
1892 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1893 } while (0)
1894
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001895 if (bytes_writer) {
1896 char *p = *bytes_str + sz;
1897 WRITE_DIGITS(p);
1898 assert(p == *bytes_str);
1899 }
1900 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001901 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001902 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001903 }
1904 else if (kind == PyUnicode_2BYTE_KIND) {
1905 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001906 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001907 }
1908 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001909 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001910 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001911 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001912 }
1913#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001914#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001915
1916 if (writer) {
1917 writer->pos += sz;
1918 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001919 else if (bytes_writer) {
1920 (*bytes_str) += sz;
1921 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001922 else {
1923 assert(_PyUnicode_CheckConsistency(v, 1));
1924 *p_output = v;
1925 }
1926 return 0;
1927}
1928
1929PyObject *
1930_PyLong_Format(PyObject *obj, int base)
1931{
1932 PyObject *str;
1933 int err;
1934 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001935 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001936 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001937 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001938 if (err == -1)
1939 return NULL;
1940 return str;
1941}
1942
1943int
1944_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1945 PyObject *obj,
1946 int base, int alternate)
1947{
1948 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001949 return long_to_decimal_string_internal(obj, NULL, writer,
1950 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001951 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001952 return long_format_binary(obj, base, alternate, NULL, writer,
1953 NULL, NULL);
1954}
1955
1956char*
1957_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1958 PyObject *obj,
1959 int base, int alternate)
1960{
1961 char *str2;
1962 int res;
1963 str2 = str;
1964 if (base == 10)
1965 res = long_to_decimal_string_internal(obj, NULL, NULL,
1966 writer, &str2);
1967 else
1968 res = long_format_binary(obj, base, alternate, NULL, NULL,
1969 writer, &str2);
1970 if (res < 0)
1971 return NULL;
1972 assert(str2 != NULL);
1973 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001974}
1975
Thomas Wouters477c8d52006-05-27 19:21:47 +00001976/* Table of digit values for 8-bit string -> integer conversion.
1977 * '0' maps to 0, ..., '9' maps to 9.
1978 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1979 * All other indices map to 37.
1980 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001981 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001982 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001983unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1985 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1986 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1987 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1988 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1989 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1990 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1991 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1992 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1993 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1994 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1995 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1996 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1997 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1998 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1999 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002000};
2001
2002/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002003 * 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 +03002004 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002005 * The point to this routine is that it takes time linear in the number of
2006 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002007 *
2008 * Return values:
2009 * -1 on syntax error (exception needs to be set, *res is untouched)
2010 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002011 */
Brett Cannona721aba2016-09-09 14:57:09 -07002012static int
2013long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002014{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002015 const char *p = *str;
2016 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002017 char prev = 0;
2018 int digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 int bits_per_char;
2020 Py_ssize_t n;
2021 PyLongObject *z;
2022 twodigits accum;
2023 int bits_in_accum;
2024 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2027 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002028 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002030 }
2031 /* count digits and set p to end-of-string */
2032 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2033 if (*p == '_') {
2034 if (prev == '_') {
2035 *str = p - 1;
2036 return -1;
2037 }
2038 } else {
2039 ++digits;
2040 }
2041 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002043 }
2044 if (prev == '_') {
2045 /* Trailing underscore not allowed. */
2046 *str = p - 1;
2047 return -1;
2048 }
2049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 *str = p;
2051 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
Brett Cannona721aba2016-09-09 14:57:09 -07002052 n = digits * bits_per_char + PyLong_SHIFT - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (n / bits_per_char < p - start) {
2054 PyErr_SetString(PyExc_ValueError,
2055 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002056 *res = NULL;
2057 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 }
2059 n = n / PyLong_SHIFT;
2060 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002061 if (z == NULL) {
2062 *res = NULL;
2063 return 0;
2064 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002065 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 * from least to most significant in both.
2067 */
2068 accum = 0;
2069 bits_in_accum = 0;
2070 pdigit = z->ob_digit;
2071 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002072 int k;
2073 if (*p == '_') {
2074 continue;
2075 }
2076 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 assert(k >= 0 && k < base);
2078 accum |= (twodigits)k << bits_in_accum;
2079 bits_in_accum += bits_per_char;
2080 if (bits_in_accum >= PyLong_SHIFT) {
2081 *pdigit++ = (digit)(accum & PyLong_MASK);
2082 assert(pdigit - z->ob_digit <= n);
2083 accum >>= PyLong_SHIFT;
2084 bits_in_accum -= PyLong_SHIFT;
2085 assert(bits_in_accum < PyLong_SHIFT);
2086 }
2087 }
2088 if (bits_in_accum) {
2089 assert(bits_in_accum <= PyLong_SHIFT);
2090 *pdigit++ = (digit)accum;
2091 assert(pdigit - z->ob_digit <= n);
2092 }
2093 while (pdigit - z->ob_digit < n)
2094 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002095 *res = long_normalize(z);
2096 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002097}
2098
Serhiy Storchaka95949422013-08-27 19:40:23 +03002099/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002100 * ignored.
2101 *
2102 * If successful, a PyLong object will be returned and 'pend' will be pointing
2103 * to the first unused byte unless it's NULL.
2104 *
2105 * If unsuccessful, NULL will be returned.
2106 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002107PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002108PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002111 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 PyLongObject *z = NULL;
2113 PyObject *strobj;
2114 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 if ((base != 0 && base < 2) || base > 36) {
2117 PyErr_SetString(PyExc_ValueError,
2118 "int() arg 2 must be >= 2 and <= 36");
2119 return NULL;
2120 }
Brett Cannona721aba2016-09-09 14:57:09 -07002121 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002123 }
2124 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002126 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 else if (*str == '-') {
2128 ++str;
2129 sign = -1;
2130 }
2131 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002132 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002134 }
2135 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002137 }
2138 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002140 }
2141 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002143 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 else {
2145 /* "old" (C-style) octal literal, now invalid.
2146 it might still be zero though */
2147 error_if_nonzero = 1;
2148 base = 10;
2149 }
2150 }
2151 if (str[0] == '0' &&
2152 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2153 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002154 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002156 /* One underscore allowed here. */
2157 if (*str == '_') {
2158 ++str;
2159 }
2160 }
2161 if (str[0] == '_') {
2162 /* May not start with underscores. */
2163 goto onError;
2164 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002167 if ((base & (base - 1)) == 0) {
2168 int res = long_from_binary_base(&str, base, &z);
2169 if (res < 0) {
2170 /* Syntax error. */
2171 goto onError;
2172 }
2173 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002175/***
2176Binary bases can be converted in time linear in the number of digits, because
2177Python's representation base is binary. Other bases (including decimal!) use
2178the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002179
Thomas Wouters477c8d52006-05-27 19:21:47 +00002180First some math: the largest integer that can be expressed in N base-B digits
2181is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2182case number of Python digits needed to hold it is the smallest integer n s.t.
2183
2184 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2185 BASE**n >= B**N [taking logs to base BASE]
2186 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2187
2188The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002189this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002190and the result is computed into it.
2191
2192The input string is actually treated as being in base base**i (i.e., i digits
2193are processed at a time), where two more static arrays hold:
2194
2195 convwidth_base[base] = the largest integer i such that base**i <= BASE
2196 convmultmax_base[base] = base ** convwidth_base[base]
2197
2198The first of these is the largest i such that i consecutive input digits
2199must fit in a single Python digit. The second is effectively the input
2200base we're really using.
2201
2202Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2203convmultmax_base[base], the result is "simply"
2204
2205 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2206
2207where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002208
2209Error analysis: as above, the number of Python digits `n` needed is worst-
2210case
2211
2212 n >= N * log(B)/log(BASE)
2213
2214where `N` is the number of input digits in base `B`. This is computed via
2215
2216 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2217
2218below. Two numeric concerns are how much space this can waste, and whether
2219the computed result can be too small. To be concrete, assume BASE = 2**15,
2220which is the default (and it's unlikely anyone changes that).
2221
2222Waste isn't a problem: provided the first input digit isn't 0, the difference
2223between the worst-case input with N digits and the smallest input with N
2224digits is about a factor of B, but B is small compared to BASE so at most
2225one allocated Python digit can remain unused on that count. If
2226N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2227and adding 1 returns a result 1 larger than necessary. However, that can't
2228happen: whenever B is a power of 2, long_from_binary_base() is called
2229instead, and it's impossible for B**i to be an integer power of 2**15 when
2230B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2231an exact integer when B is not a power of 2, since B**i has a prime factor
2232other than 2 in that case, but (2**15)**j's only prime factor is 2).
2233
2234The computed result can be too small if the true value of N*log(B)/log(BASE)
2235is a little bit larger than an exact integer, but due to roundoff errors (in
2236computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2237yields a numeric result a little less than that integer. Unfortunately, "how
2238close can a transcendental function get to an integer over some range?"
2239questions are generally theoretically intractable. Computer analysis via
2240continued fractions is practical: expand log(B)/log(BASE) via continued
2241fractions, giving a sequence i/j of "the best" rational approximations. Then
2242j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2243we can get very close to being in trouble, but very rarely. For example,
224476573 is a denominator in one of the continued-fraction approximations to
2245log(10)/log(2**15), and indeed:
2246
2247 >>> log(10)/log(2**15)*76573
2248 16958.000000654003
2249
2250is very close to an integer. If we were working with IEEE single-precision,
2251rounding errors could kill us. Finding worst cases in IEEE double-precision
2252requires better-than-double-precision log() functions, and Tim didn't bother.
2253Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002254new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002255This should happen extremely rarely, and in fact I don't have a test case
2256that triggers it(!). Instead the code was tested by artificially allocating
2257just 1 digit at the start, so that the copying code was exercised for every
2258digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002259***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002260 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 Py_ssize_t size_z;
Brett Cannona721aba2016-09-09 14:57:09 -07002262 int digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 int i;
2264 int convwidth;
2265 twodigits convmultmax, convmult;
2266 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002267 const char *scan, *lastdigit;
2268 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 static double log_base_BASE[37] = {0.0e0,};
2271 static int convwidth_base[37] = {0,};
2272 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 if (log_base_BASE[base] == 0.0) {
2275 twodigits convmax = base;
2276 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002277
Mark Dickinson22b20182010-05-10 21:27:53 +00002278 log_base_BASE[base] = (log((double)base) /
2279 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 for (;;) {
2281 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002282 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002284 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 convmax = next;
2286 ++i;
2287 }
2288 convmultmax_base[base] = convmax;
2289 assert(i > 0);
2290 convwidth_base[base] = i;
2291 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 /* Find length of the string of numeric characters. */
2294 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002295 lastdigit = str;
2296
2297 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2298 if (*scan == '_') {
2299 if (prev == '_') {
2300 /* Only one underscore allowed. */
2301 str = lastdigit + 1;
2302 goto onError;
2303 }
2304 }
2305 else {
2306 ++digits;
2307 lastdigit = scan;
2308 }
2309 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002311 }
2312 if (prev == '_') {
2313 /* Trailing underscore not allowed. */
2314 /* Set error pointer to first underscore. */
2315 str = lastdigit + 1;
2316 goto onError;
2317 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002318
Serhiy Storchaka95949422013-08-27 19:40:23 +03002319 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 * integer with this base and length. Note that there's no
2321 * need to initialize z->ob_digit -- no slot is read up before
2322 * being stored into.
2323 */
Brett Cannona721aba2016-09-09 14:57:09 -07002324 size_z = (Py_ssize_t)(digits * log_base_BASE[base]) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* Uncomment next line to test exceedingly rare copy code */
2326 /* size_z = 1; */
2327 assert(size_z > 0);
2328 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002329 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002331 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* `convwidth` consecutive input digits are treated as a single
2335 * digit in base `convmultmax`.
2336 */
2337 convwidth = convwidth_base[base];
2338 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 /* Work ;-) */
2341 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002342 if (*str == '_') {
2343 str++;
2344 continue;
2345 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* grab up to convwidth digits from the input string */
2347 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002348 for (i = 1; i < convwidth && str != scan; ++str) {
2349 if (*str == '_') {
2350 continue;
2351 }
2352 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002354 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 assert(c < PyLong_BASE);
2356 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 convmult = convmultmax;
2359 /* Calculate the shift only if we couldn't get
2360 * convwidth digits.
2361 */
2362 if (i != convwidth) {
2363 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002364 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002366 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* Multiply z by convmult, and add c. */
2370 pz = z->ob_digit;
2371 pzstop = pz + Py_SIZE(z);
2372 for (; pz < pzstop; ++pz) {
2373 c += (twodigits)*pz * convmult;
2374 *pz = (digit)(c & PyLong_MASK);
2375 c >>= PyLong_SHIFT;
2376 }
2377 /* carry off the current end? */
2378 if (c) {
2379 assert(c < PyLong_BASE);
2380 if (Py_SIZE(z) < size_z) {
2381 *pz = (digit)c;
2382 ++Py_SIZE(z);
2383 }
2384 else {
2385 PyLongObject *tmp;
2386 /* Extremely rare. Get more space. */
2387 assert(Py_SIZE(z) == size_z);
2388 tmp = _PyLong_New(size_z + 1);
2389 if (tmp == NULL) {
2390 Py_DECREF(z);
2391 return NULL;
2392 }
2393 memcpy(tmp->ob_digit,
2394 z->ob_digit,
2395 sizeof(digit) * size_z);
2396 Py_DECREF(z);
2397 z = tmp;
2398 z->ob_digit[size_z] = (digit)c;
2399 ++size_z;
2400 }
2401 }
2402 }
2403 }
Brett Cannona721aba2016-09-09 14:57:09 -07002404 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002406 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 if (error_if_nonzero) {
2408 /* reset the base to 0, else the exception message
2409 doesn't make too much sense */
2410 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002411 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 /* there might still be other problems, therefore base
2415 remains zero here for the same reason */
2416 }
Brett Cannona721aba2016-09-09 14:57:09 -07002417 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002419 }
2420 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002422 }
2423 while (*str && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002425 }
2426 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002430 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002431 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002432 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002433 }
2434 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002435 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002436 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002437 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002438
Mark Dickinson22b20182010-05-10 21:27:53 +00002439 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002440 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002441 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002442 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 Py_XDECREF(z);
2444 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2445 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002446 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002450 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 base, strobj);
2452 Py_DECREF(strobj);
2453 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002454}
2455
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002456/* Since PyLong_FromString doesn't have a length parameter,
2457 * check here for possible NULs in the string.
2458 *
2459 * Reports an invalid literal as a bytes object.
2460 */
2461PyObject *
2462_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2463{
2464 PyObject *result, *strobj;
2465 char *end = NULL;
2466
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002467 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002468 if (end == NULL || (result != NULL && end == s + len))
2469 return result;
2470 Py_XDECREF(result);
2471 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2472 if (strobj != NULL) {
2473 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002474 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002475 base, strobj);
2476 Py_DECREF(strobj);
2477 }
2478 return NULL;
2479}
2480
Guido van Rossum9e896b32000-04-05 20:11:21 +00002481PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002482PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002483{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002484 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2485 if (unicode == NULL)
2486 return NULL;
2487 v = PyLong_FromUnicodeObject(unicode, base);
2488 Py_DECREF(unicode);
2489 return v;
2490}
2491
2492PyObject *
2493PyLong_FromUnicodeObject(PyObject *u, int base)
2494{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002495 PyObject *result, *asciidig;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002496 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002497 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002499 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002500 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002502 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002503 if (buffer == NULL) {
2504 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002505 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2506 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002508 else {
2509 result = PyLong_FromString(buffer, &end, base);
2510 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2511 Py_DECREF(asciidig);
2512 return result;
2513 }
2514 Py_DECREF(asciidig);
2515 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002516 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002517 PyErr_Format(PyExc_ValueError,
2518 "invalid literal for int() with base %d: %.200R",
2519 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002520 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002521}
2522
Tim Peters9f688bf2000-07-07 15:53:28 +00002523/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002524static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002526static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002527
Serhiy Storchaka95949422013-08-27 19:40:23 +03002528/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002529
Guido van Rossume32e0141992-01-19 16:31:05 +00002530static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002531long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002533{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002534 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if (size_b == 0) {
2538 PyErr_SetString(PyExc_ZeroDivisionError,
2539 "integer division or modulo by zero");
2540 return -1;
2541 }
2542 if (size_a < size_b ||
2543 (size_a == size_b &&
2544 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2545 /* |a| < |b|. */
2546 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2547 if (*pdiv == NULL)
2548 return -1;
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002549 *prem = (PyLongObject *)long_long((PyObject *)a);
2550 if (*prem == NULL) {
2551 Py_CLEAR(*pdiv);
2552 return -1;
2553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 return 0;
2555 }
2556 if (size_b == 1) {
2557 digit rem = 0;
2558 z = divrem1(a, b->ob_digit[0], &rem);
2559 if (z == NULL)
2560 return -1;
2561 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2562 if (*prem == NULL) {
2563 Py_DECREF(z);
2564 return -1;
2565 }
2566 }
2567 else {
2568 z = x_divrem(a, b, prem);
2569 if (z == NULL)
2570 return -1;
2571 }
2572 /* Set the signs.
2573 The quotient z has the sign of a*b;
2574 the remainder r has the sign of a,
2575 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002576 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2577 _PyLong_Negate(&z);
2578 if (z == NULL) {
2579 Py_CLEAR(*prem);
2580 return -1;
2581 }
2582 }
2583 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2584 _PyLong_Negate(prem);
2585 if (*prem == NULL) {
2586 Py_DECREF(z);
2587 Py_CLEAR(*prem);
2588 return -1;
2589 }
2590 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 *pdiv = maybe_small_long(z);
2592 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002593}
2594
Serhiy Storchaka95949422013-08-27 19:40:23 +03002595/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002596 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002597
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002598static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002599x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 PyLongObject *v, *w, *a;
2602 Py_ssize_t i, k, size_v, size_w;
2603 int d;
2604 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2605 twodigits vv;
2606 sdigit zhi;
2607 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2610 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2611 handle the special case when the initial estimate q for a quotient
2612 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2613 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002616 size_v = Py_ABS(Py_SIZE(v1));
2617 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2619 v = _PyLong_New(size_v+1);
2620 if (v == NULL) {
2621 *prem = NULL;
2622 return NULL;
2623 }
2624 w = _PyLong_New(size_w);
2625 if (w == NULL) {
2626 Py_DECREF(v);
2627 *prem = NULL;
2628 return NULL;
2629 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2632 shift v1 left by the same amount. Results go into w and v. */
2633 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2634 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2635 assert(carry == 0);
2636 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2637 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2638 v->ob_digit[size_v] = carry;
2639 size_v++;
2640 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2643 at most (and usually exactly) k = size_v - size_w digits. */
2644 k = size_v - size_w;
2645 assert(k >= 0);
2646 a = _PyLong_New(k);
2647 if (a == NULL) {
2648 Py_DECREF(w);
2649 Py_DECREF(v);
2650 *prem = NULL;
2651 return NULL;
2652 }
2653 v0 = v->ob_digit;
2654 w0 = w->ob_digit;
2655 wm1 = w0[size_w-1];
2656 wm2 = w0[size_w-2];
2657 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2658 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2659 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002662 Py_DECREF(a);
2663 Py_DECREF(w);
2664 Py_DECREF(v);
2665 *prem = NULL;
2666 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002667 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 /* estimate quotient digit q; may overestimate by 1 (rare) */
2670 vtop = vk[size_w];
2671 assert(vtop <= wm1);
2672 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2673 q = (digit)(vv / wm1);
2674 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2675 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2676 | vk[size_w-2])) {
2677 --q;
2678 r += wm1;
2679 if (r >= PyLong_BASE)
2680 break;
2681 }
2682 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2685 zhi = 0;
2686 for (i = 0; i < size_w; ++i) {
2687 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2688 -PyLong_BASE * q <= z < PyLong_BASE */
2689 z = (sdigit)vk[i] + zhi -
2690 (stwodigits)q * (stwodigits)w0[i];
2691 vk[i] = (digit)z & PyLong_MASK;
2692 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002693 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 /* add w back if q was too large (this branch taken rarely) */
2697 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2698 if ((sdigit)vtop + zhi < 0) {
2699 carry = 0;
2700 for (i = 0; i < size_w; ++i) {
2701 carry += vk[i] + w0[i];
2702 vk[i] = carry & PyLong_MASK;
2703 carry >>= PyLong_SHIFT;
2704 }
2705 --q;
2706 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 /* store quotient digit */
2709 assert(q < PyLong_BASE);
2710 *--ak = q;
2711 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 /* unshift remainder; we reuse w to store the result */
2714 carry = v_rshift(w0, v0, size_w, d);
2715 assert(carry==0);
2716 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 *prem = long_normalize(w);
2719 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002720}
2721
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002722/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2723 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2724 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2725 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2726 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2727 -1.0. */
2728
2729/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2730#if DBL_MANT_DIG == 53
2731#define EXP2_DBL_MANT_DIG 9007199254740992.0
2732#else
2733#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2734#endif
2735
2736double
2737_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2740 /* See below for why x_digits is always large enough. */
2741 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2742 double dx;
2743 /* Correction term for round-half-to-even rounding. For a digit x,
2744 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2745 multiple of 4, rounding ties to a multiple of 8. */
2746 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002747
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002748 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 if (a_size == 0) {
2750 /* Special case for 0: significand 0.0, exponent 0. */
2751 *e = 0;
2752 return 0.0;
2753 }
2754 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2755 /* The following is an overflow-free version of the check
2756 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2757 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2758 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2759 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002760 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2764 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 Number of digits needed for result: write // for floor division.
2767 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2776 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2779 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2780 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 in both cases.
2787 */
2788 if (a_bits <= DBL_MANT_DIG + 2) {
2789 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2790 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2791 x_size = 0;
2792 while (x_size < shift_digits)
2793 x_digits[x_size++] = 0;
2794 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2795 (int)shift_bits);
2796 x_size += a_size;
2797 x_digits[x_size++] = rem;
2798 }
2799 else {
2800 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2801 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2802 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2803 a_size - shift_digits, (int)shift_bits);
2804 x_size = a_size - shift_digits;
2805 /* For correct rounding below, we need the least significant
2806 bit of x to be 'sticky' for this shift: if any of the bits
2807 shifted out was nonzero, we set the least significant bit
2808 of x. */
2809 if (rem)
2810 x_digits[0] |= 1;
2811 else
2812 while (shift_digits > 0)
2813 if (a->ob_digit[--shift_digits]) {
2814 x_digits[0] |= 1;
2815 break;
2816 }
2817 }
Victor Stinner63941882011-09-29 00:42:28 +02002818 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 /* Round, and convert to double. */
2821 x_digits[0] += half_even_correction[x_digits[0] & 7];
2822 dx = x_digits[--x_size];
2823 while (x_size > 0)
2824 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 /* Rescale; make correction if result is 1.0. */
2827 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2828 if (dx == 1.0) {
2829 if (a_bits == PY_SSIZE_T_MAX)
2830 goto overflow;
2831 dx = 0.5;
2832 a_bits += 1;
2833 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 *e = a_bits;
2836 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002837
2838 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 /* exponent > PY_SSIZE_T_MAX */
2840 PyErr_SetString(PyExc_OverflowError,
2841 "huge integer: number of bits overflows a Py_ssize_t");
2842 *e = 0;
2843 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002844}
2845
Serhiy Storchaka95949422013-08-27 19:40:23 +03002846/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002847 using the round-half-to-even rule in the case of a tie. */
2848
2849double
2850PyLong_AsDouble(PyObject *v)
2851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 Py_ssize_t exponent;
2853 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002854
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002855 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 PyErr_BadInternalCall();
2857 return -1.0;
2858 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002859 if (!PyLong_Check(v)) {
2860 PyErr_SetString(PyExc_TypeError, "an integer is required");
2861 return -1.0;
2862 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002863 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002864 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002865 to double. This improves performance of FP/long operations
2866 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002867 */
2868 return (double)MEDIUM_VALUE((PyLongObject *)v);
2869 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2871 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2872 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002873 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 return -1.0;
2875 }
2876 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002877}
2878
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002879/* Methods */
2880
2881static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002882long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002885}
2886
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002887static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002888long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 if (Py_SIZE(a) != Py_SIZE(b)) {
2893 sign = Py_SIZE(a) - Py_SIZE(b);
2894 }
2895 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002896 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2898 ;
2899 if (i < 0)
2900 sign = 0;
2901 else {
2902 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2903 if (Py_SIZE(a) < 0)
2904 sign = -sign;
2905 }
2906 }
2907 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002908}
2909
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002910#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002912
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002913static PyObject *
2914long_richcompare(PyObject *self, PyObject *other, int op)
2915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 int result;
2917 PyObject *v;
2918 CHECK_BINOP(self, other);
2919 if (self == other)
2920 result = 0;
2921 else
2922 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2923 /* Convert the return value to a Boolean */
2924 switch (op) {
2925 case Py_EQ:
2926 v = TEST_COND(result == 0);
2927 break;
2928 case Py_NE:
2929 v = TEST_COND(result != 0);
2930 break;
2931 case Py_LE:
2932 v = TEST_COND(result <= 0);
2933 break;
2934 case Py_GE:
2935 v = TEST_COND(result >= 0);
2936 break;
2937 case Py_LT:
2938 v = TEST_COND(result == -1);
2939 break;
2940 case Py_GT:
2941 v = TEST_COND(result == 1);
2942 break;
2943 default:
2944 PyErr_BadArgument();
2945 return NULL;
2946 }
2947 Py_INCREF(v);
2948 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002949}
2950
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002951static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002952long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002953{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002954 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 Py_ssize_t i;
2956 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 i = Py_SIZE(v);
2959 switch(i) {
2960 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2961 case 0: return 0;
2962 case 1: return v->ob_digit[0];
2963 }
2964 sign = 1;
2965 x = 0;
2966 if (i < 0) {
2967 sign = -1;
2968 i = -(i);
2969 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002971 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2972 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2973 _PyHASH_MODULUS.
2974
2975 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2976 amounts to a rotation of the bits of x. To see this, write
2977
2978 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2979
2980 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2981 PyLong_SHIFT bits of x (those that are shifted out of the
2982 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2983 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2984 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2985 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2986 congruent to y modulo _PyHASH_MODULUS. So
2987
2988 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2989
2990 The right-hand side is just the result of rotating the
2991 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2992 not all _PyHASH_BITS bits of x are 1s, the same is true
2993 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2994 the reduction of x*2**PyLong_SHIFT modulo
2995 _PyHASH_MODULUS. */
2996 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2997 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002999 if (x >= _PyHASH_MODULUS)
3000 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 }
3002 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003003 if (x == (Py_uhash_t)-1)
3004 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003005 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003006}
3007
3008
Serhiy Storchaka95949422013-08-27 19:40:23 +03003009/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003010
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003011static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003012x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003013{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003014 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 PyLongObject *z;
3016 Py_ssize_t i;
3017 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 /* Ensure a is the larger of the two: */
3020 if (size_a < size_b) {
3021 { PyLongObject *temp = a; a = b; b = temp; }
3022 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003023 size_a = size_b;
3024 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 }
3026 z = _PyLong_New(size_a+1);
3027 if (z == NULL)
3028 return NULL;
3029 for (i = 0; i < size_b; ++i) {
3030 carry += a->ob_digit[i] + b->ob_digit[i];
3031 z->ob_digit[i] = carry & PyLong_MASK;
3032 carry >>= PyLong_SHIFT;
3033 }
3034 for (; i < size_a; ++i) {
3035 carry += a->ob_digit[i];
3036 z->ob_digit[i] = carry & PyLong_MASK;
3037 carry >>= PyLong_SHIFT;
3038 }
3039 z->ob_digit[i] = carry;
3040 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003041}
3042
3043/* Subtract the absolute values of two integers. */
3044
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003045static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003046x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003047{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003048 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 PyLongObject *z;
3050 Py_ssize_t i;
3051 int sign = 1;
3052 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 /* Ensure a is the larger of the two: */
3055 if (size_a < size_b) {
3056 sign = -1;
3057 { PyLongObject *temp = a; a = b; b = temp; }
3058 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003059 size_a = size_b;
3060 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 }
3062 else if (size_a == size_b) {
3063 /* Find highest digit where a and b differ: */
3064 i = size_a;
3065 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3066 ;
3067 if (i < 0)
3068 return (PyLongObject *)PyLong_FromLong(0);
3069 if (a->ob_digit[i] < b->ob_digit[i]) {
3070 sign = -1;
3071 { PyLongObject *temp = a; a = b; b = temp; }
3072 }
3073 size_a = size_b = i+1;
3074 }
3075 z = _PyLong_New(size_a);
3076 if (z == NULL)
3077 return NULL;
3078 for (i = 0; i < size_b; ++i) {
3079 /* The following assumes unsigned arithmetic
3080 works module 2**N for some N>PyLong_SHIFT. */
3081 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3082 z->ob_digit[i] = borrow & PyLong_MASK;
3083 borrow >>= PyLong_SHIFT;
3084 borrow &= 1; /* Keep only one sign bit */
3085 }
3086 for (; i < size_a; ++i) {
3087 borrow = a->ob_digit[i] - borrow;
3088 z->ob_digit[i] = borrow & PyLong_MASK;
3089 borrow >>= PyLong_SHIFT;
3090 borrow &= 1; /* Keep only one sign bit */
3091 }
3092 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003093 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003094 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003095 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003097}
3098
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003099static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003100long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003105
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003106 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
3108 MEDIUM_VALUE(b));
3109 return result;
3110 }
3111 if (Py_SIZE(a) < 0) {
3112 if (Py_SIZE(b) < 0) {
3113 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003114 if (z != NULL) {
3115 /* x_add received at least one multiple-digit int,
3116 and thus z must be a multiple-digit int.
3117 That also means z is not an element of
3118 small_ints, so negating it in-place is safe. */
3119 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003121 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 }
3123 else
3124 z = x_sub(b, a);
3125 }
3126 else {
3127 if (Py_SIZE(b) < 0)
3128 z = x_sub(a, b);
3129 else
3130 z = x_add(a, b);
3131 }
3132 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003133}
3134
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003135static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003136long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003141
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003142 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 PyObject* r;
3144 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
3145 return r;
3146 }
3147 if (Py_SIZE(a) < 0) {
3148 if (Py_SIZE(b) < 0)
3149 z = x_sub(a, b);
3150 else
3151 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003152 if (z != NULL) {
3153 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003155 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 }
3157 else {
3158 if (Py_SIZE(b) < 0)
3159 z = x_add(a, b);
3160 else
3161 z = x_sub(a, b);
3162 }
3163 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003164}
3165
Tim Peters5af4e6c2002-08-12 02:31:19 +00003166/* Grade school multiplication, ignoring the signs.
3167 * Returns the absolute value of the product, or NULL if error.
3168 */
3169static PyLongObject *
3170x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003173 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3174 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 z = _PyLong_New(size_a + size_b);
3178 if (z == NULL)
3179 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3182 if (a == b) {
3183 /* Efficient squaring per HAC, Algorithm 14.16:
3184 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3185 * Gives slightly less than a 2x speedup when a == b,
3186 * via exploiting that each entry in the multiplication
3187 * pyramid appears twice (except for the size_a squares).
3188 */
3189 for (i = 0; i < size_a; ++i) {
3190 twodigits carry;
3191 twodigits f = a->ob_digit[i];
3192 digit *pz = z->ob_digit + (i << 1);
3193 digit *pa = a->ob_digit + i + 1;
3194 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003197 Py_DECREF(z);
3198 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003199 });
Tim Peters0973b992004-08-29 22:16:50 +00003200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 carry = *pz + f * f;
3202 *pz++ = (digit)(carry & PyLong_MASK);
3203 carry >>= PyLong_SHIFT;
3204 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 /* Now f is added in twice in each column of the
3207 * pyramid it appears. Same as adding f<<1 once.
3208 */
3209 f <<= 1;
3210 while (pa < paend) {
3211 carry += *pz + *pa++ * f;
3212 *pz++ = (digit)(carry & PyLong_MASK);
3213 carry >>= PyLong_SHIFT;
3214 assert(carry <= (PyLong_MASK << 1));
3215 }
3216 if (carry) {
3217 carry += *pz;
3218 *pz++ = (digit)(carry & PyLong_MASK);
3219 carry >>= PyLong_SHIFT;
3220 }
3221 if (carry)
3222 *pz += (digit)(carry & PyLong_MASK);
3223 assert((carry >> PyLong_SHIFT) == 0);
3224 }
3225 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003226 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 for (i = 0; i < size_a; ++i) {
3228 twodigits carry = 0;
3229 twodigits f = a->ob_digit[i];
3230 digit *pz = z->ob_digit + i;
3231 digit *pb = b->ob_digit;
3232 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003235 Py_DECREF(z);
3236 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003237 });
Tim Peters0973b992004-08-29 22:16:50 +00003238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 while (pb < pbend) {
3240 carry += *pz + *pb++ * f;
3241 *pz++ = (digit)(carry & PyLong_MASK);
3242 carry >>= PyLong_SHIFT;
3243 assert(carry <= PyLong_MASK);
3244 }
3245 if (carry)
3246 *pz += (digit)(carry & PyLong_MASK);
3247 assert((carry >> PyLong_SHIFT) == 0);
3248 }
3249 }
3250 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003251}
3252
3253/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003254 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003255 split, and sets low and high such that abs(n) == (high << size) + low,
3256 viewing the shift as being by digits. The sign bit is ignored, and
3257 the return values are >= 0.
3258 Returns 0 on success, -1 on failure.
3259*/
3260static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003261kmul_split(PyLongObject *n,
3262 Py_ssize_t size,
3263 PyLongObject **high,
3264 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 PyLongObject *hi, *lo;
3267 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003268 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003269
Victor Stinner640c35c2013-06-04 23:14:37 +02003270 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 if ((hi = _PyLong_New(size_hi)) == NULL)
3274 return -1;
3275 if ((lo = _PyLong_New(size_lo)) == NULL) {
3276 Py_DECREF(hi);
3277 return -1;
3278 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3281 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 *high = long_normalize(hi);
3284 *low = long_normalize(lo);
3285 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003286}
3287
Tim Peters60004642002-08-12 22:01:34 +00003288static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3289
Tim Peters5af4e6c2002-08-12 02:31:19 +00003290/* Karatsuba multiplication. Ignores the input signs, and returns the
3291 * absolute value of the product (or NULL if error).
3292 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3293 */
3294static PyLongObject *
3295k_mul(PyLongObject *a, PyLongObject *b)
3296{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003297 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3298 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 PyLongObject *ah = NULL;
3300 PyLongObject *al = NULL;
3301 PyLongObject *bh = NULL;
3302 PyLongObject *bl = NULL;
3303 PyLongObject *ret = NULL;
3304 PyLongObject *t1, *t2, *t3;
3305 Py_ssize_t shift; /* the number of digits we split off */
3306 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3309 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3310 * Then the original product is
3311 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3312 * By picking X to be a power of 2, "*X" is just shifting, and it's
3313 * been reduced to 3 multiplies on numbers half the size.
3314 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 /* We want to split based on the larger number; fiddle so that b
3317 * is largest.
3318 */
3319 if (asize > bsize) {
3320 t1 = a;
3321 a = b;
3322 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 i = asize;
3325 asize = bsize;
3326 bsize = i;
3327 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 /* Use gradeschool math when either number is too small. */
3330 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3331 if (asize <= i) {
3332 if (asize == 0)
3333 return (PyLongObject *)PyLong_FromLong(0);
3334 else
3335 return x_mul(a, b);
3336 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 /* If a is small compared to b, splitting on b gives a degenerate
3339 * case with ah==0, and Karatsuba may be (even much) less efficient
3340 * than "grade school" then. However, we can still win, by viewing
3341 * b as a string of "big digits", each of width a->ob_size. That
3342 * leads to a sequence of balanced calls to k_mul.
3343 */
3344 if (2 * asize <= bsize)
3345 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 /* Split a & b into hi & lo pieces. */
3348 shift = bsize >> 1;
3349 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3350 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 if (a == b) {
3353 bh = ah;
3354 bl = al;
3355 Py_INCREF(bh);
3356 Py_INCREF(bl);
3357 }
3358 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 /* The plan:
3361 * 1. Allocate result space (asize + bsize digits: that's always
3362 * enough).
3363 * 2. Compute ah*bh, and copy into result at 2*shift.
3364 * 3. Compute al*bl, and copy into result at 0. Note that this
3365 * can't overlap with #2.
3366 * 4. Subtract al*bl from the result, starting at shift. This may
3367 * underflow (borrow out of the high digit), but we don't care:
3368 * we're effectively doing unsigned arithmetic mod
3369 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3370 * borrows and carries out of the high digit can be ignored.
3371 * 5. Subtract ah*bh from the result, starting at shift.
3372 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3373 * at shift.
3374 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 /* 1. Allocate result space. */
3377 ret = _PyLong_New(asize + bsize);
3378 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003379#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 /* Fill with trash, to catch reference to uninitialized digits. */
3381 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003382#endif
Tim Peters44121a62002-08-12 06:17:58 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3385 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3386 assert(Py_SIZE(t1) >= 0);
3387 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3388 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3389 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 /* Zero-out the digits higher than the ah*bh copy. */
3392 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3393 if (i)
3394 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3395 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 /* 3. t2 <- al*bl, and copy into the low digits. */
3398 if ((t2 = k_mul(al, bl)) == NULL) {
3399 Py_DECREF(t1);
3400 goto fail;
3401 }
3402 assert(Py_SIZE(t2) >= 0);
3403 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3404 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 /* Zero out remaining digits. */
3407 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3408 if (i)
3409 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3412 * because it's fresher in cache.
3413 */
3414 i = Py_SIZE(ret) - shift; /* # digits after shift */
3415 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3416 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3419 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3422 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3423 Py_DECREF(ah);
3424 Py_DECREF(al);
3425 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 if (a == b) {
3428 t2 = t1;
3429 Py_INCREF(t2);
3430 }
3431 else if ((t2 = x_add(bh, bl)) == NULL) {
3432 Py_DECREF(t1);
3433 goto fail;
3434 }
3435 Py_DECREF(bh);
3436 Py_DECREF(bl);
3437 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 t3 = k_mul(t1, t2);
3440 Py_DECREF(t1);
3441 Py_DECREF(t2);
3442 if (t3 == NULL) goto fail;
3443 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 /* Add t3. It's not obvious why we can't run out of room here.
3446 * See the (*) comment after this function.
3447 */
3448 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3449 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003452
Mark Dickinson22b20182010-05-10 21:27:53 +00003453 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 Py_XDECREF(ret);
3455 Py_XDECREF(ah);
3456 Py_XDECREF(al);
3457 Py_XDECREF(bh);
3458 Py_XDECREF(bl);
3459 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003460}
3461
Tim Petersd6974a52002-08-13 20:37:51 +00003462/* (*) Why adding t3 can't "run out of room" above.
3463
Tim Petersab86c2b2002-08-15 20:06:00 +00003464Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3465to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003466
Tim Petersab86c2b2002-08-15 20:06:00 +000034671. For any integer i, i = c(i/2) + f(i/2). In particular,
3468 bsize = c(bsize/2) + f(bsize/2).
34692. shift = f(bsize/2)
34703. asize <= bsize
34714. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3472 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003473
Tim Petersab86c2b2002-08-15 20:06:00 +00003474We allocated asize + bsize result digits, and add t3 into them at an offset
3475of shift. This leaves asize+bsize-shift allocated digit positions for t3
3476to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3477asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003478
Tim Petersab86c2b2002-08-15 20:06:00 +00003479bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3480at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003481
Tim Petersab86c2b2002-08-15 20:06:00 +00003482If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3483digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3484most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003485
Tim Petersab86c2b2002-08-15 20:06:00 +00003486The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003487
Tim Petersab86c2b2002-08-15 20:06:00 +00003488 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003489
Tim Petersab86c2b2002-08-15 20:06:00 +00003490and we have asize + c(bsize/2) available digit positions. We need to show
3491this is always enough. An instance of c(bsize/2) cancels out in both, so
3492the question reduces to whether asize digits is enough to hold
3493(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3494then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3495asize 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 +00003496digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003497asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003498c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3499is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3500bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003501
Tim Peters48d52c02002-08-14 17:07:32 +00003502Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3503clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3504ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003505*/
3506
Tim Peters60004642002-08-12 22:01:34 +00003507/* b has at least twice the digits of a, and a is big enough that Karatsuba
3508 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3509 * of slices, each with a->ob_size digits, and multiply the slices by a,
3510 * one at a time. This gives k_mul balanced inputs to work with, and is
3511 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003512 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003513 * single-width slice overlap between successive partial sums).
3514 */
3515static PyLongObject *
3516k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3517{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003518 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3519 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 Py_ssize_t nbdone; /* # of b digits already multiplied */
3521 PyLongObject *ret;
3522 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 assert(asize > KARATSUBA_CUTOFF);
3525 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 /* Allocate result space, and zero it out. */
3528 ret = _PyLong_New(asize + bsize);
3529 if (ret == NULL)
3530 return NULL;
3531 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 /* Successive slices of b are copied into bslice. */
3534 bslice = _PyLong_New(asize);
3535 if (bslice == NULL)
3536 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 nbdone = 0;
3539 while (bsize > 0) {
3540 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003541 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 /* Multiply the next slice of b by a. */
3544 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3545 nbtouse * sizeof(digit));
3546 Py_SIZE(bslice) = nbtouse;
3547 product = k_mul(a, bslice);
3548 if (product == NULL)
3549 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 /* Add into result. */
3552 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3553 product->ob_digit, Py_SIZE(product));
3554 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 bsize -= nbtouse;
3557 nbdone += nbtouse;
3558 }
Tim Peters60004642002-08-12 22:01:34 +00003559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 Py_DECREF(bslice);
3561 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003562
Mark Dickinson22b20182010-05-10 21:27:53 +00003563 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 Py_DECREF(ret);
3565 Py_XDECREF(bslice);
3566 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003567}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003568
3569static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003570long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003577 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003579 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 z = k_mul(a, b);
3583 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003584 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3585 _PyLong_Negate(&z);
3586 if (z == NULL)
3587 return NULL;
3588 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003590}
3591
Yury Selivanove0b23092016-02-11 10:26:27 -05003592/* Fast modulo division for single-digit longs. */
3593static PyObject *
3594fast_mod(PyLongObject *a, PyLongObject *b)
3595{
3596 sdigit left = a->ob_digit[0];
3597 sdigit right = b->ob_digit[0];
3598 sdigit mod;
3599
3600 assert(Py_ABS(Py_SIZE(a)) == 1);
3601 assert(Py_ABS(Py_SIZE(b)) == 1);
3602
3603 if (Py_SIZE(a) == Py_SIZE(b)) {
3604 /* 'a' and 'b' have the same sign. */
3605 mod = left % right;
3606 }
3607 else {
3608 /* Either 'a' or 'b' is negative. */
3609 mod = right - 1 - (left - 1) % right;
3610 }
3611
Victor Stinnerf963c132016-03-23 18:36:54 +01003612 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003613}
3614
3615/* Fast floor division for single-digit longs. */
3616static PyObject *
3617fast_floor_div(PyLongObject *a, PyLongObject *b)
3618{
3619 sdigit left = a->ob_digit[0];
3620 sdigit right = b->ob_digit[0];
3621 sdigit div;
3622
3623 assert(Py_ABS(Py_SIZE(a)) == 1);
3624 assert(Py_ABS(Py_SIZE(b)) == 1);
3625
3626 if (Py_SIZE(a) == Py_SIZE(b)) {
3627 /* 'a' and 'b' have the same sign. */
3628 div = left / right;
3629 }
3630 else {
3631 /* Either 'a' or 'b' is negative. */
3632 div = -1 - (left - 1) / right;
3633 }
3634
3635 return PyLong_FromLong(div);
3636}
3637
Guido van Rossume32e0141992-01-19 16:31:05 +00003638/* The / and % operators are now defined in terms of divmod().
3639 The expression a mod b has the value a - b*floor(a/b).
3640 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003641 |a| by |b|, with the sign of a. This is also expressed
3642 as a - b*trunc(a/b), if trunc truncates towards zero.
3643 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 a b a rem b a mod b
3645 13 10 3 3
3646 -13 10 -3 7
3647 13 -10 3 -7
3648 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003649 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003650 have different signs. We then subtract one from the 'div'
3651 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003652
Tim Peters47e52ee2004-08-30 02:44:38 +00003653/* Compute
3654 * *pdiv, *pmod = divmod(v, w)
3655 * NULL can be passed for pdiv or pmod, in which case that part of
3656 * the result is simply thrown away. The caller owns a reference to
3657 * each of these it requests (does not pass NULL for).
3658 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003659static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003660l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003664
Yury Selivanove0b23092016-02-11 10:26:27 -05003665 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3666 /* Fast path for single-digit longs */
3667 div = NULL;
3668 if (pdiv != NULL) {
3669 div = (PyLongObject *)fast_floor_div(v, w);
3670 if (div == NULL) {
3671 return -1;
3672 }
3673 }
3674 if (pmod != NULL) {
3675 mod = (PyLongObject *)fast_mod(v, w);
3676 if (mod == NULL) {
3677 Py_XDECREF(div);
3678 return -1;
3679 }
3680 *pmod = mod;
3681 }
3682 if (pdiv != NULL) {
3683 /* We only want to set `*pdiv` when `*pmod` is
3684 set successfully. */
3685 *pdiv = div;
3686 }
3687 return 0;
3688 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 if (long_divrem(v, w, &div, &mod) < 0)
3690 return -1;
3691 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3692 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3693 PyLongObject *temp;
3694 PyLongObject *one;
3695 temp = (PyLongObject *) long_add(mod, w);
3696 Py_DECREF(mod);
3697 mod = temp;
3698 if (mod == NULL) {
3699 Py_DECREF(div);
3700 return -1;
3701 }
3702 one = (PyLongObject *) PyLong_FromLong(1L);
3703 if (one == NULL ||
3704 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3705 Py_DECREF(mod);
3706 Py_DECREF(div);
3707 Py_XDECREF(one);
3708 return -1;
3709 }
3710 Py_DECREF(one);
3711 Py_DECREF(div);
3712 div = temp;
3713 }
3714 if (pdiv != NULL)
3715 *pdiv = div;
3716 else
3717 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 if (pmod != NULL)
3720 *pmod = mod;
3721 else
3722 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003725}
3726
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003727static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003728long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003733
3734 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3735 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3736 }
3737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3739 div = NULL;
3740 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003741}
3742
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003743/* PyLong/PyLong -> float, with correctly rounded result. */
3744
3745#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3746#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3747
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003748static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003749long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 PyLongObject *a, *b, *x;
3752 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3753 digit mask, low;
3754 int inexact, negate, a_is_small, b_is_small;
3755 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 CHECK_BINOP(v, w);
3758 a = (PyLongObject *)v;
3759 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 /*
3762 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3765 1. choose a suitable integer 'shift'
3766 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3767 3. adjust x for correct rounding
3768 4. convert x to a double dx with the same value
3769 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3774 returns either 0.0 or -0.0, depending on the sign of b. For a and
3775 b both nonzero, ignore signs of a and b, and add the sign back in
3776 at the end. Now write a_bits and b_bits for the bit lengths of a
3777 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3778 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3783 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3784 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3785 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 1. The integer 'shift' is chosen so that x has the right number of
3790 bits for a double, plus two or three extra bits that will be used
3791 in the rounding decisions. Writing a_bits and b_bits for the
3792 number of significant bits in a and b respectively, a
3793 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 This is fine in the usual case, but if a/b is smaller than the
3798 smallest normal float then it can lead to double rounding on an
3799 IEEE 754 platform, giving incorrectly rounded results. So we
3800 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 2. The quantity x is computed by first shifting a (left -shift bits
3805 if shift <= 0, right shift bits if shift > 0) and then dividing by
3806 b. For both the shift and the division, we keep track of whether
3807 the result is inexact, in a flag 'inexact'; this information is
3808 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 With the choice of shift above, together with our assumption that
3811 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3812 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3815 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 For float representability, we need x/2**extra_bits <
3820 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3821 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 To round, we just modify the bottom digit of x in-place; this can
3826 end up giving a digit with value > PyLONG_MASK, but that's not a
3827 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 With the original choices for shift above, extra_bits will always
3830 be 2 or 3. Then rounding under the round-half-to-even rule, we
3831 round up iff the most significant of the extra bits is 1, and
3832 either: (a) the computation of x in step 2 had an inexact result,
3833 or (b) at least one other of the extra bits is 1, or (c) the least
3834 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 4. Conversion to a double is straightforward; all floating-point
3837 operations involved in the conversion are exact, so there's no
3838 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3841 The result will always be exactly representable as a double, except
3842 in the case that it overflows. To avoid dependence on the exact
3843 behaviour of ldexp on overflow, we check for overflow before
3844 applying ldexp. The result of ldexp is adjusted for sign before
3845 returning.
3846 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003849 a_size = Py_ABS(Py_SIZE(a));
3850 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3852 if (b_size == 0) {
3853 PyErr_SetString(PyExc_ZeroDivisionError,
3854 "division by zero");
3855 goto error;
3856 }
3857 if (a_size == 0)
3858 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 /* Fast path for a and b small (exactly representable in a double).
3861 Relies on floating-point division being correctly rounded; results
3862 may be subject to double rounding on x86 machines that operate with
3863 the x87 FPU set to 64-bit precision. */
3864 a_is_small = a_size <= MANT_DIG_DIGITS ||
3865 (a_size == MANT_DIG_DIGITS+1 &&
3866 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3867 b_is_small = b_size <= MANT_DIG_DIGITS ||
3868 (b_size == MANT_DIG_DIGITS+1 &&
3869 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3870 if (a_is_small && b_is_small) {
3871 double da, db;
3872 da = a->ob_digit[--a_size];
3873 while (a_size > 0)
3874 da = da * PyLong_BASE + a->ob_digit[--a_size];
3875 db = b->ob_digit[--b_size];
3876 while (b_size > 0)
3877 db = db * PyLong_BASE + b->ob_digit[--b_size];
3878 result = da / db;
3879 goto success;
3880 }
Tim Peterse2a60002001-09-04 06:17:36 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 /* Catch obvious cases of underflow and overflow */
3883 diff = a_size - b_size;
3884 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3885 /* Extreme overflow */
3886 goto overflow;
3887 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3888 /* Extreme underflow */
3889 goto underflow_or_zero;
3890 /* Next line is now safe from overflowing a Py_ssize_t */
3891 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3892 bits_in_digit(b->ob_digit[b_size - 1]);
3893 /* Now diff = a_bits - b_bits. */
3894 if (diff > DBL_MAX_EXP)
3895 goto overflow;
3896 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3897 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003900 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 /* x = abs(a * 2**-shift) */
3905 if (shift <= 0) {
3906 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3907 digit rem;
3908 /* x = a << -shift */
3909 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3910 /* In practice, it's probably impossible to end up
3911 here. Both a and b would have to be enormous,
3912 using close to SIZE_T_MAX bytes of memory each. */
3913 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003914 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 goto error;
3916 }
3917 x = _PyLong_New(a_size + shift_digits + 1);
3918 if (x == NULL)
3919 goto error;
3920 for (i = 0; i < shift_digits; i++)
3921 x->ob_digit[i] = 0;
3922 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3923 a_size, -shift % PyLong_SHIFT);
3924 x->ob_digit[a_size + shift_digits] = rem;
3925 }
3926 else {
3927 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3928 digit rem;
3929 /* x = a >> shift */
3930 assert(a_size >= shift_digits);
3931 x = _PyLong_New(a_size - shift_digits);
3932 if (x == NULL)
3933 goto error;
3934 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3935 a_size - shift_digits, shift % PyLong_SHIFT);
3936 /* set inexact if any of the bits shifted out is nonzero */
3937 if (rem)
3938 inexact = 1;
3939 while (!inexact && shift_digits > 0)
3940 if (a->ob_digit[--shift_digits])
3941 inexact = 1;
3942 }
3943 long_normalize(x);
3944 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3947 reference to x, so it's safe to modify it in-place. */
3948 if (b_size == 1) {
3949 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3950 b->ob_digit[0]);
3951 long_normalize(x);
3952 if (rem)
3953 inexact = 1;
3954 }
3955 else {
3956 PyLongObject *div, *rem;
3957 div = x_divrem(x, b, &rem);
3958 Py_DECREF(x);
3959 x = div;
3960 if (x == NULL)
3961 goto error;
3962 if (Py_SIZE(rem))
3963 inexact = 1;
3964 Py_DECREF(rem);
3965 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003966 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 assert(x_size > 0); /* result of division is never zero */
3968 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003971 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 /* Round by directly modifying the low digit of x. */
3975 mask = (digit)1 << (extra_bits - 1);
3976 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003977 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003979 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 /* Convert x to a double dx; the conversion is exact. */
3982 dx = x->ob_digit[--x_size];
3983 while (x_size > 0)
3984 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3985 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 /* Check whether ldexp result will overflow a double. */
3988 if (shift + x_bits >= DBL_MAX_EXP &&
3989 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3990 goto overflow;
3991 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003992
3993 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003995
3996 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003998
3999 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 PyErr_SetString(PyExc_OverflowError,
4001 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004002 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004004}
4005
4006static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004007long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 CHECK_BINOP(a, b);
4012
Yury Selivanove0b23092016-02-11 10:26:27 -05004013 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4014 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4015 }
4016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4018 mod = NULL;
4019 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004020}
4021
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004022static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004023long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 PyLongObject *div, *mod;
4026 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4031 return NULL;
4032 }
4033 z = PyTuple_New(2);
4034 if (z != NULL) {
4035 PyTuple_SetItem(z, 0, (PyObject *) div);
4036 PyTuple_SetItem(z, 1, (PyObject *) mod);
4037 }
4038 else {
4039 Py_DECREF(div);
4040 Py_DECREF(mod);
4041 }
4042 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004043}
4044
Tim Peters47e52ee2004-08-30 02:44:38 +00004045/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004046static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004047long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4050 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 PyLongObject *z = NULL; /* accumulated result */
4053 Py_ssize_t i, j, k; /* counters */
4054 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 /* 5-ary values. If the exponent is large enough, table is
4057 * precomputed so that table[i] == a**i % c for i in range(32).
4058 */
4059 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4060 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 /* a, b, c = v, w, x */
4063 CHECK_BINOP(v, w);
4064 a = (PyLongObject*)v; Py_INCREF(a);
4065 b = (PyLongObject*)w; Py_INCREF(b);
4066 if (PyLong_Check(x)) {
4067 c = (PyLongObject *)x;
4068 Py_INCREF(x);
4069 }
4070 else if (x == Py_None)
4071 c = NULL;
4072 else {
4073 Py_DECREF(a);
4074 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004075 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 }
Tim Peters4c483c42001-09-05 06:24:58 +00004077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 if (Py_SIZE(b) < 0) { /* if exponent is negative */
4079 if (c) {
Mark Dickinson0c346d82014-04-11 14:34:40 -04004080 PyErr_SetString(PyExc_ValueError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00004081 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 goto Error;
4083 }
4084 else {
4085 /* else return a float. This works because we know
4086 that this calls float_pow() which converts its
4087 arguments to double. */
4088 Py_DECREF(a);
4089 Py_DECREF(b);
4090 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
4091 }
4092 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 if (c) {
4095 /* if modulus == 0:
4096 raise ValueError() */
4097 if (Py_SIZE(c) == 0) {
4098 PyErr_SetString(PyExc_ValueError,
4099 "pow() 3rd argument cannot be 0");
4100 goto Error;
4101 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 /* if modulus < 0:
4104 negativeOutput = True
4105 modulus = -modulus */
4106 if (Py_SIZE(c) < 0) {
4107 negativeOutput = 1;
4108 temp = (PyLongObject *)_PyLong_Copy(c);
4109 if (temp == NULL)
4110 goto Error;
4111 Py_DECREF(c);
4112 c = temp;
4113 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004114 _PyLong_Negate(&c);
4115 if (c == NULL)
4116 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 /* if modulus == 1:
4120 return 0 */
4121 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4122 z = (PyLongObject *)PyLong_FromLong(0L);
4123 goto Done;
4124 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004125
Tim Peters81a93152013-10-05 16:53:52 -05004126 /* Reduce base by modulus in some cases:
4127 1. If base < 0. Forcing the base non-negative makes things easier.
4128 2. If base is obviously larger than the modulus. The "small
4129 exponent" case later can multiply directly by base repeatedly,
4130 while the "large exponent" case multiplies directly by base 31
4131 times. It can be unboundedly faster to multiply by
4132 base % modulus instead.
4133 We could _always_ do this reduction, but l_divmod() isn't cheap,
4134 so we only do it when it buys something. */
4135 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 if (l_divmod(a, c, NULL, &temp) < 0)
4137 goto Error;
4138 Py_DECREF(a);
4139 a = temp;
4140 temp = NULL;
4141 }
4142 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 /* At this point a, b, and c are guaranteed non-negative UNLESS
4145 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 z = (PyLongObject *)PyLong_FromLong(1L);
4148 if (z == NULL)
4149 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 /* Perform a modular reduction, X = X % c, but leave X alone if c
4152 * is NULL.
4153 */
4154#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004155 do { \
4156 if (c != NULL) { \
4157 if (l_divmod(X, c, NULL, &temp) < 0) \
4158 goto Error; \
4159 Py_XDECREF(X); \
4160 X = temp; \
4161 temp = NULL; \
4162 } \
4163 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 /* Multiply two values, then reduce the result:
4166 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004167#define MULT(X, Y, result) \
4168 do { \
4169 temp = (PyLongObject *)long_mul(X, Y); \
4170 if (temp == NULL) \
4171 goto Error; \
4172 Py_XDECREF(result); \
4173 result = temp; \
4174 temp = NULL; \
4175 REDUCE(result); \
4176 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4179 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4180 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4181 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4182 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004185 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004187 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 }
4189 }
4190 }
4191 else {
4192 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4193 Py_INCREF(z); /* still holds 1L */
4194 table[0] = z;
4195 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004196 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4199 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4202 const int index = (bi >> j) & 0x1f;
4203 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004204 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004206 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 }
4208 }
4209 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 if (negativeOutput && (Py_SIZE(z) != 0)) {
4212 temp = (PyLongObject *)long_sub(z, c);
4213 if (temp == NULL)
4214 goto Error;
4215 Py_DECREF(z);
4216 z = temp;
4217 temp = NULL;
4218 }
4219 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004220
Mark Dickinson22b20182010-05-10 21:27:53 +00004221 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004222 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004224 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4226 for (i = 0; i < 32; ++i)
4227 Py_XDECREF(table[i]);
4228 }
4229 Py_DECREF(a);
4230 Py_DECREF(b);
4231 Py_XDECREF(c);
4232 Py_XDECREF(temp);
4233 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004234}
4235
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004236static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004237long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 /* Implement ~x as -(x+1) */
4240 PyLongObject *x;
4241 PyLongObject *w;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004242 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
4244 w = (PyLongObject *)PyLong_FromLong(1L);
4245 if (w == NULL)
4246 return NULL;
4247 x = (PyLongObject *) long_add(v, w);
4248 Py_DECREF(w);
4249 if (x == NULL)
4250 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004251 _PyLong_Negate(&x);
4252 /* No need for maybe_small_long here, since any small
4253 longs will have been caught in the Py_SIZE <= 1 fast path. */
4254 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004255}
4256
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004257static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004258long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004261 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 return PyLong_FromLong(-MEDIUM_VALUE(v));
4263 z = (PyLongObject *)_PyLong_Copy(v);
4264 if (z != NULL)
4265 Py_SIZE(z) = -(Py_SIZE(v));
4266 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004267}
4268
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004269static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004270long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 if (Py_SIZE(v) < 0)
4273 return long_neg(v);
4274 else
4275 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004276}
4277
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004278static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004279long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004282}
4283
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004284static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004285long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 PyLongObject *z = NULL;
4288 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4289 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004291 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 if (Py_SIZE(a) < 0) {
4294 /* Right shifting negative numbers is harder */
4295 PyLongObject *a1, *a2;
4296 a1 = (PyLongObject *) long_invert(a);
4297 if (a1 == NULL)
4298 goto rshift_error;
4299 a2 = (PyLongObject *) long_rshift(a1, b);
4300 Py_DECREF(a1);
4301 if (a2 == NULL)
4302 goto rshift_error;
4303 z = (PyLongObject *) long_invert(a2);
4304 Py_DECREF(a2);
4305 }
4306 else {
4307 shiftby = PyLong_AsSsize_t((PyObject *)b);
4308 if (shiftby == -1L && PyErr_Occurred())
4309 goto rshift_error;
4310 if (shiftby < 0) {
4311 PyErr_SetString(PyExc_ValueError,
4312 "negative shift count");
4313 goto rshift_error;
4314 }
4315 wordshift = shiftby / PyLong_SHIFT;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004316 newsize = Py_ABS(Py_SIZE(a)) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 if (newsize <= 0)
4318 return PyLong_FromLong(0);
4319 loshift = shiftby % PyLong_SHIFT;
4320 hishift = PyLong_SHIFT - loshift;
4321 lomask = ((digit)1 << hishift) - 1;
4322 himask = PyLong_MASK ^ lomask;
4323 z = _PyLong_New(newsize);
4324 if (z == NULL)
4325 goto rshift_error;
4326 if (Py_SIZE(a) < 0)
4327 Py_SIZE(z) = -(Py_SIZE(z));
4328 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4329 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4330 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004331 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 }
4333 z = long_normalize(z);
4334 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004335 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004337
Guido van Rossumc6913e71991-11-19 20:26:46 +00004338}
4339
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004340static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004341long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 /* This version due to Tim Peters */
4344 PyLongObject *a = (PyLongObject*)v;
4345 PyLongObject *b = (PyLongObject*)w;
4346 PyLongObject *z = NULL;
4347 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4348 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 shiftby = PyLong_AsSsize_t((PyObject *)b);
4353 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004354 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 if (shiftby < 0) {
4356 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004357 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004359
4360 if (Py_SIZE(a) == 0) {
4361 return PyLong_FromLong(0);
4362 }
4363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4365 wordshift = shiftby / PyLong_SHIFT;
4366 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004367
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004368 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 newsize = oldsize + wordshift;
4370 if (remshift)
4371 ++newsize;
4372 z = _PyLong_New(newsize);
4373 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004374 return NULL;
4375 if (Py_SIZE(a) < 0) {
4376 assert(Py_REFCNT(z) == 1);
4377 Py_SIZE(z) = -Py_SIZE(z);
4378 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 for (i = 0; i < wordshift; i++)
4380 z->ob_digit[i] = 0;
4381 accum = 0;
4382 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4383 accum |= (twodigits)a->ob_digit[j] << remshift;
4384 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4385 accum >>= PyLong_SHIFT;
4386 }
4387 if (remshift)
4388 z->ob_digit[newsize-1] = (digit)accum;
4389 else
4390 assert(!accum);
4391 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004393}
4394
Mark Dickinson27a87a22009-10-25 20:43:34 +00004395/* Compute two's complement of digit vector a[0:m], writing result to
4396 z[0:m]. The digit vector a need not be normalized, but should not
4397 be entirely zero. a and z may point to the same digit vector. */
4398
4399static void
4400v_complement(digit *z, digit *a, Py_ssize_t m)
4401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 Py_ssize_t i;
4403 digit carry = 1;
4404 for (i = 0; i < m; ++i) {
4405 carry += a[i] ^ PyLong_MASK;
4406 z[i] = carry & PyLong_MASK;
4407 carry >>= PyLong_SHIFT;
4408 }
4409 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004410}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004411
4412/* Bitwise and/xor/or operations */
4413
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004414static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004415long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004416 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004417 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 int nega, negb, negz;
4420 Py_ssize_t size_a, size_b, size_z, i;
4421 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 /* Bitwise operations for negative numbers operate as though
4424 on a two's complement representation. So convert arguments
4425 from sign-magnitude to two's complement, and convert the
4426 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004429 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 nega = Py_SIZE(a) < 0;
4431 if (nega) {
4432 z = _PyLong_New(size_a);
4433 if (z == NULL)
4434 return NULL;
4435 v_complement(z->ob_digit, a->ob_digit, size_a);
4436 a = z;
4437 }
4438 else
4439 /* Keep reference count consistent. */
4440 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004443 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 negb = Py_SIZE(b) < 0;
4445 if (negb) {
4446 z = _PyLong_New(size_b);
4447 if (z == NULL) {
4448 Py_DECREF(a);
4449 return NULL;
4450 }
4451 v_complement(z->ob_digit, b->ob_digit, size_b);
4452 b = z;
4453 }
4454 else
4455 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 /* Swap a and b if necessary to ensure size_a >= size_b. */
4458 if (size_a < size_b) {
4459 z = a; a = b; b = z;
4460 size_z = size_a; size_a = size_b; size_b = size_z;
4461 negz = nega; nega = negb; negb = negz;
4462 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 /* JRH: The original logic here was to allocate the result value (z)
4465 as the longer of the two operands. However, there are some cases
4466 where the result is guaranteed to be shorter than that: AND of two
4467 positives, OR of two negatives: use the shorter number. AND with
4468 mixed signs: use the positive number. OR with mixed signs: use the
4469 negative number.
4470 */
4471 switch (op) {
4472 case '^':
4473 negz = nega ^ negb;
4474 size_z = size_a;
4475 break;
4476 case '&':
4477 negz = nega & negb;
4478 size_z = negb ? size_a : size_b;
4479 break;
4480 case '|':
4481 negz = nega | negb;
4482 size_z = negb ? size_b : size_a;
4483 break;
4484 default:
4485 PyErr_BadArgument();
4486 return NULL;
4487 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 /* We allow an extra digit if z is negative, to make sure that
4490 the final two's complement of z doesn't overflow. */
4491 z = _PyLong_New(size_z + negz);
4492 if (z == NULL) {
4493 Py_DECREF(a);
4494 Py_DECREF(b);
4495 return NULL;
4496 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 /* Compute digits for overlap of a and b. */
4499 switch(op) {
4500 case '&':
4501 for (i = 0; i < size_b; ++i)
4502 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4503 break;
4504 case '|':
4505 for (i = 0; i < size_b; ++i)
4506 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4507 break;
4508 case '^':
4509 for (i = 0; i < size_b; ++i)
4510 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4511 break;
4512 default:
4513 PyErr_BadArgument();
4514 return NULL;
4515 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 /* Copy any remaining digits of a, inverting if necessary. */
4518 if (op == '^' && negb)
4519 for (; i < size_z; ++i)
4520 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4521 else if (i < size_z)
4522 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4523 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 /* Complement result if negative. */
4526 if (negz) {
4527 Py_SIZE(z) = -(Py_SIZE(z));
4528 z->ob_digit[size_z] = PyLong_MASK;
4529 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4530 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 Py_DECREF(a);
4533 Py_DECREF(b);
4534 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004535}
4536
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004537static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004538long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 PyObject *c;
4541 CHECK_BINOP(a, b);
4542 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4543 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004544}
4545
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004546static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004547long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 PyObject *c;
4550 CHECK_BINOP(a, b);
4551 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4552 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004553}
4554
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004555static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004556long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 PyObject *c;
4559 CHECK_BINOP(a, b);
4560 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4561 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004562}
4563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004564static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004565long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 if (PyLong_CheckExact(v))
4568 Py_INCREF(v);
4569 else
4570 v = _PyLong_Copy((PyLongObject *)v);
4571 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004572}
4573
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004574PyObject *
4575_PyLong_GCD(PyObject *aarg, PyObject *barg)
4576{
4577 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4578 stwodigits x, y, q, s, t, c_carry, d_carry;
4579 stwodigits A, B, C, D, T;
4580 int nbits, k;
4581 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4582 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4583
4584 a = (PyLongObject *)aarg;
4585 b = (PyLongObject *)barg;
4586 size_a = Py_SIZE(a);
4587 size_b = Py_SIZE(b);
4588 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4589 Py_INCREF(a);
4590 Py_INCREF(b);
4591 goto simple;
4592 }
4593
4594 /* Initial reduction: make sure that 0 <= b <= a. */
4595 a = (PyLongObject *)long_abs(a);
4596 if (a == NULL)
4597 return NULL;
4598 b = (PyLongObject *)long_abs(b);
4599 if (b == NULL) {
4600 Py_DECREF(a);
4601 return NULL;
4602 }
4603 if (long_compare(a, b) < 0) {
4604 r = a;
4605 a = b;
4606 b = r;
4607 }
4608 /* We now own references to a and b */
4609
4610 alloc_a = Py_SIZE(a);
4611 alloc_b = Py_SIZE(b);
4612 /* reduce until a fits into 2 digits */
4613 while ((size_a = Py_SIZE(a)) > 2) {
4614 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4615 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4616 corresponding bits of b into y */
4617 size_b = Py_SIZE(b);
4618 assert(size_b <= size_a);
4619 if (size_b == 0) {
4620 if (size_a < alloc_a) {
4621 r = (PyLongObject *)_PyLong_Copy(a);
4622 Py_DECREF(a);
4623 }
4624 else
4625 r = a;
4626 Py_DECREF(b);
4627 Py_XDECREF(c);
4628 Py_XDECREF(d);
4629 return (PyObject *)r;
4630 }
4631 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4632 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4633 (a->ob_digit[size_a-3] >> nbits));
4634
4635 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4636 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4637 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4638
4639 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4640 larger than PyLong_MASK during the algorithm. */
4641 A = 1; B = 0; C = 0; D = 1;
4642 for (k=0;; k++) {
4643 if (y-C == 0)
4644 break;
4645 q = (x+(A-1))/(y-C);
4646 s = B+q*D;
4647 t = x-q*y;
4648 if (s > t)
4649 break;
4650 x = y; y = t;
4651 t = A+q*C; A = D; B = C; C = s; D = t;
4652 }
4653
4654 if (k == 0) {
4655 /* no progress; do a Euclidean step */
4656 if (l_divmod(a, b, NULL, &r) < 0)
4657 goto error;
4658 Py_DECREF(a);
4659 a = b;
4660 b = r;
4661 alloc_a = alloc_b;
4662 alloc_b = Py_SIZE(b);
4663 continue;
4664 }
4665
4666 /*
4667 a, b = A*b-B*a, D*a-C*b if k is odd
4668 a, b = A*a-B*b, D*b-C*a if k is even
4669 */
4670 if (k&1) {
4671 T = -A; A = -B; B = T;
4672 T = -C; C = -D; D = T;
4673 }
4674 if (c != NULL)
4675 Py_SIZE(c) = size_a;
4676 else if (Py_REFCNT(a) == 1) {
4677 Py_INCREF(a);
4678 c = a;
4679 }
4680 else {
4681 alloc_a = size_a;
4682 c = _PyLong_New(size_a);
4683 if (c == NULL)
4684 goto error;
4685 }
4686
4687 if (d != NULL)
4688 Py_SIZE(d) = size_a;
4689 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4690 Py_INCREF(b);
4691 d = b;
4692 Py_SIZE(d) = size_a;
4693 }
4694 else {
4695 alloc_b = size_a;
4696 d = _PyLong_New(size_a);
4697 if (d == NULL)
4698 goto error;
4699 }
4700 a_end = a->ob_digit + size_a;
4701 b_end = b->ob_digit + size_b;
4702
4703 /* compute new a and new b in parallel */
4704 a_digit = a->ob_digit;
4705 b_digit = b->ob_digit;
4706 c_digit = c->ob_digit;
4707 d_digit = d->ob_digit;
4708 c_carry = 0;
4709 d_carry = 0;
4710 while (b_digit < b_end) {
4711 c_carry += (A * *a_digit) - (B * *b_digit);
4712 d_carry += (D * *b_digit++) - (C * *a_digit++);
4713 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4714 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4715 c_carry >>= PyLong_SHIFT;
4716 d_carry >>= PyLong_SHIFT;
4717 }
4718 while (a_digit < a_end) {
4719 c_carry += A * *a_digit;
4720 d_carry -= C * *a_digit++;
4721 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4722 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4723 c_carry >>= PyLong_SHIFT;
4724 d_carry >>= PyLong_SHIFT;
4725 }
4726 assert(c_carry == 0);
4727 assert(d_carry == 0);
4728
4729 Py_INCREF(c);
4730 Py_INCREF(d);
4731 Py_DECREF(a);
4732 Py_DECREF(b);
4733 a = long_normalize(c);
4734 b = long_normalize(d);
4735 }
4736 Py_XDECREF(c);
4737 Py_XDECREF(d);
4738
4739simple:
4740 assert(Py_REFCNT(a) > 0);
4741 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004742/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4743 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4744#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004745 /* a fits into a long, so b must too */
4746 x = PyLong_AsLong((PyObject *)a);
4747 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004748#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004749 x = PyLong_AsLongLong((PyObject *)a);
4750 y = PyLong_AsLongLong((PyObject *)b);
4751#else
4752# error "_PyLong_GCD"
4753#endif
4754 x = Py_ABS(x);
4755 y = Py_ABS(y);
4756 Py_DECREF(a);
4757 Py_DECREF(b);
4758
4759 /* usual Euclidean algorithm for longs */
4760 while (y != 0) {
4761 t = y;
4762 y = x % y;
4763 x = t;
4764 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004765#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004766 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004767#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004768 return PyLong_FromLongLong(x);
4769#else
4770# error "_PyLong_GCD"
4771#endif
4772
4773error:
4774 Py_DECREF(a);
4775 Py_DECREF(b);
4776 Py_XDECREF(c);
4777 Py_XDECREF(d);
4778 return NULL;
4779}
4780
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004781static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004782long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784 double result;
4785 result = PyLong_AsDouble(v);
4786 if (result == -1.0 && PyErr_Occurred())
4787 return NULL;
4788 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004789}
4790
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004791static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004792long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004793
Tim Peters6d6c1a32001-08-02 04:15:00 +00004794static PyObject *
4795long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4796{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004797 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004798 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 if (type != &PyLong_Type)
4802 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004803 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4804 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004806 if (x == NULL) {
4807 if (obase != NULL) {
4808 PyErr_SetString(PyExc_TypeError,
4809 "int() missing string argument");
4810 return NULL;
4811 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004813 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004814 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004816
Gregory P. Smitha689e522012-12-25 22:38:32 -08004817 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004818 if (base == -1 && PyErr_Occurred())
4819 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004820 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004821 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004822 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004823 return NULL;
4824 }
4825
4826 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004827 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004828 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 if (PyByteArray_Check(x))
4831 string = PyByteArray_AS_STRING(x);
4832 else
4833 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004834 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 }
4836 else {
4837 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004838 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 return NULL;
4840 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004841}
4842
Serhiy Storchaka95949422013-08-27 19:40:23 +03004843/* Wimpy, slow approach to tp_new calls for subtypes of int:
4844 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004845 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004846 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004847*/
4848static PyObject *
4849long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 PyLongObject *tmp, *newobj;
4852 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 assert(PyType_IsSubtype(type, &PyLong_Type));
4855 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4856 if (tmp == NULL)
4857 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004858 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 n = Py_SIZE(tmp);
4860 if (n < 0)
4861 n = -n;
4862 newobj = (PyLongObject *)type->tp_alloc(type, n);
4863 if (newobj == NULL) {
4864 Py_DECREF(tmp);
4865 return NULL;
4866 }
4867 assert(PyLong_Check(newobj));
4868 Py_SIZE(newobj) = Py_SIZE(tmp);
4869 for (i = 0; i < n; i++)
4870 newobj->ob_digit[i] = tmp->ob_digit[i];
4871 Py_DECREF(tmp);
4872 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004873}
4874
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004875static PyObject *
4876long_getnewargs(PyLongObject *v)
4877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004879}
4880
Guido van Rossumb43daf72007-08-01 18:08:08 +00004881static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004882long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004883 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004884}
4885
4886static PyObject *
4887long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004889}
4890
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004891static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004892long__format__(PyObject *self, PyObject *args)
4893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004894 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004895 _PyUnicodeWriter writer;
4896 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4899 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004900
Victor Stinner8f674cc2013-04-17 23:02:17 +02004901 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004902 ret = _PyLong_FormatAdvancedWriter(
4903 &writer,
4904 self,
4905 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4906 if (ret == -1) {
4907 _PyUnicodeWriter_Dealloc(&writer);
4908 return NULL;
4909 }
4910 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004911}
4912
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004913/* Return a pair (q, r) such that a = b * q + r, and
4914 abs(r) <= abs(b)/2, with equality possible only if q is even.
4915 In other words, q == a / b, rounded to the nearest integer using
4916 round-half-to-even. */
4917
4918PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004919_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004920{
4921 PyLongObject *quo = NULL, *rem = NULL;
4922 PyObject *one = NULL, *twice_rem, *result, *temp;
4923 int cmp, quo_is_odd, quo_is_neg;
4924
4925 /* Equivalent Python code:
4926
4927 def divmod_near(a, b):
4928 q, r = divmod(a, b)
4929 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4930 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4931 # positive, 2 * r < b if b negative.
4932 greater_than_half = 2*r > b if b > 0 else 2*r < b
4933 exactly_half = 2*r == b
4934 if greater_than_half or exactly_half and q % 2 == 1:
4935 q += 1
4936 r -= b
4937 return q, r
4938
4939 */
4940 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4941 PyErr_SetString(PyExc_TypeError,
4942 "non-integer arguments in division");
4943 return NULL;
4944 }
4945
4946 /* Do a and b have different signs? If so, quotient is negative. */
4947 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4948
4949 one = PyLong_FromLong(1L);
4950 if (one == NULL)
4951 return NULL;
4952
4953 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4954 goto error;
4955
4956 /* compare twice the remainder with the divisor, to see
4957 if we need to adjust the quotient and remainder */
4958 twice_rem = long_lshift((PyObject *)rem, one);
4959 if (twice_rem == NULL)
4960 goto error;
4961 if (quo_is_neg) {
4962 temp = long_neg((PyLongObject*)twice_rem);
4963 Py_DECREF(twice_rem);
4964 twice_rem = temp;
4965 if (twice_rem == NULL)
4966 goto error;
4967 }
4968 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4969 Py_DECREF(twice_rem);
4970
4971 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4972 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4973 /* fix up quotient */
4974 if (quo_is_neg)
4975 temp = long_sub(quo, (PyLongObject *)one);
4976 else
4977 temp = long_add(quo, (PyLongObject *)one);
4978 Py_DECREF(quo);
4979 quo = (PyLongObject *)temp;
4980 if (quo == NULL)
4981 goto error;
4982 /* and remainder */
4983 if (quo_is_neg)
4984 temp = long_add(rem, (PyLongObject *)b);
4985 else
4986 temp = long_sub(rem, (PyLongObject *)b);
4987 Py_DECREF(rem);
4988 rem = (PyLongObject *)temp;
4989 if (rem == NULL)
4990 goto error;
4991 }
4992
4993 result = PyTuple_New(2);
4994 if (result == NULL)
4995 goto error;
4996
4997 /* PyTuple_SET_ITEM steals references */
4998 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4999 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
5000 Py_DECREF(one);
5001 return result;
5002
5003 error:
5004 Py_XDECREF(quo);
5005 Py_XDECREF(rem);
5006 Py_XDECREF(one);
5007 return NULL;
5008}
5009
Eric Smith8c663262007-08-25 02:26:07 +00005010static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005011long_round(PyObject *self, PyObject *args)
5012{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005013 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005014
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005015 /* To round an integer m to the nearest 10**n (n positive), we make use of
5016 * the divmod_near operation, defined by:
5017 *
5018 * divmod_near(a, b) = (q, r)
5019 *
5020 * where q is the nearest integer to the quotient a / b (the
5021 * nearest even integer in the case of a tie) and r == a - q * b.
5022 * Hence q * b = a - r is the nearest multiple of b to a,
5023 * preferring even multiples in the case of a tie.
5024 *
5025 * So the nearest multiple of 10**n to m is:
5026 *
5027 * m - divmod_near(m, 10**n)[1].
5028 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5030 return NULL;
5031 if (o_ndigits == NULL)
5032 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005033
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005034 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005035 if (ndigits == NULL)
5036 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005037
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005038 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 if (Py_SIZE(ndigits) >= 0) {
5040 Py_DECREF(ndigits);
5041 return long_long(self);
5042 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005043
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005044 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5045 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005047 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005049 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005050
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005051 result = PyLong_FromLong(10L);
5052 if (result == NULL) {
5053 Py_DECREF(ndigits);
5054 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005056
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005057 temp = long_pow(result, ndigits, Py_None);
5058 Py_DECREF(ndigits);
5059 Py_DECREF(result);
5060 result = temp;
5061 if (result == NULL)
5062 return NULL;
5063
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005064 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005065 Py_DECREF(result);
5066 result = temp;
5067 if (result == NULL)
5068 return NULL;
5069
5070 temp = long_sub((PyLongObject *)self,
5071 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5072 Py_DECREF(result);
5073 result = temp;
5074
5075 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005076}
5077
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005078static PyObject *
5079long_sizeof(PyLongObject *v)
5080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005081 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005082
Victor Stinner45e8e2f2014-05-14 17:24:35 +02005083 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(v))*sizeof(digit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005085}
5086
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005087static PyObject *
5088long_bit_length(PyLongObject *v)
5089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005090 PyLongObject *result, *x, *y;
5091 Py_ssize_t ndigits, msd_bits = 0;
5092 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 assert(v != NULL);
5095 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005096
Victor Stinner45e8e2f2014-05-14 17:24:35 +02005097 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 if (ndigits == 0)
5099 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 msd = v->ob_digit[ndigits-1];
5102 while (msd >= 32) {
5103 msd_bits += 6;
5104 msd >>= 6;
5105 }
5106 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5109 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 /* expression above may overflow; use Python integers instead */
5112 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5113 if (result == NULL)
5114 return NULL;
5115 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5116 if (x == NULL)
5117 goto error;
5118 y = (PyLongObject *)long_mul(result, x);
5119 Py_DECREF(x);
5120 if (y == NULL)
5121 goto error;
5122 Py_DECREF(result);
5123 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5126 if (x == NULL)
5127 goto error;
5128 y = (PyLongObject *)long_add(result, x);
5129 Py_DECREF(x);
5130 if (y == NULL)
5131 goto error;
5132 Py_DECREF(result);
5133 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005136
Mark Dickinson22b20182010-05-10 21:27:53 +00005137 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 Py_DECREF(result);
5139 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005140}
5141
5142PyDoc_STRVAR(long_bit_length_doc,
5143"int.bit_length() -> int\n\
5144\n\
5145Number of bits necessary to represent self in binary.\n\
5146>>> bin(37)\n\
5147'0b100101'\n\
5148>>> (37).bit_length()\n\
51496");
5150
Christian Heimes53876d92008-04-19 00:31:39 +00005151#if 0
5152static PyObject *
5153long_is_finite(PyObject *v)
5154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005155 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005156}
5157#endif
5158
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005159
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005160static PyObject *
5161long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
5162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 PyObject *byteorder_str;
5164 PyObject *is_signed_obj = NULL;
5165 Py_ssize_t length;
5166 int little_endian;
5167 int is_signed;
5168 PyObject *bytes;
5169 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
5172 &length, &byteorder_str,
5173 &is_signed_obj))
5174 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 if (args != NULL && Py_SIZE(args) > 2) {
5177 PyErr_SetString(PyExc_TypeError,
5178 "'signed' is a keyword-only argument");
5179 return NULL;
5180 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005182 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
5183 little_endian = 1;
5184 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
5185 little_endian = 0;
5186 else {
5187 PyErr_SetString(PyExc_ValueError,
5188 "byteorder must be either 'little' or 'big'");
5189 return NULL;
5190 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 if (is_signed_obj != NULL) {
5193 int cmp = PyObject_IsTrue(is_signed_obj);
5194 if (cmp < 0)
5195 return NULL;
5196 is_signed = cmp ? 1 : 0;
5197 }
5198 else {
5199 /* If the signed argument was omitted, use False as the
5200 default. */
5201 is_signed = 0;
5202 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 if (length < 0) {
5205 PyErr_SetString(PyExc_ValueError,
5206 "length argument must be non-negative");
5207 return NULL;
5208 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005210 bytes = PyBytes_FromStringAndSize(NULL, length);
5211 if (bytes == NULL)
5212 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
5215 length, little_endian, is_signed) < 0) {
5216 Py_DECREF(bytes);
5217 return NULL;
5218 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005221}
5222
Mark Dickinson078c2532010-01-30 18:06:17 +00005223PyDoc_STRVAR(long_to_bytes_doc,
5224"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005225\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005226Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005227\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005229raised if the integer is not representable with the given number of\n\
5230bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005231\n\
5232The byteorder argument determines the byte order used to represent the\n\
5233integer. If byteorder is 'big', the most significant byte is at the\n\
5234beginning of the byte array. If byteorder is 'little', the most\n\
5235significant byte is at the end of the byte array. To request the native\n\
5236byte order of the host system, use `sys.byteorder' as the byte order value.\n\
5237\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005238The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005240is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005241
5242static PyObject *
5243long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
5244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005245 PyObject *byteorder_str;
5246 PyObject *is_signed_obj = NULL;
5247 int little_endian;
5248 int is_signed;
5249 PyObject *obj;
5250 PyObject *bytes;
5251 PyObject *long_obj;
5252 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005254 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
5255 &obj, &byteorder_str,
5256 &is_signed_obj))
5257 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 if (args != NULL && Py_SIZE(args) > 2) {
5260 PyErr_SetString(PyExc_TypeError,
5261 "'signed' is a keyword-only argument");
5262 return NULL;
5263 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
5266 little_endian = 1;
5267 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
5268 little_endian = 0;
5269 else {
5270 PyErr_SetString(PyExc_ValueError,
5271 "byteorder must be either 'little' or 'big'");
5272 return NULL;
5273 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 if (is_signed_obj != NULL) {
5276 int cmp = PyObject_IsTrue(is_signed_obj);
5277 if (cmp < 0)
5278 return NULL;
5279 is_signed = cmp ? 1 : 0;
5280 }
5281 else {
5282 /* If the signed argument was omitted, use False as the
5283 default. */
5284 is_signed = 0;
5285 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 bytes = PyObject_Bytes(obj);
5288 if (bytes == NULL)
5289 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 long_obj = _PyLong_FromByteArray(
5292 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5293 little_endian, is_signed);
5294 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005295
Serhiy Storchakaea36c942016-05-12 10:37:58 +03005296 if (type != &PyLong_Type) {
5297 Py_SETREF(long_obj, PyObject_CallFunctionObjArgs((PyObject *)type,
5298 long_obj, NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005302}
5303
Mark Dickinson078c2532010-01-30 18:06:17 +00005304PyDoc_STRVAR(long_from_bytes_doc,
5305"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
5306\n\
5307Return the integer represented by the given array of bytes.\n\
5308\n\
R David Murray861470c2014-10-05 11:47:01 -04005309The bytes argument must be a bytes-like object (e.g. bytes or bytearray).\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005310\n\
5311The byteorder argument determines the byte order used to represent the\n\
5312integer. If byteorder is 'big', the most significant byte is at the\n\
5313beginning of the byte array. If byteorder is 'little', the most\n\
5314significant byte is at the end of the byte array. To request the native\n\
5315byte order of the host system, use `sys.byteorder' as the byte order value.\n\
5316\n\
5317The signed keyword-only argument indicates whether two's complement is\n\
5318used to represent the integer.");
5319
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005320static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005321 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
5322 "Returns self, the complex conjugate of any int."},
5323 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
5324 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00005325#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5327 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005328#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005329 {"to_bytes", (PyCFunction)long_to_bytes,
5330 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
5331 {"from_bytes", (PyCFunction)long_from_bytes,
5332 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
5333 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
5334 "Truncating an Integral returns itself."},
5335 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
5336 "Flooring an Integral returns itself."},
5337 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
5338 "Ceiling of an Integral returns itself."},
5339 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5340 "Rounding an Integral returns itself.\n"
5341 "Rounding with an ndigits argument also returns an integer."},
5342 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
5343 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
5344 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
5345 "Returns size in memory, in bytes"},
5346 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005347};
5348
Guido van Rossumb43daf72007-08-01 18:08:08 +00005349static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005350 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005351 (getter)long_long, (setter)NULL,
5352 "the real part of a complex number",
5353 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005354 {"imag",
5355 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005356 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005357 NULL},
5358 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005359 (getter)long_long, (setter)NULL,
5360 "the numerator of a rational number in lowest terms",
5361 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005362 {"denominator",
5363 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005364 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005365 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005366 {NULL} /* Sentinel */
5367};
5368
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005369PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005370"int(x=0) -> integer\n\
5371int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005372\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005373Convert a number or string to an integer, or return 0 if no arguments\n\
5374are given. If x is a number, return x.__int__(). For floating point\n\
5375numbers, this truncates towards zero.\n\
5376\n\
5377If x is not a number or if base is given, then x must be a string,\n\
5378bytes, or bytearray instance representing an integer literal in the\n\
5379given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5380by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5381Base 0 means to interpret the base from the string as an integer literal.\n\
5382>>> int('0b100', base=0)\n\
53834");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005384
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005385static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005386 (binaryfunc)long_add, /*nb_add*/
5387 (binaryfunc)long_sub, /*nb_subtract*/
5388 (binaryfunc)long_mul, /*nb_multiply*/
5389 long_mod, /*nb_remainder*/
5390 long_divmod, /*nb_divmod*/
5391 long_pow, /*nb_power*/
5392 (unaryfunc)long_neg, /*nb_negative*/
5393 (unaryfunc)long_long, /*tp_positive*/
5394 (unaryfunc)long_abs, /*tp_absolute*/
5395 (inquiry)long_bool, /*tp_bool*/
5396 (unaryfunc)long_invert, /*nb_invert*/
5397 long_lshift, /*nb_lshift*/
5398 (binaryfunc)long_rshift, /*nb_rshift*/
5399 long_and, /*nb_and*/
5400 long_xor, /*nb_xor*/
5401 long_or, /*nb_or*/
5402 long_long, /*nb_int*/
5403 0, /*nb_reserved*/
5404 long_float, /*nb_float*/
5405 0, /* nb_inplace_add */
5406 0, /* nb_inplace_subtract */
5407 0, /* nb_inplace_multiply */
5408 0, /* nb_inplace_remainder */
5409 0, /* nb_inplace_power */
5410 0, /* nb_inplace_lshift */
5411 0, /* nb_inplace_rshift */
5412 0, /* nb_inplace_and */
5413 0, /* nb_inplace_xor */
5414 0, /* nb_inplace_or */
5415 long_div, /* nb_floor_divide */
5416 long_true_divide, /* nb_true_divide */
5417 0, /* nb_inplace_floor_divide */
5418 0, /* nb_inplace_true_divide */
5419 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005420};
5421
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005422PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5424 "int", /* tp_name */
5425 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5426 sizeof(digit), /* tp_itemsize */
5427 long_dealloc, /* tp_dealloc */
5428 0, /* tp_print */
5429 0, /* tp_getattr */
5430 0, /* tp_setattr */
5431 0, /* tp_reserved */
5432 long_to_decimal_string, /* tp_repr */
5433 &long_as_number, /* tp_as_number */
5434 0, /* tp_as_sequence */
5435 0, /* tp_as_mapping */
5436 (hashfunc)long_hash, /* tp_hash */
5437 0, /* tp_call */
5438 long_to_decimal_string, /* tp_str */
5439 PyObject_GenericGetAttr, /* tp_getattro */
5440 0, /* tp_setattro */
5441 0, /* tp_as_buffer */
5442 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5443 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5444 long_doc, /* tp_doc */
5445 0, /* tp_traverse */
5446 0, /* tp_clear */
5447 long_richcompare, /* tp_richcompare */
5448 0, /* tp_weaklistoffset */
5449 0, /* tp_iter */
5450 0, /* tp_iternext */
5451 long_methods, /* tp_methods */
5452 0, /* tp_members */
5453 long_getset, /* tp_getset */
5454 0, /* tp_base */
5455 0, /* tp_dict */
5456 0, /* tp_descr_get */
5457 0, /* tp_descr_set */
5458 0, /* tp_dictoffset */
5459 0, /* tp_init */
5460 0, /* tp_alloc */
5461 long_new, /* tp_new */
5462 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005463};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005464
Mark Dickinsonbd792642009-03-18 20:06:12 +00005465static PyTypeObject Int_InfoType;
5466
5467PyDoc_STRVAR(int_info__doc__,
5468"sys.int_info\n\
5469\n\
5470A struct sequence that holds information about Python's\n\
5471internal representation of integers. The attributes are read only.");
5472
5473static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005474 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005475 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005477};
5478
5479static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 "sys.int_info", /* name */
5481 int_info__doc__, /* doc */
5482 int_info_fields, /* fields */
5483 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005484};
5485
5486PyObject *
5487PyLong_GetInfo(void)
5488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005489 PyObject* int_info;
5490 int field = 0;
5491 int_info = PyStructSequence_New(&Int_InfoType);
5492 if (int_info == NULL)
5493 return NULL;
5494 PyStructSequence_SET_ITEM(int_info, field++,
5495 PyLong_FromLong(PyLong_SHIFT));
5496 PyStructSequence_SET_ITEM(int_info, field++,
5497 PyLong_FromLong(sizeof(digit)));
5498 if (PyErr_Occurred()) {
5499 Py_CLEAR(int_info);
5500 return NULL;
5501 }
5502 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005503}
5504
Guido van Rossumddefaf32007-01-14 03:31:43 +00005505int
5506_PyLong_Init(void)
5507{
5508#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 int ival, size;
5510 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5513 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5514 if (Py_TYPE(v) == &PyLong_Type) {
5515 /* The element is already initialized, most likely
5516 * the Python interpreter was initialized before.
5517 */
5518 Py_ssize_t refcnt;
5519 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5522 _Py_NewReference(op);
5523 /* _Py_NewReference sets the ref count to 1 but
5524 * the ref count might be larger. Set the refcnt
5525 * to the original refcnt + 1 */
5526 Py_REFCNT(op) = refcnt + 1;
5527 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005528 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 }
5530 else {
Christian Heimesd3afe782013-12-04 09:27:47 +01005531 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 }
5533 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005534 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005536#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005538 if (Int_InfoType.tp_name == NULL) {
5539 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5540 return 0;
5541 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005544}
5545
5546void
5547PyLong_Fini(void)
5548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 /* Integers are currently statically allocated. Py_DECREF is not
5550 needed, but Python must forget about the reference or multiple
5551 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005552#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005553 int i;
5554 PyLongObject *v = small_ints;
5555 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5556 _Py_DEC_REFTOTAL;
5557 _Py_ForgetReference((PyObject*)v);
5558 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005559#endif
5560}