blob: ad239ce84e237ab4b0a2adee3b1368ec2b542978 [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;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100237 int sign;
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;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100249 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 /* Fast path for single-digit ints */
253 if (!(abs_ival >> PyLong_SHIFT)) {
254 v = _PyLong_New(1);
255 if (v) {
256 Py_SIZE(v) = sign;
257 v->ob_digit[0] = Py_SAFE_DOWNCAST(
258 abs_ival, unsigned long, digit);
259 }
260 return (PyObject*)v;
261 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000262
Mark Dickinson249b8982009-04-27 19:41:00 +0000263#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 /* 2 digits */
265 if (!(abs_ival >> 2*PyLong_SHIFT)) {
266 v = _PyLong_New(2);
267 if (v) {
268 Py_SIZE(v) = 2*sign;
269 v->ob_digit[0] = Py_SAFE_DOWNCAST(
270 abs_ival & PyLong_MASK, unsigned long, digit);
271 v->ob_digit[1] = Py_SAFE_DOWNCAST(
272 abs_ival >> PyLong_SHIFT, unsigned long, digit);
273 }
274 return (PyObject*)v;
275 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000276#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 /* Larger numbers: loop to determine number of digits */
279 t = abs_ival;
280 while (t) {
281 ++ndigits;
282 t >>= PyLong_SHIFT;
283 }
284 v = _PyLong_New(ndigits);
285 if (v != NULL) {
286 digit *p = v->ob_digit;
287 Py_SIZE(v) = ndigits*sign;
288 t = abs_ival;
289 while (t) {
290 *p++ = Py_SAFE_DOWNCAST(
291 t & PyLong_MASK, unsigned long, digit);
292 t >>= PyLong_SHIFT;
293 }
294 }
295 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000296}
297
Serhiy Storchaka95949422013-08-27 19:40:23 +0300298/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000299
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000300PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000301PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 PyLongObject *v;
304 unsigned long t;
305 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (ival < PyLong_BASE)
308 return PyLong_FromLong(ival);
309 /* Count the number of Python digits. */
310 t = (unsigned long)ival;
311 while (t) {
312 ++ndigits;
313 t >>= PyLong_SHIFT;
314 }
315 v = _PyLong_New(ndigits);
316 if (v != NULL) {
317 digit *p = v->ob_digit;
318 Py_SIZE(v) = ndigits;
319 while (ival) {
320 *p++ = (digit)(ival & PyLong_MASK);
321 ival >>= PyLong_SHIFT;
322 }
323 }
324 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000325}
326
Serhiy Storchaka95949422013-08-27 19:40:23 +0300327/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000328
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyLongObject *v;
333 double frac;
334 int i, ndig, expo, neg;
335 neg = 0;
336 if (Py_IS_INFINITY(dval)) {
337 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000338 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 return NULL;
340 }
341 if (Py_IS_NAN(dval)) {
342 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000343 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return NULL;
345 }
346 if (dval < 0.0) {
347 neg = 1;
348 dval = -dval;
349 }
350 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
351 if (expo <= 0)
352 return PyLong_FromLong(0L);
353 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
354 v = _PyLong_New(ndig);
355 if (v == NULL)
356 return NULL;
357 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
358 for (i = ndig; --i >= 0; ) {
359 digit bits = (digit)frac;
360 v->ob_digit[i] = bits;
361 frac = frac - (double)bits;
362 frac = ldexp(frac, PyLong_SHIFT);
363 }
364 if (neg)
365 Py_SIZE(v) = -(Py_SIZE(v));
366 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000367}
368
Thomas Wouters89f507f2006-12-13 04:49:30 +0000369/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
370 * anything about what happens when a signed integer operation overflows,
371 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700372 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000373 * (unsigned long)LONG_MAX, and for the smallest negative signed long
374 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
375 * However, some other compilers warn about applying unary minus to an
376 * unsigned operand. Hence the weird "0-".
377 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
379#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000380
Serhiy Storchaka95949422013-08-27 19:40:23 +0300381/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100382 method.
383
384 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
385 the result. Otherwise *overflow is 0.
386
387 For other errors (e.g., TypeError), return -1 and set an error condition.
388 In this case *overflow will be 0.
389*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000390
391long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000392PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200395 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 unsigned long x, prev;
397 long res;
398 Py_ssize_t i;
399 int sign;
400 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 *overflow = 0;
403 if (vv == NULL) {
404 PyErr_BadInternalCall();
405 return -1;
406 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000407
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200408 if (PyLong_Check(vv)) {
409 v = (PyLongObject *)vv;
410 }
411 else {
412 v = _PyLong_FromNbInt(vv);
413 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 return -1;
415 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 switch (i) {
422 case -1:
423 res = -(sdigit)v->ob_digit[0];
424 break;
425 case 0:
426 res = 0;
427 break;
428 case 1:
429 res = v->ob_digit[0];
430 break;
431 default:
432 sign = 1;
433 x = 0;
434 if (i < 0) {
435 sign = -1;
436 i = -(i);
437 }
438 while (--i >= 0) {
439 prev = x;
440 x = (x << PyLong_SHIFT) | v->ob_digit[i];
441 if ((x >> PyLong_SHIFT) != prev) {
442 *overflow = sign;
443 goto exit;
444 }
445 }
446 /* Haven't lost any bits, but casting to long requires extra
447 * care (see comment above).
448 */
449 if (x <= (unsigned long)LONG_MAX) {
450 res = (long)x * sign;
451 }
452 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
453 res = LONG_MIN;
454 }
455 else {
456 *overflow = sign;
457 /* res is already set to -1 */
458 }
459 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000460 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200462 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 }
464 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000465}
466
Serhiy Storchaka95949422013-08-27 19:40:23 +0300467/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100468 method. Return -1 and set an error if overflow occurs. */
469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000471PyLong_AsLong(PyObject *obj)
472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 int overflow;
474 long result = PyLong_AsLongAndOverflow(obj, &overflow);
475 if (overflow) {
476 /* XXX: could be cute and give a different
477 message for overflow == -1 */
478 PyErr_SetString(PyExc_OverflowError,
479 "Python int too large to convert to C long");
480 }
481 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000482}
483
Serhiy Storchaka95949422013-08-27 19:40:23 +0300484/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200485 method. Return -1 and set an error if overflow occurs. */
486
487int
488_PyLong_AsInt(PyObject *obj)
489{
490 int overflow;
491 long result = PyLong_AsLongAndOverflow(obj, &overflow);
492 if (overflow || result > INT_MAX || result < INT_MIN) {
493 /* XXX: could be cute and give a different
494 message for overflow == -1 */
495 PyErr_SetString(PyExc_OverflowError,
496 "Python int too large to convert to C int");
497 return -1;
498 }
499 return (int)result;
500}
501
Serhiy Storchaka95949422013-08-27 19:40:23 +0300502/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000503 Returns -1 and sets an error condition if overflow occurs. */
504
505Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000506PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200507 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 size_t x, prev;
509 Py_ssize_t i;
510 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (vv == NULL) {
513 PyErr_BadInternalCall();
514 return -1;
515 }
516 if (!PyLong_Check(vv)) {
517 PyErr_SetString(PyExc_TypeError, "an integer is required");
518 return -1;
519 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 v = (PyLongObject *)vv;
522 i = Py_SIZE(v);
523 switch (i) {
524 case -1: return -(sdigit)v->ob_digit[0];
525 case 0: return 0;
526 case 1: return v->ob_digit[0];
527 }
528 sign = 1;
529 x = 0;
530 if (i < 0) {
531 sign = -1;
532 i = -(i);
533 }
534 while (--i >= 0) {
535 prev = x;
536 x = (x << PyLong_SHIFT) | v->ob_digit[i];
537 if ((x >> PyLong_SHIFT) != prev)
538 goto overflow;
539 }
540 /* Haven't lost any bits, but casting to a signed type requires
541 * extra care (see comment above).
542 */
543 if (x <= (size_t)PY_SSIZE_T_MAX) {
544 return (Py_ssize_t)x * sign;
545 }
546 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
547 return PY_SSIZE_T_MIN;
548 }
549 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000550
Mark Dickinson22b20182010-05-10 21:27:53 +0000551 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyErr_SetString(PyExc_OverflowError,
553 "Python int too large to convert to C ssize_t");
554 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000555}
556
Serhiy Storchaka95949422013-08-27 19:40:23 +0300557/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000558 Returns -1 and sets an error condition if overflow occurs. */
559
560unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000561PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000562{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200563 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 unsigned long x, prev;
565 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 if (vv == NULL) {
568 PyErr_BadInternalCall();
569 return (unsigned long)-1;
570 }
571 if (!PyLong_Check(vv)) {
572 PyErr_SetString(PyExc_TypeError, "an integer is required");
573 return (unsigned long)-1;
574 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 v = (PyLongObject *)vv;
577 i = Py_SIZE(v);
578 x = 0;
579 if (i < 0) {
580 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000581 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 return (unsigned long) -1;
583 }
584 switch (i) {
585 case 0: return 0;
586 case 1: return v->ob_digit[0];
587 }
588 while (--i >= 0) {
589 prev = x;
590 x = (x << PyLong_SHIFT) | v->ob_digit[i];
591 if ((x >> PyLong_SHIFT) != prev) {
592 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100593 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000594 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 return (unsigned long) -1;
596 }
597 }
598 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000599}
600
Serhiy Storchaka95949422013-08-27 19:40:23 +0300601/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200602 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000603
604size_t
605PyLong_AsSize_t(PyObject *vv)
606{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200607 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 size_t x, prev;
609 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (vv == NULL) {
612 PyErr_BadInternalCall();
613 return (size_t) -1;
614 }
615 if (!PyLong_Check(vv)) {
616 PyErr_SetString(PyExc_TypeError, "an integer is required");
617 return (size_t)-1;
618 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 v = (PyLongObject *)vv;
621 i = Py_SIZE(v);
622 x = 0;
623 if (i < 0) {
624 PyErr_SetString(PyExc_OverflowError,
625 "can't convert negative value to size_t");
626 return (size_t) -1;
627 }
628 switch (i) {
629 case 0: return 0;
630 case 1: return v->ob_digit[0];
631 }
632 while (--i >= 0) {
633 prev = x;
634 x = (x << PyLong_SHIFT) | v->ob_digit[i];
635 if ((x >> PyLong_SHIFT) != prev) {
636 PyErr_SetString(PyExc_OverflowError,
637 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200638 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 }
640 }
641 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000642}
643
Serhiy Storchaka95949422013-08-27 19:40:23 +0300644/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000645 Returns -1 and sets an error condition if an error occurs. */
646
Guido van Rossumddefaf32007-01-14 03:31:43 +0000647static unsigned long
648_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000649{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200650 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 unsigned long x;
652 Py_ssize_t i;
653 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 if (vv == NULL || !PyLong_Check(vv)) {
656 PyErr_BadInternalCall();
657 return (unsigned long) -1;
658 }
659 v = (PyLongObject *)vv;
660 i = Py_SIZE(v);
661 switch (i) {
662 case 0: return 0;
663 case 1: return v->ob_digit[0];
664 }
665 sign = 1;
666 x = 0;
667 if (i < 0) {
668 sign = -1;
669 i = -i;
670 }
671 while (--i >= 0) {
672 x = (x << PyLong_SHIFT) | v->ob_digit[i];
673 }
674 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000675}
676
Guido van Rossumddefaf32007-01-14 03:31:43 +0000677unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200678PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 PyLongObject *lo;
681 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000682
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200683 if (op == NULL) {
684 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return (unsigned long)-1;
686 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000687
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200688 if (PyLong_Check(op)) {
689 return _PyLong_AsUnsignedLongMask(op);
690 }
691
692 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (lo == NULL)
694 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200695
696 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
697 Py_DECREF(lo);
698 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000699}
700
Tim Peters5b8132f2003-01-31 15:52:05 +0000701int
702_PyLong_Sign(PyObject *vv)
703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 assert(v != NULL);
707 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000710}
711
Tim Petersbaefd9e2003-01-28 20:37:45 +0000712size_t
713_PyLong_NumBits(PyObject *vv)
714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyLongObject *v = (PyLongObject *)vv;
716 size_t result = 0;
717 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 assert(v != NULL);
720 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200721 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
723 if (ndigits > 0) {
724 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700725 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100727 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 do {
729 ++result;
730 if (result == 0)
731 goto Overflow;
732 msd >>= 1;
733 } while (msd);
734 }
735 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000736
Mark Dickinson22b20182010-05-10 21:27:53 +0000737 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
739 "to express in a platform size_t");
740 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000741}
742
Tim Peters2a9b3672001-06-11 21:23:58 +0000743PyObject *
744_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000746{
Mark Dickinson22b20182010-05-10 21:27:53 +0000747 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 int incr; /* direction to move pstartbyte */
749 const unsigned char* pendbyte; /* MSB of bytes */
750 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300751 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PyLongObject* v; /* result */
753 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 if (n == 0)
756 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (little_endian) {
759 pstartbyte = bytes;
760 pendbyte = bytes + n - 1;
761 incr = 1;
762 }
763 else {
764 pstartbyte = bytes + n - 1;
765 pendbyte = bytes;
766 incr = -1;
767 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (is_signed)
770 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200773 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 is positive, and leading 0xff bytes if negative. */
775 {
776 size_t i;
777 const unsigned char* p = pendbyte;
778 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000779 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000782 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 break;
784 }
785 numsignificantbytes = n - i;
786 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
787 actually has 2 significant bytes. OTOH, 0xff0001 ==
788 -0x00ffff, so we wouldn't *need* to bump it there; but we
789 do for 0xffff = -0x0001. To be safe without bothering to
790 check every case, bump it regardless. */
791 if (is_signed && numsignificantbytes < n)
792 ++numsignificantbytes;
793 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000794
Serhiy Storchaka95949422013-08-27 19:40:23 +0300795 /* How many Python int digits do we need? We have
796 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
798 /* catch overflow before it happens */
799 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
800 PyErr_SetString(PyExc_OverflowError,
801 "byte array too long to convert to int");
802 return NULL;
803 }
804 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
805 v = _PyLong_New(ndigits);
806 if (v == NULL)
807 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 /* Copy the bits over. The tricky parts are computing 2's-comp on
810 the fly for signed numbers, and dealing with the mismatch between
811 8-bit bytes and (probably) 15-bit Python digits.*/
812 {
813 size_t i;
814 twodigits carry = 1; /* for 2's-comp calculation */
815 twodigits accum = 0; /* sliding register */
816 unsigned int accumbits = 0; /* number of bits in accum */
817 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
820 twodigits thisbyte = *p;
821 /* Compute correction for 2's comp, if needed. */
822 if (is_signed) {
823 thisbyte = (0xff ^ thisbyte) + carry;
824 carry = thisbyte >> 8;
825 thisbyte &= 0xff;
826 }
827 /* Because we're going LSB to MSB, thisbyte is
828 more significant than what's already in accum,
829 so needs to be prepended to accum. */
830 accum |= (twodigits)thisbyte << accumbits;
831 accumbits += 8;
832 if (accumbits >= PyLong_SHIFT) {
833 /* There's enough to fill a Python digit. */
834 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000835 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 ++idigit;
837 accum >>= PyLong_SHIFT;
838 accumbits -= PyLong_SHIFT;
839 assert(accumbits < PyLong_SHIFT);
840 }
841 }
842 assert(accumbits < PyLong_SHIFT);
843 if (accumbits) {
844 assert(idigit < ndigits);
845 v->ob_digit[idigit] = (digit)accum;
846 ++idigit;
847 }
848 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 Py_SIZE(v) = is_signed ? -idigit : idigit;
851 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000852}
853
854int
855_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 unsigned char* bytes, size_t n,
857 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000860 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000862 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
864 digit carry; /* for computing 2's-comp */
865 size_t j; /* # bytes filled */
866 unsigned char* p; /* pointer to next byte in bytes */
867 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (Py_SIZE(v) < 0) {
872 ndigits = -(Py_SIZE(v));
873 if (!is_signed) {
874 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000875 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 return -1;
877 }
878 do_twos_comp = 1;
879 }
880 else {
881 ndigits = Py_SIZE(v);
882 do_twos_comp = 0;
883 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 if (little_endian) {
886 p = bytes;
887 pincr = 1;
888 }
889 else {
890 p = bytes + n - 1;
891 pincr = -1;
892 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Copy over all the Python digits.
895 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300896 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 normalized. */
898 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
899 j = 0;
900 accum = 0;
901 accumbits = 0;
902 carry = do_twos_comp ? 1 : 0;
903 for (i = 0; i < ndigits; ++i) {
904 digit thisdigit = v->ob_digit[i];
905 if (do_twos_comp) {
906 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
907 carry = thisdigit >> PyLong_SHIFT;
908 thisdigit &= PyLong_MASK;
909 }
910 /* Because we're going LSB to MSB, thisdigit is more
911 significant than what's already in accum, so needs to be
912 prepended to accum. */
913 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* The most-significant digit may be (probably is) at least
916 partly empty. */
917 if (i == ndigits - 1) {
918 /* Count # of sign bits -- they needn't be stored,
919 * although for signed conversion we need later to
920 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000921 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 while (s != 0) {
923 s >>= 1;
924 accumbits++;
925 }
926 }
927 else
928 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 /* Store as many bytes as possible. */
931 while (accumbits >= 8) {
932 if (j >= n)
933 goto Overflow;
934 ++j;
935 *p = (unsigned char)(accum & 0xff);
936 p += pincr;
937 accumbits -= 8;
938 accum >>= 8;
939 }
940 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Store the straggler (if any). */
943 assert(accumbits < 8);
944 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
945 if (accumbits > 0) {
946 if (j >= n)
947 goto Overflow;
948 ++j;
949 if (do_twos_comp) {
950 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300951 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 infinite supply of sign bits). */
953 accum |= (~(twodigits)0) << accumbits;
954 }
955 *p = (unsigned char)(accum & 0xff);
956 p += pincr;
957 }
958 else if (j == n && n > 0 && is_signed) {
959 /* The main loop filled the byte array exactly, so the code
960 just above didn't get to ensure there's a sign bit, and the
961 loop below wouldn't add one either. Make sure a sign bit
962 exists. */
963 unsigned char msb = *(p - pincr);
964 int sign_bit_set = msb >= 0x80;
965 assert(accumbits == 0);
966 if (sign_bit_set == do_twos_comp)
967 return 0;
968 else
969 goto Overflow;
970 }
Tim Peters05607ad2001-06-13 21:01:27 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 /* Fill remaining bytes with copies of the sign bit. */
973 {
974 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
975 for ( ; j < n; ++j, p += pincr)
976 *p = signbyte;
977 }
Tim Peters05607ad2001-06-13 21:01:27 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000980
Mark Dickinson22b20182010-05-10 21:27:53 +0000981 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
983 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000984
Tim Peters2a9b3672001-06-11 21:23:58 +0000985}
986
Serhiy Storchaka95949422013-08-27 19:40:23 +0300987/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000988
989PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000990PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000991{
Mark Dickinson91044792012-10-18 19:21:43 +0100992#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -0700993 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100994#else
995
Tim Peters70128a12001-06-16 08:48:40 +0000996#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700997# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000998#endif
Benjamin Petersonca470632016-09-06 13:47:26 -0700999 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001000#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001001
Guido van Rossum78694d91998-09-18 14:14:13 +00001002}
1003
Serhiy Storchaka95949422013-08-27 19:40:23 +03001004/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001005
1006void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001007PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001008{
Tim Peters70128a12001-06-16 08:48:40 +00001009#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1013 x = PyLong_AsLong(vv);
1014 else
1015 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001016#else
Tim Peters70128a12001-06-16 08:48:40 +00001017
Tim Peters70128a12001-06-16 08:48:40 +00001018#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001019# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001020#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001021 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1024 x = PyLong_AsLongLong(vv);
1025 else
1026 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001027
1028#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (x == -1 && PyErr_Occurred())
1031 return NULL;
1032 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001033}
1034
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001035/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001036 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001037 */
1038
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001039#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001040
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001041/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001042
1043PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001044PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001047 unsigned long long abs_ival;
1048 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 int ndigits = 0;
1050 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 CHECK_SMALL_INT(ival);
1053 if (ival < 0) {
1054 /* avoid signed overflow on negation; see comments
1055 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001056 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 negative = 1;
1058 }
1059 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001060 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 /* Count the number of Python digits.
1064 We used to pick 5 ("big enough for anything"), but that's a
1065 waste of time and space given that 5*15 = 75 bits are rarely
1066 needed. */
1067 t = abs_ival;
1068 while (t) {
1069 ++ndigits;
1070 t >>= PyLong_SHIFT;
1071 }
1072 v = _PyLong_New(ndigits);
1073 if (v != NULL) {
1074 digit *p = v->ob_digit;
1075 Py_SIZE(v) = negative ? -ndigits : ndigits;
1076 t = abs_ival;
1077 while (t) {
1078 *p++ = (digit)(t & PyLong_MASK);
1079 t >>= PyLong_SHIFT;
1080 }
1081 }
1082 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001083}
1084
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001085/* Create a new int object from a C unsigned long long int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001086
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001087PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001088PyLong_FromUnsignedLongLong(unsigned long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001091 unsigned long long t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (ival < PyLong_BASE)
1095 return PyLong_FromLong((long)ival);
1096 /* Count the number of Python digits. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001097 t = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 while (t) {
1099 ++ndigits;
1100 t >>= PyLong_SHIFT;
1101 }
1102 v = _PyLong_New(ndigits);
1103 if (v != NULL) {
1104 digit *p = v->ob_digit;
1105 Py_SIZE(v) = ndigits;
1106 while (ival) {
1107 *p++ = (digit)(ival & PyLong_MASK);
1108 ival >>= PyLong_SHIFT;
1109 }
1110 }
1111 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001112}
1113
Serhiy Storchaka95949422013-08-27 19:40:23 +03001114/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001115
1116PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001117PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 PyLongObject *v;
1120 size_t abs_ival;
1121 size_t t; /* unsigned so >> doesn't propagate sign bit */
1122 int ndigits = 0;
1123 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 CHECK_SMALL_INT(ival);
1126 if (ival < 0) {
1127 /* avoid signed overflow when ival = SIZE_T_MIN */
1128 abs_ival = (size_t)(-1-ival)+1;
1129 negative = 1;
1130 }
1131 else {
1132 abs_ival = (size_t)ival;
1133 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 /* Count the number of Python digits. */
1136 t = abs_ival;
1137 while (t) {
1138 ++ndigits;
1139 t >>= PyLong_SHIFT;
1140 }
1141 v = _PyLong_New(ndigits);
1142 if (v != NULL) {
1143 digit *p = v->ob_digit;
1144 Py_SIZE(v) = negative ? -ndigits : ndigits;
1145 t = abs_ival;
1146 while (t) {
1147 *p++ = (digit)(t & PyLong_MASK);
1148 t >>= PyLong_SHIFT;
1149 }
1150 }
1151 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001152}
1153
Serhiy Storchaka95949422013-08-27 19:40:23 +03001154/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001155
1156PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001157PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyLongObject *v;
1160 size_t t;
1161 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (ival < PyLong_BASE)
1164 return PyLong_FromLong((long)ival);
1165 /* Count the number of Python digits. */
1166 t = ival;
1167 while (t) {
1168 ++ndigits;
1169 t >>= PyLong_SHIFT;
1170 }
1171 v = _PyLong_New(ndigits);
1172 if (v != NULL) {
1173 digit *p = v->ob_digit;
1174 Py_SIZE(v) = ndigits;
1175 while (ival) {
1176 *p++ = (digit)(ival & PyLong_MASK);
1177 ival >>= PyLong_SHIFT;
1178 }
1179 }
1180 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001181}
1182
Serhiy Storchaka95949422013-08-27 19:40:23 +03001183/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001184 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001185
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001186long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001187PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001190 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001192 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (vv == NULL) {
1195 PyErr_BadInternalCall();
1196 return -1;
1197 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001198
1199 if (PyLong_Check(vv)) {
1200 v = (PyLongObject *)vv;
1201 }
1202 else {
1203 v = _PyLong_FromNbInt(vv);
1204 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001206 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001208
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001209 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001211 case -1:
1212 bytes = -(sdigit)v->ob_digit[0];
1213 break;
1214 case 0:
1215 bytes = 0;
1216 break;
1217 case 1:
1218 bytes = v->ob_digit[0];
1219 break;
1220 default:
1221 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001222 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001224 if (do_decref) {
1225 Py_DECREF(v);
1226 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001227
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001228 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001230 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 else
1232 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001233}
1234
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001235/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001236 Return -1 and set an error if overflow occurs. */
1237
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001238unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001239PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001242 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001244
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001245 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001247 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001249 if (!PyLong_Check(vv)) {
1250 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001251 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001252 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 v = (PyLongObject*)vv;
1255 switch(Py_SIZE(v)) {
1256 case 0: return 0;
1257 case 1: return v->ob_digit[0];
1258 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001259
Mark Dickinson22b20182010-05-10 21:27:53 +00001260 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001261 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001262
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001263 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001265 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 else
1267 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001268}
Tim Petersd1a7da62001-06-13 00:35:57 +00001269
Serhiy Storchaka95949422013-08-27 19:40:23 +03001270/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001271 Returns -1 and sets an error condition if an error occurs. */
1272
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001273static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001274_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001275{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001276 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001277 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 Py_ssize_t i;
1279 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (vv == NULL || !PyLong_Check(vv)) {
1282 PyErr_BadInternalCall();
1283 return (unsigned long) -1;
1284 }
1285 v = (PyLongObject *)vv;
1286 switch(Py_SIZE(v)) {
1287 case 0: return 0;
1288 case 1: return v->ob_digit[0];
1289 }
1290 i = Py_SIZE(v);
1291 sign = 1;
1292 x = 0;
1293 if (i < 0) {
1294 sign = -1;
1295 i = -i;
1296 }
1297 while (--i >= 0) {
1298 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1299 }
1300 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001301}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001302
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001303unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001304PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001307 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001308
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001309 if (op == NULL) {
1310 PyErr_BadInternalCall();
1311 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001313
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001314 if (PyLong_Check(op)) {
1315 return _PyLong_AsUnsignedLongLongMask(op);
1316 }
1317
1318 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001320 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001321
1322 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1323 Py_DECREF(lo);
1324 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001325}
Tim Petersd1a7da62001-06-13 00:35:57 +00001326
Serhiy Storchaka95949422013-08-27 19:40:23 +03001327/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001328 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001329
Mark Dickinson8d48b432011-10-23 20:47:14 +01001330 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1331 the result. Otherwise *overflow is 0.
1332
1333 For other errors (e.g., TypeError), return -1 and set an error condition.
1334 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001335*/
1336
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001337long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001338PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001341 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001342 unsigned long long x, prev;
1343 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 Py_ssize_t i;
1345 int sign;
1346 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 *overflow = 0;
1349 if (vv == NULL) {
1350 PyErr_BadInternalCall();
1351 return -1;
1352 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001353
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001354 if (PyLong_Check(vv)) {
1355 v = (PyLongObject *)vv;
1356 }
1357 else {
1358 v = _PyLong_FromNbInt(vv);
1359 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 return -1;
1361 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 switch (i) {
1368 case -1:
1369 res = -(sdigit)v->ob_digit[0];
1370 break;
1371 case 0:
1372 res = 0;
1373 break;
1374 case 1:
1375 res = v->ob_digit[0];
1376 break;
1377 default:
1378 sign = 1;
1379 x = 0;
1380 if (i < 0) {
1381 sign = -1;
1382 i = -(i);
1383 }
1384 while (--i >= 0) {
1385 prev = x;
1386 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1387 if ((x >> PyLong_SHIFT) != prev) {
1388 *overflow = sign;
1389 goto exit;
1390 }
1391 }
1392 /* Haven't lost any bits, but casting to long requires extra
1393 * care (see comment above).
1394 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001395 if (x <= (unsigned long long)PY_LLONG_MAX) {
1396 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 }
1398 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1399 res = PY_LLONG_MIN;
1400 }
1401 else {
1402 *overflow = sign;
1403 /* res is already set to -1 */
1404 }
1405 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001406 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001408 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 }
1410 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001411}
1412
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001413#define CHECK_BINOP(v,w) \
1414 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001415 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1416 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001417 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001418
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001419/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1420 2**k if d is nonzero, else 0. */
1421
1422static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1424 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001425};
1426
1427static int
1428bits_in_digit(digit d)
1429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 int d_bits = 0;
1431 while (d >= 32) {
1432 d_bits += 6;
1433 d >>= 6;
1434 }
1435 d_bits += (int)BitLengthTable[d];
1436 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001437}
1438
Tim Peters877a2122002-08-12 05:09:36 +00001439/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1440 * is modified in place, by adding y to it. Carries are propagated as far as
1441 * x[m-1], and the remaining carry (0 or 1) is returned.
1442 */
1443static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001444v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 Py_ssize_t i;
1447 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 assert(m >= n);
1450 for (i = 0; i < n; ++i) {
1451 carry += x[i] + y[i];
1452 x[i] = carry & PyLong_MASK;
1453 carry >>= PyLong_SHIFT;
1454 assert((carry & 1) == carry);
1455 }
1456 for (; carry && i < m; ++i) {
1457 carry += x[i];
1458 x[i] = carry & PyLong_MASK;
1459 carry >>= PyLong_SHIFT;
1460 assert((carry & 1) == carry);
1461 }
1462 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001463}
1464
1465/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1466 * is modified in place, by subtracting y from it. Borrows are propagated as
1467 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1468 */
1469static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001470v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 Py_ssize_t i;
1473 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 assert(m >= n);
1476 for (i = 0; i < n; ++i) {
1477 borrow = x[i] - y[i] - borrow;
1478 x[i] = borrow & PyLong_MASK;
1479 borrow >>= PyLong_SHIFT;
1480 borrow &= 1; /* keep only 1 sign bit */
1481 }
1482 for (; borrow && i < m; ++i) {
1483 borrow = x[i] - borrow;
1484 x[i] = borrow & PyLong_MASK;
1485 borrow >>= PyLong_SHIFT;
1486 borrow &= 1;
1487 }
1488 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001489}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001490
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001491/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1492 * result in z[0:m], and return the d bits shifted out of the top.
1493 */
1494static digit
1495v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 Py_ssize_t i;
1498 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 assert(0 <= d && d < PyLong_SHIFT);
1501 for (i=0; i < m; i++) {
1502 twodigits acc = (twodigits)a[i] << d | carry;
1503 z[i] = (digit)acc & PyLong_MASK;
1504 carry = (digit)(acc >> PyLong_SHIFT);
1505 }
1506 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001507}
1508
1509/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1510 * result in z[0:m], and return the d bits shifted out of the bottom.
1511 */
1512static digit
1513v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 Py_ssize_t i;
1516 digit carry = 0;
1517 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 assert(0 <= d && d < PyLong_SHIFT);
1520 for (i=m; i-- > 0;) {
1521 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1522 carry = (digit)acc & mask;
1523 z[i] = (digit)(acc >> d);
1524 }
1525 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001526}
1527
Tim Peters212e6142001-07-14 12:23:19 +00001528/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1529 in pout, and returning the remainder. pin and pout point at the LSD.
1530 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001531 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001532 immutable. */
1533
1534static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001535inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 assert(n > 0 && n <= PyLong_MASK);
1540 pin += size;
1541 pout += size;
1542 while (--size >= 0) {
1543 digit hi;
1544 rem = (rem << PyLong_SHIFT) | *--pin;
1545 *--pout = hi = (digit)(rem / n);
1546 rem -= (twodigits)hi * n;
1547 }
1548 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001549}
1550
Serhiy Storchaka95949422013-08-27 19:40:23 +03001551/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001552 (as function result) and the remainder (through *prem).
1553 The sign of a is ignored; n should not be zero. */
1554
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001555static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001556divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001557{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001558 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 assert(n > 0 && n <= PyLong_MASK);
1562 z = _PyLong_New(size);
1563 if (z == NULL)
1564 return NULL;
1565 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1566 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001567}
1568
Serhiy Storchaka95949422013-08-27 19:40:23 +03001569/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001570 string. (Return value is non-shared so that callers can modify the
1571 returned value if necessary.) */
1572
Victor Stinnerd3f08822012-05-29 12:57:52 +02001573static int
1574long_to_decimal_string_internal(PyObject *aa,
1575 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001576 _PyUnicodeWriter *writer,
1577 _PyBytesWriter *bytes_writer,
1578 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001581 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 Py_ssize_t size, strlen, size_a, i, j;
1583 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001585 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001586 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 a = (PyLongObject *)aa;
1589 if (a == NULL || !PyLong_Check(a)) {
1590 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001591 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001593 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 /* quick and dirty upper bound for the number of digits
1597 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 But log2(a) < size_a * PyLong_SHIFT, and
1602 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001603 > 3.3 * _PyLong_DECIMAL_SHIFT
1604
1605 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1606 size_a + size_a / d < size_a + size_a / floor(d),
1607 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1608 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001610 d = (33 * _PyLong_DECIMAL_SHIFT) /
1611 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1612 assert(size_a < PY_SSIZE_T_MAX/2);
1613 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 scratch = _PyLong_New(size);
1615 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001616 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 /* convert array of base _PyLong_BASE digits in pin to an array of
1619 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1620 Volume 2 (3rd edn), section 4.4, Method 1b). */
1621 pin = a->ob_digit;
1622 pout = scratch->ob_digit;
1623 size = 0;
1624 for (i = size_a; --i >= 0; ) {
1625 digit hi = pin[i];
1626 for (j = 0; j < size; j++) {
1627 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1628 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1629 pout[j] = (digit)(z - (twodigits)hi *
1630 _PyLong_DECIMAL_BASE);
1631 }
1632 while (hi) {
1633 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1634 hi /= _PyLong_DECIMAL_BASE;
1635 }
1636 /* check for keyboard interrupt */
1637 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001638 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001639 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001640 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 }
1642 /* pout should have at least one digit, so that the case when a = 0
1643 works correctly */
1644 if (size == 0)
1645 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 /* calculate exact length of output string, and allocate */
1648 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1649 tenpow = 10;
1650 rem = pout[size-1];
1651 while (rem >= tenpow) {
1652 tenpow *= 10;
1653 strlen++;
1654 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001655 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001656 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1657 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001658 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001659 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001660 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001662 else if (bytes_writer) {
1663 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1664 if (*bytes_str == NULL) {
1665 Py_DECREF(scratch);
1666 return -1;
1667 }
1668 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001669 else {
1670 str = PyUnicode_New(strlen, '9');
1671 if (str == NULL) {
1672 Py_DECREF(scratch);
1673 return -1;
1674 }
1675 kind = PyUnicode_KIND(str);
1676 }
1677
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001678#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001679 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001680 /* pout[0] through pout[size-2] contribute exactly \
1681 _PyLong_DECIMAL_SHIFT digits each */ \
1682 for (i=0; i < size - 1; i++) { \
1683 rem = pout[i]; \
1684 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1685 *--p = '0' + rem % 10; \
1686 rem /= 10; \
1687 } \
1688 } \
1689 /* pout[size-1]: always produce at least one decimal digit */ \
1690 rem = pout[i]; \
1691 do { \
1692 *--p = '0' + rem % 10; \
1693 rem /= 10; \
1694 } while (rem != 0); \
1695 \
1696 /* and sign */ \
1697 if (negative) \
1698 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001699 } while (0)
1700
1701#define WRITE_UNICODE_DIGITS(TYPE) \
1702 do { \
1703 if (writer) \
1704 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1705 else \
1706 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1707 \
1708 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001709 \
1710 /* check we've counted correctly */ \
1711 if (writer) \
1712 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1713 else \
1714 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1715 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001718 if (bytes_writer) {
1719 char *p = *bytes_str + strlen;
1720 WRITE_DIGITS(p);
1721 assert(p == *bytes_str);
1722 }
1723 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001724 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001725 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001727 else if (kind == PyUnicode_2BYTE_KIND) {
1728 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001729 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001730 }
1731 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001732 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001733 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001734 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001735 }
1736#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001737#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001740 if (writer) {
1741 writer->pos += strlen;
1742 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001743 else if (bytes_writer) {
1744 (*bytes_str) += strlen;
1745 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001746 else {
1747 assert(_PyUnicode_CheckConsistency(str, 1));
1748 *p_output = (PyObject *)str;
1749 }
1750 return 0;
1751}
1752
1753static PyObject *
1754long_to_decimal_string(PyObject *aa)
1755{
1756 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001757 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001758 return NULL;
1759 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001760}
1761
Serhiy Storchaka95949422013-08-27 19:40:23 +03001762/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001763 which should be one of 2, 8 or 16. Return a string object.
1764 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1765 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001766
Victor Stinnerd3f08822012-05-29 12:57:52 +02001767static int
1768long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001769 PyObject **p_output, _PyUnicodeWriter *writer,
1770 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001771{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001772 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001773 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001774 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001776 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001777 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001779
Victor Stinnerd3f08822012-05-29 12:57:52 +02001780 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 if (a == NULL || !PyLong_Check(a)) {
1782 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001783 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001785 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001786 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 /* Compute a rough upper bound for the length of the string */
1789 switch (base) {
1790 case 16:
1791 bits = 4;
1792 break;
1793 case 8:
1794 bits = 3;
1795 break;
1796 case 2:
1797 bits = 1;
1798 break;
1799 default:
1800 assert(0); /* shouldn't ever get here */
1801 bits = 0; /* to silence gcc warning */
1802 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001803
Mark Dickinsone2846542012-04-20 21:21:24 +01001804 /* Compute exact length 'sz' of output string. */
1805 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001806 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001807 }
1808 else {
1809 Py_ssize_t size_a_in_bits;
1810 /* Ensure overflow doesn't occur during computation of sz. */
1811 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1812 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001813 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001814 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001815 }
1816 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1817 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001818 /* Allow 1 character for a '-' sign. */
1819 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1820 }
1821 if (alternate) {
1822 /* 2 characters for prefix */
1823 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001824 }
1825
Victor Stinnerd3f08822012-05-29 12:57:52 +02001826 if (writer) {
1827 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1828 return -1;
1829 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001831 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001832 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1833 if (*bytes_str == NULL)
1834 return -1;
1835 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001837 v = PyUnicode_New(sz, 'x');
1838 if (v == NULL)
1839 return -1;
1840 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001842
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001843#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001844 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001845 if (size_a == 0) { \
1846 *--p = '0'; \
1847 } \
1848 else { \
1849 /* JRH: special case for power-of-2 bases */ \
1850 twodigits accum = 0; \
1851 int accumbits = 0; /* # of bits in accum */ \
1852 Py_ssize_t i; \
1853 for (i = 0; i < size_a; ++i) { \
1854 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1855 accumbits += PyLong_SHIFT; \
1856 assert(accumbits >= bits); \
1857 do { \
1858 char cdigit; \
1859 cdigit = (char)(accum & (base - 1)); \
1860 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1861 *--p = cdigit; \
1862 accumbits -= bits; \
1863 accum >>= bits; \
1864 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1865 } \
1866 } \
1867 \
1868 if (alternate) { \
1869 if (base == 16) \
1870 *--p = 'x'; \
1871 else if (base == 8) \
1872 *--p = 'o'; \
1873 else /* (base == 2) */ \
1874 *--p = 'b'; \
1875 *--p = '0'; \
1876 } \
1877 if (negative) \
1878 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001879 } while (0)
1880
1881#define WRITE_UNICODE_DIGITS(TYPE) \
1882 do { \
1883 if (writer) \
1884 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1885 else \
1886 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1887 \
1888 WRITE_DIGITS(p); \
1889 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001890 if (writer) \
1891 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1892 else \
1893 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1894 } while (0)
1895
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001896 if (bytes_writer) {
1897 char *p = *bytes_str + sz;
1898 WRITE_DIGITS(p);
1899 assert(p == *bytes_str);
1900 }
1901 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001902 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001903 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001904 }
1905 else if (kind == PyUnicode_2BYTE_KIND) {
1906 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001907 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001908 }
1909 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001910 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001911 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001912 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001913 }
1914#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001915#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001916
1917 if (writer) {
1918 writer->pos += sz;
1919 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001920 else if (bytes_writer) {
1921 (*bytes_str) += sz;
1922 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001923 else {
1924 assert(_PyUnicode_CheckConsistency(v, 1));
1925 *p_output = v;
1926 }
1927 return 0;
1928}
1929
1930PyObject *
1931_PyLong_Format(PyObject *obj, int base)
1932{
1933 PyObject *str;
1934 int err;
1935 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001936 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001937 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001938 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001939 if (err == -1)
1940 return NULL;
1941 return str;
1942}
1943
1944int
1945_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1946 PyObject *obj,
1947 int base, int alternate)
1948{
1949 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001950 return long_to_decimal_string_internal(obj, NULL, writer,
1951 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001952 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001953 return long_format_binary(obj, base, alternate, NULL, writer,
1954 NULL, NULL);
1955}
1956
1957char*
1958_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1959 PyObject *obj,
1960 int base, int alternate)
1961{
1962 char *str2;
1963 int res;
1964 str2 = str;
1965 if (base == 10)
1966 res = long_to_decimal_string_internal(obj, NULL, NULL,
1967 writer, &str2);
1968 else
1969 res = long_format_binary(obj, base, alternate, NULL, NULL,
1970 writer, &str2);
1971 if (res < 0)
1972 return NULL;
1973 assert(str2 != NULL);
1974 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001975}
1976
Thomas Wouters477c8d52006-05-27 19:21:47 +00001977/* Table of digit values for 8-bit string -> integer conversion.
1978 * '0' maps to 0, ..., '9' maps to 9.
1979 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1980 * All other indices map to 37.
1981 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001982 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001983 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001984unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1988 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1989 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1990 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1991 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1992 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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,
2000 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002001};
2002
2003/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002004 * 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 +03002005 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002006 * The point to this routine is that it takes time linear in the number of
2007 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002008 *
2009 * Return values:
2010 * -1 on syntax error (exception needs to be set, *res is untouched)
2011 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002012 */
Brett Cannona721aba2016-09-09 14:57:09 -07002013static int
2014long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002015{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002016 const char *p = *str;
2017 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002018 char prev = 0;
2019 int digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 int bits_per_char;
2021 Py_ssize_t n;
2022 PyLongObject *z;
2023 twodigits accum;
2024 int bits_in_accum;
2025 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2028 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002029 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002031 }
2032 /* count digits and set p to end-of-string */
2033 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2034 if (*p == '_') {
2035 if (prev == '_') {
2036 *str = p - 1;
2037 return -1;
2038 }
2039 } else {
2040 ++digits;
2041 }
2042 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002044 }
2045 if (prev == '_') {
2046 /* Trailing underscore not allowed. */
2047 *str = p - 1;
2048 return -1;
2049 }
2050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 *str = p;
2052 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
Brett Cannona721aba2016-09-09 14:57:09 -07002053 n = digits * bits_per_char + PyLong_SHIFT - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 if (n / bits_per_char < p - start) {
2055 PyErr_SetString(PyExc_ValueError,
2056 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002057 *res = NULL;
2058 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 }
2060 n = n / PyLong_SHIFT;
2061 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002062 if (z == NULL) {
2063 *res = NULL;
2064 return 0;
2065 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002066 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 * from least to most significant in both.
2068 */
2069 accum = 0;
2070 bits_in_accum = 0;
2071 pdigit = z->ob_digit;
2072 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002073 int k;
2074 if (*p == '_') {
2075 continue;
2076 }
2077 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 assert(k >= 0 && k < base);
2079 accum |= (twodigits)k << bits_in_accum;
2080 bits_in_accum += bits_per_char;
2081 if (bits_in_accum >= PyLong_SHIFT) {
2082 *pdigit++ = (digit)(accum & PyLong_MASK);
2083 assert(pdigit - z->ob_digit <= n);
2084 accum >>= PyLong_SHIFT;
2085 bits_in_accum -= PyLong_SHIFT;
2086 assert(bits_in_accum < PyLong_SHIFT);
2087 }
2088 }
2089 if (bits_in_accum) {
2090 assert(bits_in_accum <= PyLong_SHIFT);
2091 *pdigit++ = (digit)accum;
2092 assert(pdigit - z->ob_digit <= n);
2093 }
2094 while (pdigit - z->ob_digit < n)
2095 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002096 *res = long_normalize(z);
2097 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002098}
2099
Serhiy Storchaka95949422013-08-27 19:40:23 +03002100/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002101 * ignored.
2102 *
2103 * If successful, a PyLong object will be returned and 'pend' will be pointing
2104 * to the first unused byte unless it's NULL.
2105 *
2106 * If unsuccessful, NULL will be returned.
2107 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002108PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002109PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002112 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 PyLongObject *z = NULL;
2114 PyObject *strobj;
2115 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 if ((base != 0 && base < 2) || base > 36) {
2118 PyErr_SetString(PyExc_ValueError,
2119 "int() arg 2 must be >= 2 and <= 36");
2120 return NULL;
2121 }
Brett Cannona721aba2016-09-09 14:57:09 -07002122 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002124 }
2125 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 else if (*str == '-') {
2129 ++str;
2130 sign = -1;
2131 }
2132 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002133 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002135 }
2136 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002138 }
2139 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002141 }
2142 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002144 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 else {
2146 /* "old" (C-style) octal literal, now invalid.
2147 it might still be zero though */
2148 error_if_nonzero = 1;
2149 base = 10;
2150 }
2151 }
2152 if (str[0] == '0' &&
2153 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2154 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002155 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002157 /* One underscore allowed here. */
2158 if (*str == '_') {
2159 ++str;
2160 }
2161 }
2162 if (str[0] == '_') {
2163 /* May not start with underscores. */
2164 goto onError;
2165 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002168 if ((base & (base - 1)) == 0) {
2169 int res = long_from_binary_base(&str, base, &z);
2170 if (res < 0) {
2171 /* Syntax error. */
2172 goto onError;
2173 }
2174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002176/***
2177Binary bases can be converted in time linear in the number of digits, because
2178Python's representation base is binary. Other bases (including decimal!) use
2179the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002180
Thomas Wouters477c8d52006-05-27 19:21:47 +00002181First some math: the largest integer that can be expressed in N base-B digits
2182is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2183case number of Python digits needed to hold it is the smallest integer n s.t.
2184
2185 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2186 BASE**n >= B**N [taking logs to base BASE]
2187 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2188
2189The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002190this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002191and the result is computed into it.
2192
2193The input string is actually treated as being in base base**i (i.e., i digits
2194are processed at a time), where two more static arrays hold:
2195
2196 convwidth_base[base] = the largest integer i such that base**i <= BASE
2197 convmultmax_base[base] = base ** convwidth_base[base]
2198
2199The first of these is the largest i such that i consecutive input digits
2200must fit in a single Python digit. The second is effectively the input
2201base we're really using.
2202
2203Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2204convmultmax_base[base], the result is "simply"
2205
2206 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2207
2208where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002209
2210Error analysis: as above, the number of Python digits `n` needed is worst-
2211case
2212
2213 n >= N * log(B)/log(BASE)
2214
2215where `N` is the number of input digits in base `B`. This is computed via
2216
2217 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2218
2219below. Two numeric concerns are how much space this can waste, and whether
2220the computed result can be too small. To be concrete, assume BASE = 2**15,
2221which is the default (and it's unlikely anyone changes that).
2222
2223Waste isn't a problem: provided the first input digit isn't 0, the difference
2224between the worst-case input with N digits and the smallest input with N
2225digits is about a factor of B, but B is small compared to BASE so at most
2226one allocated Python digit can remain unused on that count. If
2227N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2228and adding 1 returns a result 1 larger than necessary. However, that can't
2229happen: whenever B is a power of 2, long_from_binary_base() is called
2230instead, and it's impossible for B**i to be an integer power of 2**15 when
2231B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2232an exact integer when B is not a power of 2, since B**i has a prime factor
2233other than 2 in that case, but (2**15)**j's only prime factor is 2).
2234
2235The computed result can be too small if the true value of N*log(B)/log(BASE)
2236is a little bit larger than an exact integer, but due to roundoff errors (in
2237computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2238yields a numeric result a little less than that integer. Unfortunately, "how
2239close can a transcendental function get to an integer over some range?"
2240questions are generally theoretically intractable. Computer analysis via
2241continued fractions is practical: expand log(B)/log(BASE) via continued
2242fractions, giving a sequence i/j of "the best" rational approximations. Then
2243j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2244we can get very close to being in trouble, but very rarely. For example,
224576573 is a denominator in one of the continued-fraction approximations to
2246log(10)/log(2**15), and indeed:
2247
2248 >>> log(10)/log(2**15)*76573
2249 16958.000000654003
2250
2251is very close to an integer. If we were working with IEEE single-precision,
2252rounding errors could kill us. Finding worst cases in IEEE double-precision
2253requires better-than-double-precision log() functions, and Tim didn't bother.
2254Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002255new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002256This should happen extremely rarely, and in fact I don't have a test case
2257that triggers it(!). Instead the code was tested by artificially allocating
2258just 1 digit at the start, so that the copying code was exercised for every
2259digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002260***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002261 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 Py_ssize_t size_z;
Brett Cannona721aba2016-09-09 14:57:09 -07002263 int digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 int i;
2265 int convwidth;
2266 twodigits convmultmax, convmult;
2267 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002268 const char *scan, *lastdigit;
2269 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 static double log_base_BASE[37] = {0.0e0,};
2272 static int convwidth_base[37] = {0,};
2273 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 if (log_base_BASE[base] == 0.0) {
2276 twodigits convmax = base;
2277 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002278
Mark Dickinson22b20182010-05-10 21:27:53 +00002279 log_base_BASE[base] = (log((double)base) /
2280 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 for (;;) {
2282 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002283 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002285 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 convmax = next;
2287 ++i;
2288 }
2289 convmultmax_base[base] = convmax;
2290 assert(i > 0);
2291 convwidth_base[base] = i;
2292 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* Find length of the string of numeric characters. */
2295 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002296 lastdigit = str;
2297
2298 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2299 if (*scan == '_') {
2300 if (prev == '_') {
2301 /* Only one underscore allowed. */
2302 str = lastdigit + 1;
2303 goto onError;
2304 }
2305 }
2306 else {
2307 ++digits;
2308 lastdigit = scan;
2309 }
2310 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002312 }
2313 if (prev == '_') {
2314 /* Trailing underscore not allowed. */
2315 /* Set error pointer to first underscore. */
2316 str = lastdigit + 1;
2317 goto onError;
2318 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002319
Serhiy Storchaka95949422013-08-27 19:40:23 +03002320 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 * integer with this base and length. Note that there's no
2322 * need to initialize z->ob_digit -- no slot is read up before
2323 * being stored into.
2324 */
Brett Cannona721aba2016-09-09 14:57:09 -07002325 size_z = (Py_ssize_t)(digits * log_base_BASE[base]) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 /* Uncomment next line to test exceedingly rare copy code */
2327 /* size_z = 1; */
2328 assert(size_z > 0);
2329 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002330 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002332 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 /* `convwidth` consecutive input digits are treated as a single
2336 * digit in base `convmultmax`.
2337 */
2338 convwidth = convwidth_base[base];
2339 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* Work ;-) */
2342 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002343 if (*str == '_') {
2344 str++;
2345 continue;
2346 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 /* grab up to convwidth digits from the input string */
2348 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002349 for (i = 1; i < convwidth && str != scan; ++str) {
2350 if (*str == '_') {
2351 continue;
2352 }
2353 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002355 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 assert(c < PyLong_BASE);
2357 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 convmult = convmultmax;
2360 /* Calculate the shift only if we couldn't get
2361 * convwidth digits.
2362 */
2363 if (i != convwidth) {
2364 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002365 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002367 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 /* Multiply z by convmult, and add c. */
2371 pz = z->ob_digit;
2372 pzstop = pz + Py_SIZE(z);
2373 for (; pz < pzstop; ++pz) {
2374 c += (twodigits)*pz * convmult;
2375 *pz = (digit)(c & PyLong_MASK);
2376 c >>= PyLong_SHIFT;
2377 }
2378 /* carry off the current end? */
2379 if (c) {
2380 assert(c < PyLong_BASE);
2381 if (Py_SIZE(z) < size_z) {
2382 *pz = (digit)c;
2383 ++Py_SIZE(z);
2384 }
2385 else {
2386 PyLongObject *tmp;
2387 /* Extremely rare. Get more space. */
2388 assert(Py_SIZE(z) == size_z);
2389 tmp = _PyLong_New(size_z + 1);
2390 if (tmp == NULL) {
2391 Py_DECREF(z);
2392 return NULL;
2393 }
2394 memcpy(tmp->ob_digit,
2395 z->ob_digit,
2396 sizeof(digit) * size_z);
2397 Py_DECREF(z);
2398 z = tmp;
2399 z->ob_digit[size_z] = (digit)c;
2400 ++size_z;
2401 }
2402 }
2403 }
2404 }
Brett Cannona721aba2016-09-09 14:57:09 -07002405 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002407 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 if (error_if_nonzero) {
2409 /* reset the base to 0, else the exception message
2410 doesn't make too much sense */
2411 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002412 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002414 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 /* there might still be other problems, therefore base
2416 remains zero here for the same reason */
2417 }
Brett Cannona721aba2016-09-09 14:57:09 -07002418 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002420 }
2421 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002423 }
2424 while (*str && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002426 }
2427 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002429 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002431 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002432 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002433 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002434 }
2435 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002436 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002437 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002438 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002439
Mark Dickinson22b20182010-05-10 21:27:53 +00002440 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002441 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002442 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002443 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 Py_XDECREF(z);
2445 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2446 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002447 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002451 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 base, strobj);
2453 Py_DECREF(strobj);
2454 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002455}
2456
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002457/* Since PyLong_FromString doesn't have a length parameter,
2458 * check here for possible NULs in the string.
2459 *
2460 * Reports an invalid literal as a bytes object.
2461 */
2462PyObject *
2463_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2464{
2465 PyObject *result, *strobj;
2466 char *end = NULL;
2467
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002468 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002469 if (end == NULL || (result != NULL && end == s + len))
2470 return result;
2471 Py_XDECREF(result);
2472 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2473 if (strobj != NULL) {
2474 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002475 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002476 base, strobj);
2477 Py_DECREF(strobj);
2478 }
2479 return NULL;
2480}
2481
Guido van Rossum9e896b32000-04-05 20:11:21 +00002482PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002483PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002484{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002485 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2486 if (unicode == NULL)
2487 return NULL;
2488 v = PyLong_FromUnicodeObject(unicode, base);
2489 Py_DECREF(unicode);
2490 return v;
2491}
2492
2493PyObject *
2494PyLong_FromUnicodeObject(PyObject *u, int base)
2495{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002496 PyObject *result, *asciidig;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002497 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002498 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002501 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002504 if (buffer == NULL) {
2505 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002506 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2507 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002509 else {
2510 result = PyLong_FromString(buffer, &end, base);
2511 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2512 Py_DECREF(asciidig);
2513 return result;
2514 }
2515 Py_DECREF(asciidig);
2516 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002517 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002518 PyErr_Format(PyExc_ValueError,
2519 "invalid literal for int() with base %d: %.200R",
2520 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002521 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002522}
2523
Tim Peters9f688bf2000-07-07 15:53:28 +00002524/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002525static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002527static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002528
Serhiy Storchaka95949422013-08-27 19:40:23 +03002529/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002530
Guido van Rossume32e0141992-01-19 16:31:05 +00002531static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002532long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002534{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002535 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 if (size_b == 0) {
2539 PyErr_SetString(PyExc_ZeroDivisionError,
2540 "integer division or modulo by zero");
2541 return -1;
2542 }
2543 if (size_a < size_b ||
2544 (size_a == size_b &&
2545 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2546 /* |a| < |b|. */
2547 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2548 if (*pdiv == NULL)
2549 return -1;
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002550 *prem = (PyLongObject *)long_long((PyObject *)a);
2551 if (*prem == NULL) {
2552 Py_CLEAR(*pdiv);
2553 return -1;
2554 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 return 0;
2556 }
2557 if (size_b == 1) {
2558 digit rem = 0;
2559 z = divrem1(a, b->ob_digit[0], &rem);
2560 if (z == NULL)
2561 return -1;
2562 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2563 if (*prem == NULL) {
2564 Py_DECREF(z);
2565 return -1;
2566 }
2567 }
2568 else {
2569 z = x_divrem(a, b, prem);
2570 if (z == NULL)
2571 return -1;
2572 }
2573 /* Set the signs.
2574 The quotient z has the sign of a*b;
2575 the remainder r has the sign of a,
2576 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002577 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2578 _PyLong_Negate(&z);
2579 if (z == NULL) {
2580 Py_CLEAR(*prem);
2581 return -1;
2582 }
2583 }
2584 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2585 _PyLong_Negate(prem);
2586 if (*prem == NULL) {
2587 Py_DECREF(z);
2588 Py_CLEAR(*prem);
2589 return -1;
2590 }
2591 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 *pdiv = maybe_small_long(z);
2593 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002594}
2595
Serhiy Storchaka95949422013-08-27 19:40:23 +03002596/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002597 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002598
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002599static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002600x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 PyLongObject *v, *w, *a;
2603 Py_ssize_t i, k, size_v, size_w;
2604 int d;
2605 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2606 twodigits vv;
2607 sdigit zhi;
2608 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2611 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2612 handle the special case when the initial estimate q for a quotient
2613 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2614 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002617 size_v = Py_ABS(Py_SIZE(v1));
2618 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2620 v = _PyLong_New(size_v+1);
2621 if (v == NULL) {
2622 *prem = NULL;
2623 return NULL;
2624 }
2625 w = _PyLong_New(size_w);
2626 if (w == NULL) {
2627 Py_DECREF(v);
2628 *prem = NULL;
2629 return NULL;
2630 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2633 shift v1 left by the same amount. Results go into w and v. */
2634 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2635 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2636 assert(carry == 0);
2637 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2638 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2639 v->ob_digit[size_v] = carry;
2640 size_v++;
2641 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2644 at most (and usually exactly) k = size_v - size_w digits. */
2645 k = size_v - size_w;
2646 assert(k >= 0);
2647 a = _PyLong_New(k);
2648 if (a == NULL) {
2649 Py_DECREF(w);
2650 Py_DECREF(v);
2651 *prem = NULL;
2652 return NULL;
2653 }
2654 v0 = v->ob_digit;
2655 w0 = w->ob_digit;
2656 wm1 = w0[size_w-1];
2657 wm2 = w0[size_w-2];
2658 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2659 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2660 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002663 Py_DECREF(a);
2664 Py_DECREF(w);
2665 Py_DECREF(v);
2666 *prem = NULL;
2667 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002668 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 /* estimate quotient digit q; may overestimate by 1 (rare) */
2671 vtop = vk[size_w];
2672 assert(vtop <= wm1);
2673 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2674 q = (digit)(vv / wm1);
2675 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2676 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2677 | vk[size_w-2])) {
2678 --q;
2679 r += wm1;
2680 if (r >= PyLong_BASE)
2681 break;
2682 }
2683 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2686 zhi = 0;
2687 for (i = 0; i < size_w; ++i) {
2688 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2689 -PyLong_BASE * q <= z < PyLong_BASE */
2690 z = (sdigit)vk[i] + zhi -
2691 (stwodigits)q * (stwodigits)w0[i];
2692 vk[i] = (digit)z & PyLong_MASK;
2693 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002694 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 /* add w back if q was too large (this branch taken rarely) */
2698 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2699 if ((sdigit)vtop + zhi < 0) {
2700 carry = 0;
2701 for (i = 0; i < size_w; ++i) {
2702 carry += vk[i] + w0[i];
2703 vk[i] = carry & PyLong_MASK;
2704 carry >>= PyLong_SHIFT;
2705 }
2706 --q;
2707 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 /* store quotient digit */
2710 assert(q < PyLong_BASE);
2711 *--ak = q;
2712 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 /* unshift remainder; we reuse w to store the result */
2715 carry = v_rshift(w0, v0, size_w, d);
2716 assert(carry==0);
2717 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 *prem = long_normalize(w);
2720 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002721}
2722
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002723/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2724 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2725 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2726 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2727 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2728 -1.0. */
2729
2730/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2731#if DBL_MANT_DIG == 53
2732#define EXP2_DBL_MANT_DIG 9007199254740992.0
2733#else
2734#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2735#endif
2736
2737double
2738_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2741 /* See below for why x_digits is always large enough. */
2742 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2743 double dx;
2744 /* Correction term for round-half-to-even rounding. For a digit x,
2745 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2746 multiple of 4, rounding ties to a multiple of 8. */
2747 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002748
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002749 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 if (a_size == 0) {
2751 /* Special case for 0: significand 0.0, exponent 0. */
2752 *e = 0;
2753 return 0.0;
2754 }
2755 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2756 /* The following is an overflow-free version of the check
2757 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2758 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2759 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2760 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002761 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2765 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 Number of digits needed for result: write // for floor division.
2768 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2777 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2780 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2781 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 in both cases.
2788 */
2789 if (a_bits <= DBL_MANT_DIG + 2) {
2790 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2791 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2792 x_size = 0;
2793 while (x_size < shift_digits)
2794 x_digits[x_size++] = 0;
2795 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2796 (int)shift_bits);
2797 x_size += a_size;
2798 x_digits[x_size++] = rem;
2799 }
2800 else {
2801 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2802 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2803 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2804 a_size - shift_digits, (int)shift_bits);
2805 x_size = a_size - shift_digits;
2806 /* For correct rounding below, we need the least significant
2807 bit of x to be 'sticky' for this shift: if any of the bits
2808 shifted out was nonzero, we set the least significant bit
2809 of x. */
2810 if (rem)
2811 x_digits[0] |= 1;
2812 else
2813 while (shift_digits > 0)
2814 if (a->ob_digit[--shift_digits]) {
2815 x_digits[0] |= 1;
2816 break;
2817 }
2818 }
Victor Stinner63941882011-09-29 00:42:28 +02002819 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 /* Round, and convert to double. */
2822 x_digits[0] += half_even_correction[x_digits[0] & 7];
2823 dx = x_digits[--x_size];
2824 while (x_size > 0)
2825 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 /* Rescale; make correction if result is 1.0. */
2828 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2829 if (dx == 1.0) {
2830 if (a_bits == PY_SSIZE_T_MAX)
2831 goto overflow;
2832 dx = 0.5;
2833 a_bits += 1;
2834 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 *e = a_bits;
2837 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002838
2839 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 /* exponent > PY_SSIZE_T_MAX */
2841 PyErr_SetString(PyExc_OverflowError,
2842 "huge integer: number of bits overflows a Py_ssize_t");
2843 *e = 0;
2844 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002845}
2846
Serhiy Storchaka95949422013-08-27 19:40:23 +03002847/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002848 using the round-half-to-even rule in the case of a tie. */
2849
2850double
2851PyLong_AsDouble(PyObject *v)
2852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 Py_ssize_t exponent;
2854 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002855
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002856 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 PyErr_BadInternalCall();
2858 return -1.0;
2859 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002860 if (!PyLong_Check(v)) {
2861 PyErr_SetString(PyExc_TypeError, "an integer is required");
2862 return -1.0;
2863 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002864 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002865 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002866 to double. This improves performance of FP/long operations
2867 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002868 */
2869 return (double)MEDIUM_VALUE((PyLongObject *)v);
2870 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2872 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2873 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002874 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 return -1.0;
2876 }
2877 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002878}
2879
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002880/* Methods */
2881
2882static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002883long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002886}
2887
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002888static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002889long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 if (Py_SIZE(a) != Py_SIZE(b)) {
2894 sign = Py_SIZE(a) - Py_SIZE(b);
2895 }
2896 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002897 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2899 ;
2900 if (i < 0)
2901 sign = 0;
2902 else {
2903 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2904 if (Py_SIZE(a) < 0)
2905 sign = -sign;
2906 }
2907 }
2908 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002909}
2910
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002911#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002913
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002914static PyObject *
2915long_richcompare(PyObject *self, PyObject *other, int op)
2916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 int result;
2918 PyObject *v;
2919 CHECK_BINOP(self, other);
2920 if (self == other)
2921 result = 0;
2922 else
2923 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2924 /* Convert the return value to a Boolean */
2925 switch (op) {
2926 case Py_EQ:
2927 v = TEST_COND(result == 0);
2928 break;
2929 case Py_NE:
2930 v = TEST_COND(result != 0);
2931 break;
2932 case Py_LE:
2933 v = TEST_COND(result <= 0);
2934 break;
2935 case Py_GE:
2936 v = TEST_COND(result >= 0);
2937 break;
2938 case Py_LT:
2939 v = TEST_COND(result == -1);
2940 break;
2941 case Py_GT:
2942 v = TEST_COND(result == 1);
2943 break;
2944 default:
2945 PyErr_BadArgument();
2946 return NULL;
2947 }
2948 Py_INCREF(v);
2949 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002950}
2951
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002952static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002953long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002954{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002955 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 Py_ssize_t i;
2957 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 i = Py_SIZE(v);
2960 switch(i) {
2961 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2962 case 0: return 0;
2963 case 1: return v->ob_digit[0];
2964 }
2965 sign = 1;
2966 x = 0;
2967 if (i < 0) {
2968 sign = -1;
2969 i = -(i);
2970 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002972 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2973 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2974 _PyHASH_MODULUS.
2975
2976 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2977 amounts to a rotation of the bits of x. To see this, write
2978
2979 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2980
2981 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2982 PyLong_SHIFT bits of x (those that are shifted out of the
2983 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2984 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2985 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2986 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2987 congruent to y modulo _PyHASH_MODULUS. So
2988
2989 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2990
2991 The right-hand side is just the result of rotating the
2992 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2993 not all _PyHASH_BITS bits of x are 1s, the same is true
2994 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2995 the reduction of x*2**PyLong_SHIFT modulo
2996 _PyHASH_MODULUS. */
2997 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2998 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003000 if (x >= _PyHASH_MODULUS)
3001 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 }
3003 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003004 if (x == (Py_uhash_t)-1)
3005 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003006 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003007}
3008
3009
Serhiy Storchaka95949422013-08-27 19:40:23 +03003010/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003011
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003012static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003013x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003014{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003015 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 PyLongObject *z;
3017 Py_ssize_t i;
3018 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 /* Ensure a is the larger of the two: */
3021 if (size_a < size_b) {
3022 { PyLongObject *temp = a; a = b; b = temp; }
3023 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003024 size_a = size_b;
3025 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 }
3027 z = _PyLong_New(size_a+1);
3028 if (z == NULL)
3029 return NULL;
3030 for (i = 0; i < size_b; ++i) {
3031 carry += a->ob_digit[i] + b->ob_digit[i];
3032 z->ob_digit[i] = carry & PyLong_MASK;
3033 carry >>= PyLong_SHIFT;
3034 }
3035 for (; i < size_a; ++i) {
3036 carry += a->ob_digit[i];
3037 z->ob_digit[i] = carry & PyLong_MASK;
3038 carry >>= PyLong_SHIFT;
3039 }
3040 z->ob_digit[i] = carry;
3041 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003042}
3043
3044/* Subtract the absolute values of two integers. */
3045
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003046static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003047x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003048{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003049 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 PyLongObject *z;
3051 Py_ssize_t i;
3052 int sign = 1;
3053 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 /* Ensure a is the larger of the two: */
3056 if (size_a < size_b) {
3057 sign = -1;
3058 { PyLongObject *temp = a; a = b; b = temp; }
3059 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003060 size_a = size_b;
3061 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 }
3063 else if (size_a == size_b) {
3064 /* Find highest digit where a and b differ: */
3065 i = size_a;
3066 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3067 ;
3068 if (i < 0)
3069 return (PyLongObject *)PyLong_FromLong(0);
3070 if (a->ob_digit[i] < b->ob_digit[i]) {
3071 sign = -1;
3072 { PyLongObject *temp = a; a = b; b = temp; }
3073 }
3074 size_a = size_b = i+1;
3075 }
3076 z = _PyLong_New(size_a);
3077 if (z == NULL)
3078 return NULL;
3079 for (i = 0; i < size_b; ++i) {
3080 /* The following assumes unsigned arithmetic
3081 works module 2**N for some N>PyLong_SHIFT. */
3082 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3083 z->ob_digit[i] = borrow & PyLong_MASK;
3084 borrow >>= PyLong_SHIFT;
3085 borrow &= 1; /* Keep only one sign bit */
3086 }
3087 for (; i < size_a; ++i) {
3088 borrow = a->ob_digit[i] - borrow;
3089 z->ob_digit[i] = borrow & PyLong_MASK;
3090 borrow >>= PyLong_SHIFT;
3091 borrow &= 1; /* Keep only one sign bit */
3092 }
3093 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003094 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003095 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003096 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003098}
3099
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003100static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003101long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003106
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003107 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
3109 MEDIUM_VALUE(b));
3110 return result;
3111 }
3112 if (Py_SIZE(a) < 0) {
3113 if (Py_SIZE(b) < 0) {
3114 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003115 if (z != NULL) {
3116 /* x_add received at least one multiple-digit int,
3117 and thus z must be a multiple-digit int.
3118 That also means z is not an element of
3119 small_ints, so negating it in-place is safe. */
3120 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003122 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 }
3124 else
3125 z = x_sub(b, a);
3126 }
3127 else {
3128 if (Py_SIZE(b) < 0)
3129 z = x_sub(a, b);
3130 else
3131 z = x_add(a, b);
3132 }
3133 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003134}
3135
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003136static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003137long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003142
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003143 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 PyObject* r;
3145 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
3146 return r;
3147 }
3148 if (Py_SIZE(a) < 0) {
3149 if (Py_SIZE(b) < 0)
3150 z = x_sub(a, b);
3151 else
3152 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003153 if (z != NULL) {
3154 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 }
3158 else {
3159 if (Py_SIZE(b) < 0)
3160 z = x_add(a, b);
3161 else
3162 z = x_sub(a, b);
3163 }
3164 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003165}
3166
Tim Peters5af4e6c2002-08-12 02:31:19 +00003167/* Grade school multiplication, ignoring the signs.
3168 * Returns the absolute value of the product, or NULL if error.
3169 */
3170static PyLongObject *
3171x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003174 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3175 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 z = _PyLong_New(size_a + size_b);
3179 if (z == NULL)
3180 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3183 if (a == b) {
3184 /* Efficient squaring per HAC, Algorithm 14.16:
3185 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3186 * Gives slightly less than a 2x speedup when a == b,
3187 * via exploiting that each entry in the multiplication
3188 * pyramid appears twice (except for the size_a squares).
3189 */
3190 for (i = 0; i < size_a; ++i) {
3191 twodigits carry;
3192 twodigits f = a->ob_digit[i];
3193 digit *pz = z->ob_digit + (i << 1);
3194 digit *pa = a->ob_digit + i + 1;
3195 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003198 Py_DECREF(z);
3199 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003200 });
Tim Peters0973b992004-08-29 22:16:50 +00003201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 carry = *pz + f * f;
3203 *pz++ = (digit)(carry & PyLong_MASK);
3204 carry >>= PyLong_SHIFT;
3205 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 /* Now f is added in twice in each column of the
3208 * pyramid it appears. Same as adding f<<1 once.
3209 */
3210 f <<= 1;
3211 while (pa < paend) {
3212 carry += *pz + *pa++ * f;
3213 *pz++ = (digit)(carry & PyLong_MASK);
3214 carry >>= PyLong_SHIFT;
3215 assert(carry <= (PyLong_MASK << 1));
3216 }
3217 if (carry) {
3218 carry += *pz;
3219 *pz++ = (digit)(carry & PyLong_MASK);
3220 carry >>= PyLong_SHIFT;
3221 }
3222 if (carry)
3223 *pz += (digit)(carry & PyLong_MASK);
3224 assert((carry >> PyLong_SHIFT) == 0);
3225 }
3226 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003227 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 for (i = 0; i < size_a; ++i) {
3229 twodigits carry = 0;
3230 twodigits f = a->ob_digit[i];
3231 digit *pz = z->ob_digit + i;
3232 digit *pb = b->ob_digit;
3233 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003236 Py_DECREF(z);
3237 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003238 });
Tim Peters0973b992004-08-29 22:16:50 +00003239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 while (pb < pbend) {
3241 carry += *pz + *pb++ * f;
3242 *pz++ = (digit)(carry & PyLong_MASK);
3243 carry >>= PyLong_SHIFT;
3244 assert(carry <= PyLong_MASK);
3245 }
3246 if (carry)
3247 *pz += (digit)(carry & PyLong_MASK);
3248 assert((carry >> PyLong_SHIFT) == 0);
3249 }
3250 }
3251 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003252}
3253
3254/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003255 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003256 split, and sets low and high such that abs(n) == (high << size) + low,
3257 viewing the shift as being by digits. The sign bit is ignored, and
3258 the return values are >= 0.
3259 Returns 0 on success, -1 on failure.
3260*/
3261static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003262kmul_split(PyLongObject *n,
3263 Py_ssize_t size,
3264 PyLongObject **high,
3265 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 PyLongObject *hi, *lo;
3268 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003269 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003270
Victor Stinner640c35c2013-06-04 23:14:37 +02003271 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 if ((hi = _PyLong_New(size_hi)) == NULL)
3275 return -1;
3276 if ((lo = _PyLong_New(size_lo)) == NULL) {
3277 Py_DECREF(hi);
3278 return -1;
3279 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3282 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 *high = long_normalize(hi);
3285 *low = long_normalize(lo);
3286 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003287}
3288
Tim Peters60004642002-08-12 22:01:34 +00003289static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3290
Tim Peters5af4e6c2002-08-12 02:31:19 +00003291/* Karatsuba multiplication. Ignores the input signs, and returns the
3292 * absolute value of the product (or NULL if error).
3293 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3294 */
3295static PyLongObject *
3296k_mul(PyLongObject *a, PyLongObject *b)
3297{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003298 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3299 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 PyLongObject *ah = NULL;
3301 PyLongObject *al = NULL;
3302 PyLongObject *bh = NULL;
3303 PyLongObject *bl = NULL;
3304 PyLongObject *ret = NULL;
3305 PyLongObject *t1, *t2, *t3;
3306 Py_ssize_t shift; /* the number of digits we split off */
3307 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3310 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3311 * Then the original product is
3312 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3313 * By picking X to be a power of 2, "*X" is just shifting, and it's
3314 * been reduced to 3 multiplies on numbers half the size.
3315 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 /* We want to split based on the larger number; fiddle so that b
3318 * is largest.
3319 */
3320 if (asize > bsize) {
3321 t1 = a;
3322 a = b;
3323 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 i = asize;
3326 asize = bsize;
3327 bsize = i;
3328 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 /* Use gradeschool math when either number is too small. */
3331 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3332 if (asize <= i) {
3333 if (asize == 0)
3334 return (PyLongObject *)PyLong_FromLong(0);
3335 else
3336 return x_mul(a, b);
3337 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 /* If a is small compared to b, splitting on b gives a degenerate
3340 * case with ah==0, and Karatsuba may be (even much) less efficient
3341 * than "grade school" then. However, we can still win, by viewing
3342 * b as a string of "big digits", each of width a->ob_size. That
3343 * leads to a sequence of balanced calls to k_mul.
3344 */
3345 if (2 * asize <= bsize)
3346 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 /* Split a & b into hi & lo pieces. */
3349 shift = bsize >> 1;
3350 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3351 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 if (a == b) {
3354 bh = ah;
3355 bl = al;
3356 Py_INCREF(bh);
3357 Py_INCREF(bl);
3358 }
3359 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 /* The plan:
3362 * 1. Allocate result space (asize + bsize digits: that's always
3363 * enough).
3364 * 2. Compute ah*bh, and copy into result at 2*shift.
3365 * 3. Compute al*bl, and copy into result at 0. Note that this
3366 * can't overlap with #2.
3367 * 4. Subtract al*bl from the result, starting at shift. This may
3368 * underflow (borrow out of the high digit), but we don't care:
3369 * we're effectively doing unsigned arithmetic mod
3370 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3371 * borrows and carries out of the high digit can be ignored.
3372 * 5. Subtract ah*bh from the result, starting at shift.
3373 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3374 * at shift.
3375 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 /* 1. Allocate result space. */
3378 ret = _PyLong_New(asize + bsize);
3379 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003380#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 /* Fill with trash, to catch reference to uninitialized digits. */
3382 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003383#endif
Tim Peters44121a62002-08-12 06:17:58 +00003384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3386 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3387 assert(Py_SIZE(t1) >= 0);
3388 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3389 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3390 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 /* Zero-out the digits higher than the ah*bh copy. */
3393 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3394 if (i)
3395 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3396 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 /* 3. t2 <- al*bl, and copy into the low digits. */
3399 if ((t2 = k_mul(al, bl)) == NULL) {
3400 Py_DECREF(t1);
3401 goto fail;
3402 }
3403 assert(Py_SIZE(t2) >= 0);
3404 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3405 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 /* Zero out remaining digits. */
3408 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3409 if (i)
3410 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3413 * because it's fresher in cache.
3414 */
3415 i = Py_SIZE(ret) - shift; /* # digits after shift */
3416 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3417 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3420 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3423 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3424 Py_DECREF(ah);
3425 Py_DECREF(al);
3426 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 if (a == b) {
3429 t2 = t1;
3430 Py_INCREF(t2);
3431 }
3432 else if ((t2 = x_add(bh, bl)) == NULL) {
3433 Py_DECREF(t1);
3434 goto fail;
3435 }
3436 Py_DECREF(bh);
3437 Py_DECREF(bl);
3438 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 t3 = k_mul(t1, t2);
3441 Py_DECREF(t1);
3442 Py_DECREF(t2);
3443 if (t3 == NULL) goto fail;
3444 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 /* Add t3. It's not obvious why we can't run out of room here.
3447 * See the (*) comment after this function.
3448 */
3449 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3450 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003453
Mark Dickinson22b20182010-05-10 21:27:53 +00003454 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 Py_XDECREF(ret);
3456 Py_XDECREF(ah);
3457 Py_XDECREF(al);
3458 Py_XDECREF(bh);
3459 Py_XDECREF(bl);
3460 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003461}
3462
Tim Petersd6974a52002-08-13 20:37:51 +00003463/* (*) Why adding t3 can't "run out of room" above.
3464
Tim Petersab86c2b2002-08-15 20:06:00 +00003465Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3466to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003467
Tim Petersab86c2b2002-08-15 20:06:00 +000034681. For any integer i, i = c(i/2) + f(i/2). In particular,
3469 bsize = c(bsize/2) + f(bsize/2).
34702. shift = f(bsize/2)
34713. asize <= bsize
34724. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3473 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003474
Tim Petersab86c2b2002-08-15 20:06:00 +00003475We allocated asize + bsize result digits, and add t3 into them at an offset
3476of shift. This leaves asize+bsize-shift allocated digit positions for t3
3477to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3478asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003479
Tim Petersab86c2b2002-08-15 20:06:00 +00003480bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3481at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003482
Tim Petersab86c2b2002-08-15 20:06:00 +00003483If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3484digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3485most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003486
Tim Petersab86c2b2002-08-15 20:06:00 +00003487The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003488
Tim Petersab86c2b2002-08-15 20:06:00 +00003489 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003490
Tim Petersab86c2b2002-08-15 20:06:00 +00003491and we have asize + c(bsize/2) available digit positions. We need to show
3492this is always enough. An instance of c(bsize/2) cancels out in both, so
3493the question reduces to whether asize digits is enough to hold
3494(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3495then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3496asize 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 +00003497digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003498asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003499c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3500is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3501bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003502
Tim Peters48d52c02002-08-14 17:07:32 +00003503Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3504clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3505ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003506*/
3507
Tim Peters60004642002-08-12 22:01:34 +00003508/* b has at least twice the digits of a, and a is big enough that Karatsuba
3509 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3510 * of slices, each with a->ob_size digits, and multiply the slices by a,
3511 * one at a time. This gives k_mul balanced inputs to work with, and is
3512 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003513 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003514 * single-width slice overlap between successive partial sums).
3515 */
3516static PyLongObject *
3517k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3518{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003519 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3520 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 Py_ssize_t nbdone; /* # of b digits already multiplied */
3522 PyLongObject *ret;
3523 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 assert(asize > KARATSUBA_CUTOFF);
3526 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 /* Allocate result space, and zero it out. */
3529 ret = _PyLong_New(asize + bsize);
3530 if (ret == NULL)
3531 return NULL;
3532 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 /* Successive slices of b are copied into bslice. */
3535 bslice = _PyLong_New(asize);
3536 if (bslice == NULL)
3537 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 nbdone = 0;
3540 while (bsize > 0) {
3541 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003542 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 /* Multiply the next slice of b by a. */
3545 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3546 nbtouse * sizeof(digit));
3547 Py_SIZE(bslice) = nbtouse;
3548 product = k_mul(a, bslice);
3549 if (product == NULL)
3550 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 /* Add into result. */
3553 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3554 product->ob_digit, Py_SIZE(product));
3555 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 bsize -= nbtouse;
3558 nbdone += nbtouse;
3559 }
Tim Peters60004642002-08-12 22:01:34 +00003560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 Py_DECREF(bslice);
3562 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003563
Mark Dickinson22b20182010-05-10 21:27:53 +00003564 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 Py_DECREF(ret);
3566 Py_XDECREF(bslice);
3567 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003568}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003569
3570static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003571long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003578 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003580 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 z = k_mul(a, b);
3584 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003585 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3586 _PyLong_Negate(&z);
3587 if (z == NULL)
3588 return NULL;
3589 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003591}
3592
Yury Selivanove0b23092016-02-11 10:26:27 -05003593/* Fast modulo division for single-digit longs. */
3594static PyObject *
3595fast_mod(PyLongObject *a, PyLongObject *b)
3596{
3597 sdigit left = a->ob_digit[0];
3598 sdigit right = b->ob_digit[0];
3599 sdigit mod;
3600
3601 assert(Py_ABS(Py_SIZE(a)) == 1);
3602 assert(Py_ABS(Py_SIZE(b)) == 1);
3603
3604 if (Py_SIZE(a) == Py_SIZE(b)) {
3605 /* 'a' and 'b' have the same sign. */
3606 mod = left % right;
3607 }
3608 else {
3609 /* Either 'a' or 'b' is negative. */
3610 mod = right - 1 - (left - 1) % right;
3611 }
3612
Victor Stinnerf963c132016-03-23 18:36:54 +01003613 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003614}
3615
3616/* Fast floor division for single-digit longs. */
3617static PyObject *
3618fast_floor_div(PyLongObject *a, PyLongObject *b)
3619{
3620 sdigit left = a->ob_digit[0];
3621 sdigit right = b->ob_digit[0];
3622 sdigit div;
3623
3624 assert(Py_ABS(Py_SIZE(a)) == 1);
3625 assert(Py_ABS(Py_SIZE(b)) == 1);
3626
3627 if (Py_SIZE(a) == Py_SIZE(b)) {
3628 /* 'a' and 'b' have the same sign. */
3629 div = left / right;
3630 }
3631 else {
3632 /* Either 'a' or 'b' is negative. */
3633 div = -1 - (left - 1) / right;
3634 }
3635
3636 return PyLong_FromLong(div);
3637}
3638
Guido van Rossume32e0141992-01-19 16:31:05 +00003639/* The / and % operators are now defined in terms of divmod().
3640 The expression a mod b has the value a - b*floor(a/b).
3641 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003642 |a| by |b|, with the sign of a. This is also expressed
3643 as a - b*trunc(a/b), if trunc truncates towards zero.
3644 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 a b a rem b a mod b
3646 13 10 3 3
3647 -13 10 -3 7
3648 13 -10 3 -7
3649 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003650 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003651 have different signs. We then subtract one from the 'div'
3652 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003653
Tim Peters47e52ee2004-08-30 02:44:38 +00003654/* Compute
3655 * *pdiv, *pmod = divmod(v, w)
3656 * NULL can be passed for pdiv or pmod, in which case that part of
3657 * the result is simply thrown away. The caller owns a reference to
3658 * each of these it requests (does not pass NULL for).
3659 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003660static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003661l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003665
Yury Selivanove0b23092016-02-11 10:26:27 -05003666 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3667 /* Fast path for single-digit longs */
3668 div = NULL;
3669 if (pdiv != NULL) {
3670 div = (PyLongObject *)fast_floor_div(v, w);
3671 if (div == NULL) {
3672 return -1;
3673 }
3674 }
3675 if (pmod != NULL) {
3676 mod = (PyLongObject *)fast_mod(v, w);
3677 if (mod == NULL) {
3678 Py_XDECREF(div);
3679 return -1;
3680 }
3681 *pmod = mod;
3682 }
3683 if (pdiv != NULL) {
3684 /* We only want to set `*pdiv` when `*pmod` is
3685 set successfully. */
3686 *pdiv = div;
3687 }
3688 return 0;
3689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 if (long_divrem(v, w, &div, &mod) < 0)
3691 return -1;
3692 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3693 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3694 PyLongObject *temp;
3695 PyLongObject *one;
3696 temp = (PyLongObject *) long_add(mod, w);
3697 Py_DECREF(mod);
3698 mod = temp;
3699 if (mod == NULL) {
3700 Py_DECREF(div);
3701 return -1;
3702 }
3703 one = (PyLongObject *) PyLong_FromLong(1L);
3704 if (one == NULL ||
3705 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3706 Py_DECREF(mod);
3707 Py_DECREF(div);
3708 Py_XDECREF(one);
3709 return -1;
3710 }
3711 Py_DECREF(one);
3712 Py_DECREF(div);
3713 div = temp;
3714 }
3715 if (pdiv != NULL)
3716 *pdiv = div;
3717 else
3718 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 if (pmod != NULL)
3721 *pmod = mod;
3722 else
3723 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003726}
3727
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003728static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003729long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003734
3735 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3736 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3737 }
3738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3740 div = NULL;
3741 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003742}
3743
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003744/* PyLong/PyLong -> float, with correctly rounded result. */
3745
3746#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3747#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3748
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003749static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003750long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 PyLongObject *a, *b, *x;
3753 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3754 digit mask, low;
3755 int inexact, negate, a_is_small, b_is_small;
3756 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 CHECK_BINOP(v, w);
3759 a = (PyLongObject *)v;
3760 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 /*
3763 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3766 1. choose a suitable integer 'shift'
3767 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3768 3. adjust x for correct rounding
3769 4. convert x to a double dx with the same value
3770 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3775 returns either 0.0 or -0.0, depending on the sign of b. For a and
3776 b both nonzero, ignore signs of a and b, and add the sign back in
3777 at the end. Now write a_bits and b_bits for the bit lengths of a
3778 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3779 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3784 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3785 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3786 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 1. The integer 'shift' is chosen so that x has the right number of
3791 bits for a double, plus two or three extra bits that will be used
3792 in the rounding decisions. Writing a_bits and b_bits for the
3793 number of significant bits in a and b respectively, a
3794 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 This is fine in the usual case, but if a/b is smaller than the
3799 smallest normal float then it can lead to double rounding on an
3800 IEEE 754 platform, giving incorrectly rounded results. So we
3801 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 2. The quantity x is computed by first shifting a (left -shift bits
3806 if shift <= 0, right shift bits if shift > 0) and then dividing by
3807 b. For both the shift and the division, we keep track of whether
3808 the result is inexact, in a flag 'inexact'; this information is
3809 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 With the choice of shift above, together with our assumption that
3812 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3813 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3816 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 For float representability, we need x/2**extra_bits <
3821 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3822 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 To round, we just modify the bottom digit of x in-place; this can
3827 end up giving a digit with value > PyLONG_MASK, but that's not a
3828 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 With the original choices for shift above, extra_bits will always
3831 be 2 or 3. Then rounding under the round-half-to-even rule, we
3832 round up iff the most significant of the extra bits is 1, and
3833 either: (a) the computation of x in step 2 had an inexact result,
3834 or (b) at least one other of the extra bits is 1, or (c) the least
3835 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 4. Conversion to a double is straightforward; all floating-point
3838 operations involved in the conversion are exact, so there's no
3839 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003841 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3842 The result will always be exactly representable as a double, except
3843 in the case that it overflows. To avoid dependence on the exact
3844 behaviour of ldexp on overflow, we check for overflow before
3845 applying ldexp. The result of ldexp is adjusted for sign before
3846 returning.
3847 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003850 a_size = Py_ABS(Py_SIZE(a));
3851 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3853 if (b_size == 0) {
3854 PyErr_SetString(PyExc_ZeroDivisionError,
3855 "division by zero");
3856 goto error;
3857 }
3858 if (a_size == 0)
3859 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 /* Fast path for a and b small (exactly representable in a double).
3862 Relies on floating-point division being correctly rounded; results
3863 may be subject to double rounding on x86 machines that operate with
3864 the x87 FPU set to 64-bit precision. */
3865 a_is_small = a_size <= MANT_DIG_DIGITS ||
3866 (a_size == MANT_DIG_DIGITS+1 &&
3867 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3868 b_is_small = b_size <= MANT_DIG_DIGITS ||
3869 (b_size == MANT_DIG_DIGITS+1 &&
3870 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3871 if (a_is_small && b_is_small) {
3872 double da, db;
3873 da = a->ob_digit[--a_size];
3874 while (a_size > 0)
3875 da = da * PyLong_BASE + a->ob_digit[--a_size];
3876 db = b->ob_digit[--b_size];
3877 while (b_size > 0)
3878 db = db * PyLong_BASE + b->ob_digit[--b_size];
3879 result = da / db;
3880 goto success;
3881 }
Tim Peterse2a60002001-09-04 06:17:36 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 /* Catch obvious cases of underflow and overflow */
3884 diff = a_size - b_size;
3885 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3886 /* Extreme overflow */
3887 goto overflow;
3888 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3889 /* Extreme underflow */
3890 goto underflow_or_zero;
3891 /* Next line is now safe from overflowing a Py_ssize_t */
3892 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3893 bits_in_digit(b->ob_digit[b_size - 1]);
3894 /* Now diff = a_bits - b_bits. */
3895 if (diff > DBL_MAX_EXP)
3896 goto overflow;
3897 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3898 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003901 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 /* x = abs(a * 2**-shift) */
3906 if (shift <= 0) {
3907 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3908 digit rem;
3909 /* x = a << -shift */
3910 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3911 /* In practice, it's probably impossible to end up
3912 here. Both a and b would have to be enormous,
3913 using close to SIZE_T_MAX bytes of memory each. */
3914 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003915 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 goto error;
3917 }
3918 x = _PyLong_New(a_size + shift_digits + 1);
3919 if (x == NULL)
3920 goto error;
3921 for (i = 0; i < shift_digits; i++)
3922 x->ob_digit[i] = 0;
3923 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3924 a_size, -shift % PyLong_SHIFT);
3925 x->ob_digit[a_size + shift_digits] = rem;
3926 }
3927 else {
3928 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3929 digit rem;
3930 /* x = a >> shift */
3931 assert(a_size >= shift_digits);
3932 x = _PyLong_New(a_size - shift_digits);
3933 if (x == NULL)
3934 goto error;
3935 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3936 a_size - shift_digits, shift % PyLong_SHIFT);
3937 /* set inexact if any of the bits shifted out is nonzero */
3938 if (rem)
3939 inexact = 1;
3940 while (!inexact && shift_digits > 0)
3941 if (a->ob_digit[--shift_digits])
3942 inexact = 1;
3943 }
3944 long_normalize(x);
3945 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3948 reference to x, so it's safe to modify it in-place. */
3949 if (b_size == 1) {
3950 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3951 b->ob_digit[0]);
3952 long_normalize(x);
3953 if (rem)
3954 inexact = 1;
3955 }
3956 else {
3957 PyLongObject *div, *rem;
3958 div = x_divrem(x, b, &rem);
3959 Py_DECREF(x);
3960 x = div;
3961 if (x == NULL)
3962 goto error;
3963 if (Py_SIZE(rem))
3964 inexact = 1;
3965 Py_DECREF(rem);
3966 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003967 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 assert(x_size > 0); /* result of division is never zero */
3969 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003972 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 /* Round by directly modifying the low digit of x. */
3976 mask = (digit)1 << (extra_bits - 1);
3977 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003978 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003980 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 /* Convert x to a double dx; the conversion is exact. */
3983 dx = x->ob_digit[--x_size];
3984 while (x_size > 0)
3985 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3986 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 /* Check whether ldexp result will overflow a double. */
3989 if (shift + x_bits >= DBL_MAX_EXP &&
3990 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3991 goto overflow;
3992 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003993
3994 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003996
3997 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003999
4000 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 PyErr_SetString(PyExc_OverflowError,
4002 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004003 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004005}
4006
4007static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004008long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 CHECK_BINOP(a, b);
4013
Yury Selivanove0b23092016-02-11 10:26:27 -05004014 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4015 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4016 }
4017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4019 mod = NULL;
4020 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004021}
4022
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004023static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004024long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 PyLongObject *div, *mod;
4027 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4032 return NULL;
4033 }
4034 z = PyTuple_New(2);
4035 if (z != NULL) {
4036 PyTuple_SetItem(z, 0, (PyObject *) div);
4037 PyTuple_SetItem(z, 1, (PyObject *) mod);
4038 }
4039 else {
4040 Py_DECREF(div);
4041 Py_DECREF(mod);
4042 }
4043 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004044}
4045
Tim Peters47e52ee2004-08-30 02:44:38 +00004046/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004047static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004048long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4051 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 PyLongObject *z = NULL; /* accumulated result */
4054 Py_ssize_t i, j, k; /* counters */
4055 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 /* 5-ary values. If the exponent is large enough, table is
4058 * precomputed so that table[i] == a**i % c for i in range(32).
4059 */
4060 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4061 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 /* a, b, c = v, w, x */
4064 CHECK_BINOP(v, w);
4065 a = (PyLongObject*)v; Py_INCREF(a);
4066 b = (PyLongObject*)w; Py_INCREF(b);
4067 if (PyLong_Check(x)) {
4068 c = (PyLongObject *)x;
4069 Py_INCREF(x);
4070 }
4071 else if (x == Py_None)
4072 c = NULL;
4073 else {
4074 Py_DECREF(a);
4075 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004076 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 }
Tim Peters4c483c42001-09-05 06:24:58 +00004078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 if (Py_SIZE(b) < 0) { /* if exponent is negative */
4080 if (c) {
Mark Dickinson0c346d82014-04-11 14:34:40 -04004081 PyErr_SetString(PyExc_ValueError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00004082 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 goto Error;
4084 }
4085 else {
4086 /* else return a float. This works because we know
4087 that this calls float_pow() which converts its
4088 arguments to double. */
4089 Py_DECREF(a);
4090 Py_DECREF(b);
4091 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
4092 }
4093 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 if (c) {
4096 /* if modulus == 0:
4097 raise ValueError() */
4098 if (Py_SIZE(c) == 0) {
4099 PyErr_SetString(PyExc_ValueError,
4100 "pow() 3rd argument cannot be 0");
4101 goto Error;
4102 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 /* if modulus < 0:
4105 negativeOutput = True
4106 modulus = -modulus */
4107 if (Py_SIZE(c) < 0) {
4108 negativeOutput = 1;
4109 temp = (PyLongObject *)_PyLong_Copy(c);
4110 if (temp == NULL)
4111 goto Error;
4112 Py_DECREF(c);
4113 c = temp;
4114 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004115 _PyLong_Negate(&c);
4116 if (c == NULL)
4117 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 /* if modulus == 1:
4121 return 0 */
4122 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4123 z = (PyLongObject *)PyLong_FromLong(0L);
4124 goto Done;
4125 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004126
Tim Peters81a93152013-10-05 16:53:52 -05004127 /* Reduce base by modulus in some cases:
4128 1. If base < 0. Forcing the base non-negative makes things easier.
4129 2. If base is obviously larger than the modulus. The "small
4130 exponent" case later can multiply directly by base repeatedly,
4131 while the "large exponent" case multiplies directly by base 31
4132 times. It can be unboundedly faster to multiply by
4133 base % modulus instead.
4134 We could _always_ do this reduction, but l_divmod() isn't cheap,
4135 so we only do it when it buys something. */
4136 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 if (l_divmod(a, c, NULL, &temp) < 0)
4138 goto Error;
4139 Py_DECREF(a);
4140 a = temp;
4141 temp = NULL;
4142 }
4143 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 /* At this point a, b, and c are guaranteed non-negative UNLESS
4146 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 z = (PyLongObject *)PyLong_FromLong(1L);
4149 if (z == NULL)
4150 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 /* Perform a modular reduction, X = X % c, but leave X alone if c
4153 * is NULL.
4154 */
4155#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004156 do { \
4157 if (c != NULL) { \
4158 if (l_divmod(X, c, NULL, &temp) < 0) \
4159 goto Error; \
4160 Py_XDECREF(X); \
4161 X = temp; \
4162 temp = NULL; \
4163 } \
4164 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 /* Multiply two values, then reduce the result:
4167 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004168#define MULT(X, Y, result) \
4169 do { \
4170 temp = (PyLongObject *)long_mul(X, Y); \
4171 if (temp == NULL) \
4172 goto Error; \
4173 Py_XDECREF(result); \
4174 result = temp; \
4175 temp = NULL; \
4176 REDUCE(result); \
4177 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4180 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4181 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4182 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4183 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004186 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004188 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 }
4190 }
4191 }
4192 else {
4193 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4194 Py_INCREF(z); /* still holds 1L */
4195 table[0] = z;
4196 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004197 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4200 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4203 const int index = (bi >> j) & 0x1f;
4204 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004205 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004207 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 }
4209 }
4210 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 if (negativeOutput && (Py_SIZE(z) != 0)) {
4213 temp = (PyLongObject *)long_sub(z, c);
4214 if (temp == NULL)
4215 goto Error;
4216 Py_DECREF(z);
4217 z = temp;
4218 temp = NULL;
4219 }
4220 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004221
Mark Dickinson22b20182010-05-10 21:27:53 +00004222 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004223 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004225 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4227 for (i = 0; i < 32; ++i)
4228 Py_XDECREF(table[i]);
4229 }
4230 Py_DECREF(a);
4231 Py_DECREF(b);
4232 Py_XDECREF(c);
4233 Py_XDECREF(temp);
4234 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004235}
4236
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004237static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004238long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004240 /* Implement ~x as -(x+1) */
4241 PyLongObject *x;
4242 PyLongObject *w;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004243 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
4245 w = (PyLongObject *)PyLong_FromLong(1L);
4246 if (w == NULL)
4247 return NULL;
4248 x = (PyLongObject *) long_add(v, w);
4249 Py_DECREF(w);
4250 if (x == NULL)
4251 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004252 _PyLong_Negate(&x);
4253 /* No need for maybe_small_long here, since any small
4254 longs will have been caught in the Py_SIZE <= 1 fast path. */
4255 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004256}
4257
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004258static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004259long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004262 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 return PyLong_FromLong(-MEDIUM_VALUE(v));
4264 z = (PyLongObject *)_PyLong_Copy(v);
4265 if (z != NULL)
4266 Py_SIZE(z) = -(Py_SIZE(v));
4267 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004268}
4269
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004270static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004271long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004273 if (Py_SIZE(v) < 0)
4274 return long_neg(v);
4275 else
4276 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004277}
4278
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004279static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004280long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004283}
4284
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004285static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004286long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 PyLongObject *z = NULL;
4289 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4290 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 if (Py_SIZE(a) < 0) {
4295 /* Right shifting negative numbers is harder */
4296 PyLongObject *a1, *a2;
4297 a1 = (PyLongObject *) long_invert(a);
4298 if (a1 == NULL)
4299 goto rshift_error;
4300 a2 = (PyLongObject *) long_rshift(a1, b);
4301 Py_DECREF(a1);
4302 if (a2 == NULL)
4303 goto rshift_error;
4304 z = (PyLongObject *) long_invert(a2);
4305 Py_DECREF(a2);
4306 }
4307 else {
4308 shiftby = PyLong_AsSsize_t((PyObject *)b);
4309 if (shiftby == -1L && PyErr_Occurred())
4310 goto rshift_error;
4311 if (shiftby < 0) {
4312 PyErr_SetString(PyExc_ValueError,
4313 "negative shift count");
4314 goto rshift_error;
4315 }
4316 wordshift = shiftby / PyLong_SHIFT;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004317 newsize = Py_ABS(Py_SIZE(a)) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 if (newsize <= 0)
4319 return PyLong_FromLong(0);
4320 loshift = shiftby % PyLong_SHIFT;
4321 hishift = PyLong_SHIFT - loshift;
4322 lomask = ((digit)1 << hishift) - 1;
4323 himask = PyLong_MASK ^ lomask;
4324 z = _PyLong_New(newsize);
4325 if (z == NULL)
4326 goto rshift_error;
4327 if (Py_SIZE(a) < 0)
4328 Py_SIZE(z) = -(Py_SIZE(z));
4329 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4330 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4331 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004332 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 }
4334 z = long_normalize(z);
4335 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004336 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004338
Guido van Rossumc6913e71991-11-19 20:26:46 +00004339}
4340
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004341static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004342long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 /* This version due to Tim Peters */
4345 PyLongObject *a = (PyLongObject*)v;
4346 PyLongObject *b = (PyLongObject*)w;
4347 PyLongObject *z = NULL;
4348 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4349 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 shiftby = PyLong_AsSsize_t((PyObject *)b);
4354 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004355 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 if (shiftby < 0) {
4357 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004358 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004360
4361 if (Py_SIZE(a) == 0) {
4362 return PyLong_FromLong(0);
4363 }
4364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4366 wordshift = shiftby / PyLong_SHIFT;
4367 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004368
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004369 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 newsize = oldsize + wordshift;
4371 if (remshift)
4372 ++newsize;
4373 z = _PyLong_New(newsize);
4374 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004375 return NULL;
4376 if (Py_SIZE(a) < 0) {
4377 assert(Py_REFCNT(z) == 1);
4378 Py_SIZE(z) = -Py_SIZE(z);
4379 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 for (i = 0; i < wordshift; i++)
4381 z->ob_digit[i] = 0;
4382 accum = 0;
4383 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4384 accum |= (twodigits)a->ob_digit[j] << remshift;
4385 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4386 accum >>= PyLong_SHIFT;
4387 }
4388 if (remshift)
4389 z->ob_digit[newsize-1] = (digit)accum;
4390 else
4391 assert(!accum);
4392 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004394}
4395
Mark Dickinson27a87a22009-10-25 20:43:34 +00004396/* Compute two's complement of digit vector a[0:m], writing result to
4397 z[0:m]. The digit vector a need not be normalized, but should not
4398 be entirely zero. a and z may point to the same digit vector. */
4399
4400static void
4401v_complement(digit *z, digit *a, Py_ssize_t m)
4402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 Py_ssize_t i;
4404 digit carry = 1;
4405 for (i = 0; i < m; ++i) {
4406 carry += a[i] ^ PyLong_MASK;
4407 z[i] = carry & PyLong_MASK;
4408 carry >>= PyLong_SHIFT;
4409 }
4410 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004411}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004412
4413/* Bitwise and/xor/or operations */
4414
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004415static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004416long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004417 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004418 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 int nega, negb, negz;
4421 Py_ssize_t size_a, size_b, size_z, i;
4422 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 /* Bitwise operations for negative numbers operate as though
4425 on a two's complement representation. So convert arguments
4426 from sign-magnitude to two's complement, and convert the
4427 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004430 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 nega = Py_SIZE(a) < 0;
4432 if (nega) {
4433 z = _PyLong_New(size_a);
4434 if (z == NULL)
4435 return NULL;
4436 v_complement(z->ob_digit, a->ob_digit, size_a);
4437 a = z;
4438 }
4439 else
4440 /* Keep reference count consistent. */
4441 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004444 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 negb = Py_SIZE(b) < 0;
4446 if (negb) {
4447 z = _PyLong_New(size_b);
4448 if (z == NULL) {
4449 Py_DECREF(a);
4450 return NULL;
4451 }
4452 v_complement(z->ob_digit, b->ob_digit, size_b);
4453 b = z;
4454 }
4455 else
4456 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 /* Swap a and b if necessary to ensure size_a >= size_b. */
4459 if (size_a < size_b) {
4460 z = a; a = b; b = z;
4461 size_z = size_a; size_a = size_b; size_b = size_z;
4462 negz = nega; nega = negb; negb = negz;
4463 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 /* JRH: The original logic here was to allocate the result value (z)
4466 as the longer of the two operands. However, there are some cases
4467 where the result is guaranteed to be shorter than that: AND of two
4468 positives, OR of two negatives: use the shorter number. AND with
4469 mixed signs: use the positive number. OR with mixed signs: use the
4470 negative number.
4471 */
4472 switch (op) {
4473 case '^':
4474 negz = nega ^ negb;
4475 size_z = size_a;
4476 break;
4477 case '&':
4478 negz = nega & negb;
4479 size_z = negb ? size_a : size_b;
4480 break;
4481 case '|':
4482 negz = nega | negb;
4483 size_z = negb ? size_b : size_a;
4484 break;
4485 default:
4486 PyErr_BadArgument();
4487 return NULL;
4488 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 /* We allow an extra digit if z is negative, to make sure that
4491 the final two's complement of z doesn't overflow. */
4492 z = _PyLong_New(size_z + negz);
4493 if (z == NULL) {
4494 Py_DECREF(a);
4495 Py_DECREF(b);
4496 return NULL;
4497 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 /* Compute digits for overlap of a and b. */
4500 switch(op) {
4501 case '&':
4502 for (i = 0; i < size_b; ++i)
4503 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4504 break;
4505 case '|':
4506 for (i = 0; i < size_b; ++i)
4507 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4508 break;
4509 case '^':
4510 for (i = 0; i < size_b; ++i)
4511 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4512 break;
4513 default:
4514 PyErr_BadArgument();
4515 return NULL;
4516 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 /* Copy any remaining digits of a, inverting if necessary. */
4519 if (op == '^' && negb)
4520 for (; i < size_z; ++i)
4521 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4522 else if (i < size_z)
4523 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4524 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 /* Complement result if negative. */
4527 if (negz) {
4528 Py_SIZE(z) = -(Py_SIZE(z));
4529 z->ob_digit[size_z] = PyLong_MASK;
4530 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4531 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 Py_DECREF(a);
4534 Py_DECREF(b);
4535 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004536}
4537
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004538static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004539long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 PyObject *c;
4542 CHECK_BINOP(a, b);
4543 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4544 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004545}
4546
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004547static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004548long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 PyObject *c;
4551 CHECK_BINOP(a, b);
4552 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4553 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004554}
4555
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004556static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004557long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 PyObject *c;
4560 CHECK_BINOP(a, b);
4561 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4562 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004563}
4564
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004565static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004566long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568 if (PyLong_CheckExact(v))
4569 Py_INCREF(v);
4570 else
4571 v = _PyLong_Copy((PyLongObject *)v);
4572 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004573}
4574
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004575PyObject *
4576_PyLong_GCD(PyObject *aarg, PyObject *barg)
4577{
4578 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4579 stwodigits x, y, q, s, t, c_carry, d_carry;
4580 stwodigits A, B, C, D, T;
4581 int nbits, k;
4582 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4583 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4584
4585 a = (PyLongObject *)aarg;
4586 b = (PyLongObject *)barg;
4587 size_a = Py_SIZE(a);
4588 size_b = Py_SIZE(b);
4589 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4590 Py_INCREF(a);
4591 Py_INCREF(b);
4592 goto simple;
4593 }
4594
4595 /* Initial reduction: make sure that 0 <= b <= a. */
4596 a = (PyLongObject *)long_abs(a);
4597 if (a == NULL)
4598 return NULL;
4599 b = (PyLongObject *)long_abs(b);
4600 if (b == NULL) {
4601 Py_DECREF(a);
4602 return NULL;
4603 }
4604 if (long_compare(a, b) < 0) {
4605 r = a;
4606 a = b;
4607 b = r;
4608 }
4609 /* We now own references to a and b */
4610
4611 alloc_a = Py_SIZE(a);
4612 alloc_b = Py_SIZE(b);
4613 /* reduce until a fits into 2 digits */
4614 while ((size_a = Py_SIZE(a)) > 2) {
4615 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4616 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4617 corresponding bits of b into y */
4618 size_b = Py_SIZE(b);
4619 assert(size_b <= size_a);
4620 if (size_b == 0) {
4621 if (size_a < alloc_a) {
4622 r = (PyLongObject *)_PyLong_Copy(a);
4623 Py_DECREF(a);
4624 }
4625 else
4626 r = a;
4627 Py_DECREF(b);
4628 Py_XDECREF(c);
4629 Py_XDECREF(d);
4630 return (PyObject *)r;
4631 }
4632 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4633 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4634 (a->ob_digit[size_a-3] >> nbits));
4635
4636 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4637 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4638 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4639
4640 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4641 larger than PyLong_MASK during the algorithm. */
4642 A = 1; B = 0; C = 0; D = 1;
4643 for (k=0;; k++) {
4644 if (y-C == 0)
4645 break;
4646 q = (x+(A-1))/(y-C);
4647 s = B+q*D;
4648 t = x-q*y;
4649 if (s > t)
4650 break;
4651 x = y; y = t;
4652 t = A+q*C; A = D; B = C; C = s; D = t;
4653 }
4654
4655 if (k == 0) {
4656 /* no progress; do a Euclidean step */
4657 if (l_divmod(a, b, NULL, &r) < 0)
4658 goto error;
4659 Py_DECREF(a);
4660 a = b;
4661 b = r;
4662 alloc_a = alloc_b;
4663 alloc_b = Py_SIZE(b);
4664 continue;
4665 }
4666
4667 /*
4668 a, b = A*b-B*a, D*a-C*b if k is odd
4669 a, b = A*a-B*b, D*b-C*a if k is even
4670 */
4671 if (k&1) {
4672 T = -A; A = -B; B = T;
4673 T = -C; C = -D; D = T;
4674 }
4675 if (c != NULL)
4676 Py_SIZE(c) = size_a;
4677 else if (Py_REFCNT(a) == 1) {
4678 Py_INCREF(a);
4679 c = a;
4680 }
4681 else {
4682 alloc_a = size_a;
4683 c = _PyLong_New(size_a);
4684 if (c == NULL)
4685 goto error;
4686 }
4687
4688 if (d != NULL)
4689 Py_SIZE(d) = size_a;
4690 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4691 Py_INCREF(b);
4692 d = b;
4693 Py_SIZE(d) = size_a;
4694 }
4695 else {
4696 alloc_b = size_a;
4697 d = _PyLong_New(size_a);
4698 if (d == NULL)
4699 goto error;
4700 }
4701 a_end = a->ob_digit + size_a;
4702 b_end = b->ob_digit + size_b;
4703
4704 /* compute new a and new b in parallel */
4705 a_digit = a->ob_digit;
4706 b_digit = b->ob_digit;
4707 c_digit = c->ob_digit;
4708 d_digit = d->ob_digit;
4709 c_carry = 0;
4710 d_carry = 0;
4711 while (b_digit < b_end) {
4712 c_carry += (A * *a_digit) - (B * *b_digit);
4713 d_carry += (D * *b_digit++) - (C * *a_digit++);
4714 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4715 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4716 c_carry >>= PyLong_SHIFT;
4717 d_carry >>= PyLong_SHIFT;
4718 }
4719 while (a_digit < a_end) {
4720 c_carry += A * *a_digit;
4721 d_carry -= C * *a_digit++;
4722 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4723 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4724 c_carry >>= PyLong_SHIFT;
4725 d_carry >>= PyLong_SHIFT;
4726 }
4727 assert(c_carry == 0);
4728 assert(d_carry == 0);
4729
4730 Py_INCREF(c);
4731 Py_INCREF(d);
4732 Py_DECREF(a);
4733 Py_DECREF(b);
4734 a = long_normalize(c);
4735 b = long_normalize(d);
4736 }
4737 Py_XDECREF(c);
4738 Py_XDECREF(d);
4739
4740simple:
4741 assert(Py_REFCNT(a) > 0);
4742 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004743/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4744 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4745#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004746 /* a fits into a long, so b must too */
4747 x = PyLong_AsLong((PyObject *)a);
4748 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004749#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004750 x = PyLong_AsLongLong((PyObject *)a);
4751 y = PyLong_AsLongLong((PyObject *)b);
4752#else
4753# error "_PyLong_GCD"
4754#endif
4755 x = Py_ABS(x);
4756 y = Py_ABS(y);
4757 Py_DECREF(a);
4758 Py_DECREF(b);
4759
4760 /* usual Euclidean algorithm for longs */
4761 while (y != 0) {
4762 t = y;
4763 y = x % y;
4764 x = t;
4765 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004766#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004767 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004768#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004769 return PyLong_FromLongLong(x);
4770#else
4771# error "_PyLong_GCD"
4772#endif
4773
4774error:
4775 Py_DECREF(a);
4776 Py_DECREF(b);
4777 Py_XDECREF(c);
4778 Py_XDECREF(d);
4779 return NULL;
4780}
4781
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004782static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004783long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 double result;
4786 result = PyLong_AsDouble(v);
4787 if (result == -1.0 && PyErr_Occurred())
4788 return NULL;
4789 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004790}
4791
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004792static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004793long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004794
Tim Peters6d6c1a32001-08-02 04:15:00 +00004795static PyObject *
4796long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4797{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004798 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004799 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 if (type != &PyLong_Type)
4803 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004804 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4805 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004807 if (x == NULL) {
4808 if (obase != NULL) {
4809 PyErr_SetString(PyExc_TypeError,
4810 "int() missing string argument");
4811 return NULL;
4812 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004814 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004815 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004816 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004817
Gregory P. Smitha689e522012-12-25 22:38:32 -08004818 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004819 if (base == -1 && PyErr_Occurred())
4820 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004821 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004822 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004823 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004824 return NULL;
4825 }
4826
4827 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004828 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 if (PyByteArray_Check(x))
4832 string = PyByteArray_AS_STRING(x);
4833 else
4834 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004835 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 }
4837 else {
4838 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004839 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004840 return NULL;
4841 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004842}
4843
Serhiy Storchaka95949422013-08-27 19:40:23 +03004844/* Wimpy, slow approach to tp_new calls for subtypes of int:
4845 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004846 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004847 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004848*/
4849static PyObject *
4850long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 PyLongObject *tmp, *newobj;
4853 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 assert(PyType_IsSubtype(type, &PyLong_Type));
4856 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4857 if (tmp == NULL)
4858 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004859 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 n = Py_SIZE(tmp);
4861 if (n < 0)
4862 n = -n;
4863 newobj = (PyLongObject *)type->tp_alloc(type, n);
4864 if (newobj == NULL) {
4865 Py_DECREF(tmp);
4866 return NULL;
4867 }
4868 assert(PyLong_Check(newobj));
4869 Py_SIZE(newobj) = Py_SIZE(tmp);
4870 for (i = 0; i < n; i++)
4871 newobj->ob_digit[i] = tmp->ob_digit[i];
4872 Py_DECREF(tmp);
4873 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004874}
4875
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004876static PyObject *
4877long_getnewargs(PyLongObject *v)
4878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004879 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004880}
4881
Guido van Rossumb43daf72007-08-01 18:08:08 +00004882static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004883long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004884 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004885}
4886
4887static PyObject *
4888long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004890}
4891
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004892static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004893long__format__(PyObject *self, PyObject *args)
4894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004896 _PyUnicodeWriter writer;
4897 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004899 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4900 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004901
Victor Stinner8f674cc2013-04-17 23:02:17 +02004902 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004903 ret = _PyLong_FormatAdvancedWriter(
4904 &writer,
4905 self,
4906 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4907 if (ret == -1) {
4908 _PyUnicodeWriter_Dealloc(&writer);
4909 return NULL;
4910 }
4911 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004912}
4913
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004914/* Return a pair (q, r) such that a = b * q + r, and
4915 abs(r) <= abs(b)/2, with equality possible only if q is even.
4916 In other words, q == a / b, rounded to the nearest integer using
4917 round-half-to-even. */
4918
4919PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004920_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004921{
4922 PyLongObject *quo = NULL, *rem = NULL;
4923 PyObject *one = NULL, *twice_rem, *result, *temp;
4924 int cmp, quo_is_odd, quo_is_neg;
4925
4926 /* Equivalent Python code:
4927
4928 def divmod_near(a, b):
4929 q, r = divmod(a, b)
4930 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4931 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4932 # positive, 2 * r < b if b negative.
4933 greater_than_half = 2*r > b if b > 0 else 2*r < b
4934 exactly_half = 2*r == b
4935 if greater_than_half or exactly_half and q % 2 == 1:
4936 q += 1
4937 r -= b
4938 return q, r
4939
4940 */
4941 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4942 PyErr_SetString(PyExc_TypeError,
4943 "non-integer arguments in division");
4944 return NULL;
4945 }
4946
4947 /* Do a and b have different signs? If so, quotient is negative. */
4948 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4949
4950 one = PyLong_FromLong(1L);
4951 if (one == NULL)
4952 return NULL;
4953
4954 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4955 goto error;
4956
4957 /* compare twice the remainder with the divisor, to see
4958 if we need to adjust the quotient and remainder */
4959 twice_rem = long_lshift((PyObject *)rem, one);
4960 if (twice_rem == NULL)
4961 goto error;
4962 if (quo_is_neg) {
4963 temp = long_neg((PyLongObject*)twice_rem);
4964 Py_DECREF(twice_rem);
4965 twice_rem = temp;
4966 if (twice_rem == NULL)
4967 goto error;
4968 }
4969 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4970 Py_DECREF(twice_rem);
4971
4972 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4973 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4974 /* fix up quotient */
4975 if (quo_is_neg)
4976 temp = long_sub(quo, (PyLongObject *)one);
4977 else
4978 temp = long_add(quo, (PyLongObject *)one);
4979 Py_DECREF(quo);
4980 quo = (PyLongObject *)temp;
4981 if (quo == NULL)
4982 goto error;
4983 /* and remainder */
4984 if (quo_is_neg)
4985 temp = long_add(rem, (PyLongObject *)b);
4986 else
4987 temp = long_sub(rem, (PyLongObject *)b);
4988 Py_DECREF(rem);
4989 rem = (PyLongObject *)temp;
4990 if (rem == NULL)
4991 goto error;
4992 }
4993
4994 result = PyTuple_New(2);
4995 if (result == NULL)
4996 goto error;
4997
4998 /* PyTuple_SET_ITEM steals references */
4999 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5000 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
5001 Py_DECREF(one);
5002 return result;
5003
5004 error:
5005 Py_XDECREF(quo);
5006 Py_XDECREF(rem);
5007 Py_XDECREF(one);
5008 return NULL;
5009}
5010
Eric Smith8c663262007-08-25 02:26:07 +00005011static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005012long_round(PyObject *self, PyObject *args)
5013{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005014 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005015
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005016 /* To round an integer m to the nearest 10**n (n positive), we make use of
5017 * the divmod_near operation, defined by:
5018 *
5019 * divmod_near(a, b) = (q, r)
5020 *
5021 * where q is the nearest integer to the quotient a / b (the
5022 * nearest even integer in the case of a tie) and r == a - q * b.
5023 * Hence q * b = a - r is the nearest multiple of b to a,
5024 * preferring even multiples in the case of a tie.
5025 *
5026 * So the nearest multiple of 10**n to m is:
5027 *
5028 * m - divmod_near(m, 10**n)[1].
5029 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5031 return NULL;
5032 if (o_ndigits == NULL)
5033 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005034
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005035 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 if (ndigits == NULL)
5037 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005038
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005039 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005040 if (Py_SIZE(ndigits) >= 0) {
5041 Py_DECREF(ndigits);
5042 return long_long(self);
5043 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005044
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005045 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5046 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005048 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005049 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005050 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005051
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005052 result = PyLong_FromLong(10L);
5053 if (result == NULL) {
5054 Py_DECREF(ndigits);
5055 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005056 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005057
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005058 temp = long_pow(result, ndigits, Py_None);
5059 Py_DECREF(ndigits);
5060 Py_DECREF(result);
5061 result = temp;
5062 if (result == NULL)
5063 return NULL;
5064
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005065 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005066 Py_DECREF(result);
5067 result = temp;
5068 if (result == NULL)
5069 return NULL;
5070
5071 temp = long_sub((PyLongObject *)self,
5072 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5073 Py_DECREF(result);
5074 result = temp;
5075
5076 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005077}
5078
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005079static PyObject *
5080long_sizeof(PyLongObject *v)
5081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005083
Victor Stinner45e8e2f2014-05-14 17:24:35 +02005084 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(v))*sizeof(digit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005086}
5087
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005088static PyObject *
5089long_bit_length(PyLongObject *v)
5090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 PyLongObject *result, *x, *y;
5092 Py_ssize_t ndigits, msd_bits = 0;
5093 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005095 assert(v != NULL);
5096 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005097
Victor Stinner45e8e2f2014-05-14 17:24:35 +02005098 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 if (ndigits == 0)
5100 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 msd = v->ob_digit[ndigits-1];
5103 while (msd >= 32) {
5104 msd_bits += 6;
5105 msd >>= 6;
5106 }
5107 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5110 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 /* expression above may overflow; use Python integers instead */
5113 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5114 if (result == NULL)
5115 return NULL;
5116 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5117 if (x == NULL)
5118 goto error;
5119 y = (PyLongObject *)long_mul(result, x);
5120 Py_DECREF(x);
5121 if (y == NULL)
5122 goto error;
5123 Py_DECREF(result);
5124 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5127 if (x == NULL)
5128 goto error;
5129 y = (PyLongObject *)long_add(result, x);
5130 Py_DECREF(x);
5131 if (y == NULL)
5132 goto error;
5133 Py_DECREF(result);
5134 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005137
Mark Dickinson22b20182010-05-10 21:27:53 +00005138 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005139 Py_DECREF(result);
5140 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005141}
5142
5143PyDoc_STRVAR(long_bit_length_doc,
5144"int.bit_length() -> int\n\
5145\n\
5146Number of bits necessary to represent self in binary.\n\
5147>>> bin(37)\n\
5148'0b100101'\n\
5149>>> (37).bit_length()\n\
51506");
5151
Christian Heimes53876d92008-04-19 00:31:39 +00005152#if 0
5153static PyObject *
5154long_is_finite(PyObject *v)
5155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005157}
5158#endif
5159
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005160
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005161static PyObject *
5162long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
5163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 PyObject *byteorder_str;
5165 PyObject *is_signed_obj = NULL;
5166 Py_ssize_t length;
5167 int little_endian;
5168 int is_signed;
5169 PyObject *bytes;
5170 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005172 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
5173 &length, &byteorder_str,
5174 &is_signed_obj))
5175 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 if (args != NULL && Py_SIZE(args) > 2) {
5178 PyErr_SetString(PyExc_TypeError,
5179 "'signed' is a keyword-only argument");
5180 return NULL;
5181 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005182
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02005183 if (_PyUnicode_EqualToASCIIString(byteorder_str, "little"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 little_endian = 1;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02005185 else if (_PyUnicode_EqualToASCIIString(byteorder_str, "big"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005186 little_endian = 0;
5187 else {
5188 PyErr_SetString(PyExc_ValueError,
5189 "byteorder must be either 'little' or 'big'");
5190 return NULL;
5191 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 if (is_signed_obj != NULL) {
5194 int cmp = PyObject_IsTrue(is_signed_obj);
5195 if (cmp < 0)
5196 return NULL;
5197 is_signed = cmp ? 1 : 0;
5198 }
5199 else {
5200 /* If the signed argument was omitted, use False as the
5201 default. */
5202 is_signed = 0;
5203 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 if (length < 0) {
5206 PyErr_SetString(PyExc_ValueError,
5207 "length argument must be non-negative");
5208 return NULL;
5209 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 bytes = PyBytes_FromStringAndSize(NULL, length);
5212 if (bytes == NULL)
5213 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005215 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
5216 length, little_endian, is_signed) < 0) {
5217 Py_DECREF(bytes);
5218 return NULL;
5219 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005222}
5223
Mark Dickinson078c2532010-01-30 18:06:17 +00005224PyDoc_STRVAR(long_to_bytes_doc,
5225"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005226\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005227Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005228\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005230raised if the integer is not representable with the given number of\n\
5231bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005232\n\
5233The byteorder argument determines the byte order used to represent the\n\
5234integer. If byteorder is 'big', the most significant byte is at the\n\
5235beginning of the byte array. If byteorder is 'little', the most\n\
5236significant byte is at the end of the byte array. To request the native\n\
5237byte order of the host system, use `sys.byteorder' as the byte order value.\n\
5238\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005239The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005241is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005242
5243static PyObject *
5244long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
5245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 PyObject *byteorder_str;
5247 PyObject *is_signed_obj = NULL;
5248 int little_endian;
5249 int is_signed;
5250 PyObject *obj;
5251 PyObject *bytes;
5252 PyObject *long_obj;
5253 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
5256 &obj, &byteorder_str,
5257 &is_signed_obj))
5258 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 if (args != NULL && Py_SIZE(args) > 2) {
5261 PyErr_SetString(PyExc_TypeError,
5262 "'signed' is a keyword-only argument");
5263 return NULL;
5264 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005265
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02005266 if (_PyUnicode_EqualToASCIIString(byteorder_str, "little"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 little_endian = 1;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02005268 else if (_PyUnicode_EqualToASCIIString(byteorder_str, "big"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005269 little_endian = 0;
5270 else {
5271 PyErr_SetString(PyExc_ValueError,
5272 "byteorder must be either 'little' or 'big'");
5273 return NULL;
5274 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 if (is_signed_obj != NULL) {
5277 int cmp = PyObject_IsTrue(is_signed_obj);
5278 if (cmp < 0)
5279 return NULL;
5280 is_signed = cmp ? 1 : 0;
5281 }
5282 else {
5283 /* If the signed argument was omitted, use False as the
5284 default. */
5285 is_signed = 0;
5286 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 bytes = PyObject_Bytes(obj);
5289 if (bytes == NULL)
5290 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 long_obj = _PyLong_FromByteArray(
5293 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5294 little_endian, is_signed);
5295 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005296
Serhiy Storchakaea36c942016-05-12 10:37:58 +03005297 if (type != &PyLong_Type) {
5298 Py_SETREF(long_obj, PyObject_CallFunctionObjArgs((PyObject *)type,
5299 long_obj, NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005303}
5304
Mark Dickinson078c2532010-01-30 18:06:17 +00005305PyDoc_STRVAR(long_from_bytes_doc,
5306"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
5307\n\
5308Return the integer represented by the given array of bytes.\n\
5309\n\
R David Murray861470c2014-10-05 11:47:01 -04005310The bytes argument must be a bytes-like object (e.g. bytes or bytearray).\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005311\n\
5312The byteorder argument determines the byte order used to represent the\n\
5313integer. If byteorder is 'big', the most significant byte is at the\n\
5314beginning of the byte array. If byteorder is 'little', the most\n\
5315significant byte is at the end of the byte array. To request the native\n\
5316byte order of the host system, use `sys.byteorder' as the byte order value.\n\
5317\n\
5318The signed keyword-only argument indicates whether two's complement is\n\
5319used to represent the integer.");
5320
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005321static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
5323 "Returns self, the complex conjugate of any int."},
5324 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
5325 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00005326#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5328 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005329#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 {"to_bytes", (PyCFunction)long_to_bytes,
5331 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
5332 {"from_bytes", (PyCFunction)long_from_bytes,
5333 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
5334 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
5335 "Truncating an Integral returns itself."},
5336 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
5337 "Flooring an Integral returns itself."},
5338 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
5339 "Ceiling of an Integral returns itself."},
5340 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5341 "Rounding an Integral returns itself.\n"
5342 "Rounding with an ndigits argument also returns an integer."},
5343 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
5344 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
5345 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
5346 "Returns size in memory, in bytes"},
5347 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005348};
5349
Guido van Rossumb43daf72007-08-01 18:08:08 +00005350static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005351 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005352 (getter)long_long, (setter)NULL,
5353 "the real part of a complex number",
5354 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005355 {"imag",
5356 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005357 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005358 NULL},
5359 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005360 (getter)long_long, (setter)NULL,
5361 "the numerator of a rational number in lowest terms",
5362 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005363 {"denominator",
5364 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005365 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005366 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005367 {NULL} /* Sentinel */
5368};
5369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005370PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005371"int(x=0) -> integer\n\
5372int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005373\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005374Convert a number or string to an integer, or return 0 if no arguments\n\
5375are given. If x is a number, return x.__int__(). For floating point\n\
5376numbers, this truncates towards zero.\n\
5377\n\
5378If x is not a number or if base is given, then x must be a string,\n\
5379bytes, or bytearray instance representing an integer literal in the\n\
5380given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5381by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5382Base 0 means to interpret the base from the string as an integer literal.\n\
5383>>> int('0b100', base=0)\n\
53844");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005385
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005386static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005387 (binaryfunc)long_add, /*nb_add*/
5388 (binaryfunc)long_sub, /*nb_subtract*/
5389 (binaryfunc)long_mul, /*nb_multiply*/
5390 long_mod, /*nb_remainder*/
5391 long_divmod, /*nb_divmod*/
5392 long_pow, /*nb_power*/
5393 (unaryfunc)long_neg, /*nb_negative*/
5394 (unaryfunc)long_long, /*tp_positive*/
5395 (unaryfunc)long_abs, /*tp_absolute*/
5396 (inquiry)long_bool, /*tp_bool*/
5397 (unaryfunc)long_invert, /*nb_invert*/
5398 long_lshift, /*nb_lshift*/
5399 (binaryfunc)long_rshift, /*nb_rshift*/
5400 long_and, /*nb_and*/
5401 long_xor, /*nb_xor*/
5402 long_or, /*nb_or*/
5403 long_long, /*nb_int*/
5404 0, /*nb_reserved*/
5405 long_float, /*nb_float*/
5406 0, /* nb_inplace_add */
5407 0, /* nb_inplace_subtract */
5408 0, /* nb_inplace_multiply */
5409 0, /* nb_inplace_remainder */
5410 0, /* nb_inplace_power */
5411 0, /* nb_inplace_lshift */
5412 0, /* nb_inplace_rshift */
5413 0, /* nb_inplace_and */
5414 0, /* nb_inplace_xor */
5415 0, /* nb_inplace_or */
5416 long_div, /* nb_floor_divide */
5417 long_true_divide, /* nb_true_divide */
5418 0, /* nb_inplace_floor_divide */
5419 0, /* nb_inplace_true_divide */
5420 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005421};
5422
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005423PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5425 "int", /* tp_name */
5426 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5427 sizeof(digit), /* tp_itemsize */
5428 long_dealloc, /* tp_dealloc */
5429 0, /* tp_print */
5430 0, /* tp_getattr */
5431 0, /* tp_setattr */
5432 0, /* tp_reserved */
5433 long_to_decimal_string, /* tp_repr */
5434 &long_as_number, /* tp_as_number */
5435 0, /* tp_as_sequence */
5436 0, /* tp_as_mapping */
5437 (hashfunc)long_hash, /* tp_hash */
5438 0, /* tp_call */
5439 long_to_decimal_string, /* tp_str */
5440 PyObject_GenericGetAttr, /* tp_getattro */
5441 0, /* tp_setattro */
5442 0, /* tp_as_buffer */
5443 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5444 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5445 long_doc, /* tp_doc */
5446 0, /* tp_traverse */
5447 0, /* tp_clear */
5448 long_richcompare, /* tp_richcompare */
5449 0, /* tp_weaklistoffset */
5450 0, /* tp_iter */
5451 0, /* tp_iternext */
5452 long_methods, /* tp_methods */
5453 0, /* tp_members */
5454 long_getset, /* tp_getset */
5455 0, /* tp_base */
5456 0, /* tp_dict */
5457 0, /* tp_descr_get */
5458 0, /* tp_descr_set */
5459 0, /* tp_dictoffset */
5460 0, /* tp_init */
5461 0, /* tp_alloc */
5462 long_new, /* tp_new */
5463 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005464};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005465
Mark Dickinsonbd792642009-03-18 20:06:12 +00005466static PyTypeObject Int_InfoType;
5467
5468PyDoc_STRVAR(int_info__doc__,
5469"sys.int_info\n\
5470\n\
5471A struct sequence that holds information about Python's\n\
5472internal representation of integers. The attributes are read only.");
5473
5474static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005475 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005476 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005478};
5479
5480static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 "sys.int_info", /* name */
5482 int_info__doc__, /* doc */
5483 int_info_fields, /* fields */
5484 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005485};
5486
5487PyObject *
5488PyLong_GetInfo(void)
5489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005490 PyObject* int_info;
5491 int field = 0;
5492 int_info = PyStructSequence_New(&Int_InfoType);
5493 if (int_info == NULL)
5494 return NULL;
5495 PyStructSequence_SET_ITEM(int_info, field++,
5496 PyLong_FromLong(PyLong_SHIFT));
5497 PyStructSequence_SET_ITEM(int_info, field++,
5498 PyLong_FromLong(sizeof(digit)));
5499 if (PyErr_Occurred()) {
5500 Py_CLEAR(int_info);
5501 return NULL;
5502 }
5503 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005504}
5505
Guido van Rossumddefaf32007-01-14 03:31:43 +00005506int
5507_PyLong_Init(void)
5508{
5509#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 int ival, size;
5511 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5514 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5515 if (Py_TYPE(v) == &PyLong_Type) {
5516 /* The element is already initialized, most likely
5517 * the Python interpreter was initialized before.
5518 */
5519 Py_ssize_t refcnt;
5520 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005522 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5523 _Py_NewReference(op);
5524 /* _Py_NewReference sets the ref count to 1 but
5525 * the ref count might be larger. Set the refcnt
5526 * to the original refcnt + 1 */
5527 Py_REFCNT(op) = refcnt + 1;
5528 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005529 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 }
5531 else {
Christian Heimesd3afe782013-12-04 09:27:47 +01005532 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 }
5534 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005535 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005537#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005539 if (Int_InfoType.tp_name == NULL) {
5540 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5541 return 0;
5542 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005545}
5546
5547void
5548PyLong_Fini(void)
5549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005550 /* Integers are currently statically allocated. Py_DECREF is not
5551 needed, but Python must forget about the reference or multiple
5552 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005553#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 int i;
5555 PyLongObject *v = small_ints;
5556 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5557 _Py_DEC_REFTOTAL;
5558 _Py_ForgetReference((PyObject*)v);
5559 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005560#endif
5561}