blob: b9f6327759d7f354cacb063054f24c825d3780db [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;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 while (ival) {
319 *p++ = (digit)(ival & PyLong_MASK);
320 ival >>= PyLong_SHIFT;
321 }
322 }
323 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000324}
325
Serhiy Storchaka95949422013-08-27 19:40:23 +0300326/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000327
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyLongObject *v;
332 double frac;
333 int i, ndig, expo, neg;
334 neg = 0;
335 if (Py_IS_INFINITY(dval)) {
336 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000337 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 return NULL;
339 }
340 if (Py_IS_NAN(dval)) {
341 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000342 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return NULL;
344 }
345 if (dval < 0.0) {
346 neg = 1;
347 dval = -dval;
348 }
349 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
350 if (expo <= 0)
351 return PyLong_FromLong(0L);
352 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
353 v = _PyLong_New(ndig);
354 if (v == NULL)
355 return NULL;
356 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
357 for (i = ndig; --i >= 0; ) {
358 digit bits = (digit)frac;
359 v->ob_digit[i] = bits;
360 frac = frac - (double)bits;
361 frac = ldexp(frac, PyLong_SHIFT);
362 }
363 if (neg)
364 Py_SIZE(v) = -(Py_SIZE(v));
365 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000366}
367
Thomas Wouters89f507f2006-12-13 04:49:30 +0000368/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
369 * anything about what happens when a signed integer operation overflows,
370 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700371 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000372 * (unsigned long)LONG_MAX, and for the smallest negative signed long
373 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
374 * However, some other compilers warn about applying unary minus to an
375 * unsigned operand. Hence the weird "0-".
376 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
378#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000379
Serhiy Storchaka95949422013-08-27 19:40:23 +0300380/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100381 method.
382
383 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
384 the result. Otherwise *overflow is 0.
385
386 For other errors (e.g., TypeError), return -1 and set an error condition.
387 In this case *overflow will be 0.
388*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000389
390long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000391PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200394 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 unsigned long x, prev;
396 long res;
397 Py_ssize_t i;
398 int sign;
399 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 *overflow = 0;
402 if (vv == NULL) {
403 PyErr_BadInternalCall();
404 return -1;
405 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000406
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200407 if (PyLong_Check(vv)) {
408 v = (PyLongObject *)vv;
409 }
410 else {
411 v = _PyLong_FromNbInt(vv);
412 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 return -1;
414 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 switch (i) {
421 case -1:
422 res = -(sdigit)v->ob_digit[0];
423 break;
424 case 0:
425 res = 0;
426 break;
427 case 1:
428 res = v->ob_digit[0];
429 break;
430 default:
431 sign = 1;
432 x = 0;
433 if (i < 0) {
434 sign = -1;
435 i = -(i);
436 }
437 while (--i >= 0) {
438 prev = x;
439 x = (x << PyLong_SHIFT) | v->ob_digit[i];
440 if ((x >> PyLong_SHIFT) != prev) {
441 *overflow = sign;
442 goto exit;
443 }
444 }
445 /* Haven't lost any bits, but casting to long requires extra
446 * care (see comment above).
447 */
448 if (x <= (unsigned long)LONG_MAX) {
449 res = (long)x * sign;
450 }
451 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
452 res = LONG_MIN;
453 }
454 else {
455 *overflow = sign;
456 /* res is already set to -1 */
457 }
458 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000459 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200461 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 }
463 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000464}
465
Serhiy Storchaka95949422013-08-27 19:40:23 +0300466/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100467 method. Return -1 and set an error if overflow occurs. */
468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000470PyLong_AsLong(PyObject *obj)
471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 int overflow;
473 long result = PyLong_AsLongAndOverflow(obj, &overflow);
474 if (overflow) {
475 /* XXX: could be cute and give a different
476 message for overflow == -1 */
477 PyErr_SetString(PyExc_OverflowError,
478 "Python int too large to convert to C long");
479 }
480 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000481}
482
Serhiy Storchaka95949422013-08-27 19:40:23 +0300483/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200484 method. Return -1 and set an error if overflow occurs. */
485
486int
487_PyLong_AsInt(PyObject *obj)
488{
489 int overflow;
490 long result = PyLong_AsLongAndOverflow(obj, &overflow);
491 if (overflow || result > INT_MAX || result < INT_MIN) {
492 /* XXX: could be cute and give a different
493 message for overflow == -1 */
494 PyErr_SetString(PyExc_OverflowError,
495 "Python int too large to convert to C int");
496 return -1;
497 }
498 return (int)result;
499}
500
Serhiy Storchaka95949422013-08-27 19:40:23 +0300501/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000502 Returns -1 and sets an error condition if overflow occurs. */
503
504Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000505PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200506 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 size_t x, prev;
508 Py_ssize_t i;
509 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (vv == NULL) {
512 PyErr_BadInternalCall();
513 return -1;
514 }
515 if (!PyLong_Check(vv)) {
516 PyErr_SetString(PyExc_TypeError, "an integer is required");
517 return -1;
518 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 v = (PyLongObject *)vv;
521 i = Py_SIZE(v);
522 switch (i) {
523 case -1: return -(sdigit)v->ob_digit[0];
524 case 0: return 0;
525 case 1: return v->ob_digit[0];
526 }
527 sign = 1;
528 x = 0;
529 if (i < 0) {
530 sign = -1;
531 i = -(i);
532 }
533 while (--i >= 0) {
534 prev = x;
535 x = (x << PyLong_SHIFT) | v->ob_digit[i];
536 if ((x >> PyLong_SHIFT) != prev)
537 goto overflow;
538 }
539 /* Haven't lost any bits, but casting to a signed type requires
540 * extra care (see comment above).
541 */
542 if (x <= (size_t)PY_SSIZE_T_MAX) {
543 return (Py_ssize_t)x * sign;
544 }
545 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
546 return PY_SSIZE_T_MIN;
547 }
548 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000549
Mark Dickinson22b20182010-05-10 21:27:53 +0000550 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyErr_SetString(PyExc_OverflowError,
552 "Python int too large to convert to C ssize_t");
553 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000554}
555
Serhiy Storchaka95949422013-08-27 19:40:23 +0300556/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000557 Returns -1 and sets an error condition if overflow occurs. */
558
559unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000560PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000561{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200562 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 unsigned long x, prev;
564 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (vv == NULL) {
567 PyErr_BadInternalCall();
568 return (unsigned long)-1;
569 }
570 if (!PyLong_Check(vv)) {
571 PyErr_SetString(PyExc_TypeError, "an integer is required");
572 return (unsigned long)-1;
573 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 v = (PyLongObject *)vv;
576 i = Py_SIZE(v);
577 x = 0;
578 if (i < 0) {
579 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000580 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return (unsigned long) -1;
582 }
583 switch (i) {
584 case 0: return 0;
585 case 1: return v->ob_digit[0];
586 }
587 while (--i >= 0) {
588 prev = x;
589 x = (x << PyLong_SHIFT) | v->ob_digit[i];
590 if ((x >> PyLong_SHIFT) != prev) {
591 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100592 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000593 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return (unsigned long) -1;
595 }
596 }
597 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000598}
599
Serhiy Storchaka95949422013-08-27 19:40:23 +0300600/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200601 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000602
603size_t
604PyLong_AsSize_t(PyObject *vv)
605{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200606 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 size_t x, prev;
608 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (vv == NULL) {
611 PyErr_BadInternalCall();
612 return (size_t) -1;
613 }
614 if (!PyLong_Check(vv)) {
615 PyErr_SetString(PyExc_TypeError, "an integer is required");
616 return (size_t)-1;
617 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 v = (PyLongObject *)vv;
620 i = Py_SIZE(v);
621 x = 0;
622 if (i < 0) {
623 PyErr_SetString(PyExc_OverflowError,
624 "can't convert negative value to size_t");
625 return (size_t) -1;
626 }
627 switch (i) {
628 case 0: return 0;
629 case 1: return v->ob_digit[0];
630 }
631 while (--i >= 0) {
632 prev = x;
633 x = (x << PyLong_SHIFT) | v->ob_digit[i];
634 if ((x >> PyLong_SHIFT) != prev) {
635 PyErr_SetString(PyExc_OverflowError,
636 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200637 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 }
639 }
640 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000641}
642
Serhiy Storchaka95949422013-08-27 19:40:23 +0300643/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000644 Returns -1 and sets an error condition if an error occurs. */
645
Guido van Rossumddefaf32007-01-14 03:31:43 +0000646static unsigned long
647_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000648{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200649 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 unsigned long x;
651 Py_ssize_t i;
652 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (vv == NULL || !PyLong_Check(vv)) {
655 PyErr_BadInternalCall();
656 return (unsigned long) -1;
657 }
658 v = (PyLongObject *)vv;
659 i = Py_SIZE(v);
660 switch (i) {
661 case 0: return 0;
662 case 1: return v->ob_digit[0];
663 }
664 sign = 1;
665 x = 0;
666 if (i < 0) {
667 sign = -1;
668 i = -i;
669 }
670 while (--i >= 0) {
671 x = (x << PyLong_SHIFT) | v->ob_digit[i];
672 }
673 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000674}
675
Guido van Rossumddefaf32007-01-14 03:31:43 +0000676unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200677PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyLongObject *lo;
680 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000681
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200682 if (op == NULL) {
683 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 return (unsigned long)-1;
685 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000686
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200687 if (PyLong_Check(op)) {
688 return _PyLong_AsUnsignedLongMask(op);
689 }
690
691 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (lo == NULL)
693 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200694
695 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
696 Py_DECREF(lo);
697 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000698}
699
Tim Peters5b8132f2003-01-31 15:52:05 +0000700int
701_PyLong_Sign(PyObject *vv)
702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 assert(v != NULL);
706 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000709}
710
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200711/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
712 2**k if d is nonzero, else 0. */
713
714static const unsigned char BitLengthTable[32] = {
715 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
716 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
717};
718
719static int
720bits_in_digit(digit d)
721{
722 int d_bits = 0;
723 while (d >= 32) {
724 d_bits += 6;
725 d >>= 6;
726 }
727 d_bits += (int)BitLengthTable[d];
728 return d_bits;
729}
730
Tim Petersbaefd9e2003-01-28 20:37:45 +0000731size_t
732_PyLong_NumBits(PyObject *vv)
733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyLongObject *v = (PyLongObject *)vv;
735 size_t result = 0;
736 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200737 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 assert(v != NULL);
740 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200741 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
743 if (ndigits > 0) {
744 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700745 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100747 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200748 msd_bits = bits_in_digit(msd);
749 if (SIZE_MAX - msd_bits < result)
750 goto Overflow;
751 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 }
753 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000754
Mark Dickinson22b20182010-05-10 21:27:53 +0000755 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
757 "to express in a platform size_t");
758 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000759}
760
Tim Peters2a9b3672001-06-11 21:23:58 +0000761PyObject *
762_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000764{
Mark Dickinson22b20182010-05-10 21:27:53 +0000765 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 int incr; /* direction to move pstartbyte */
767 const unsigned char* pendbyte; /* MSB of bytes */
768 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300769 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 PyLongObject* v; /* result */
771 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 if (n == 0)
774 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (little_endian) {
777 pstartbyte = bytes;
778 pendbyte = bytes + n - 1;
779 incr = 1;
780 }
781 else {
782 pstartbyte = bytes + n - 1;
783 pendbyte = bytes;
784 incr = -1;
785 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (is_signed)
788 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200791 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 is positive, and leading 0xff bytes if negative. */
793 {
794 size_t i;
795 const unsigned char* p = pendbyte;
796 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000797 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000800 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 break;
802 }
803 numsignificantbytes = n - i;
804 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
805 actually has 2 significant bytes. OTOH, 0xff0001 ==
806 -0x00ffff, so we wouldn't *need* to bump it there; but we
807 do for 0xffff = -0x0001. To be safe without bothering to
808 check every case, bump it regardless. */
809 if (is_signed && numsignificantbytes < n)
810 ++numsignificantbytes;
811 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000812
Serhiy Storchaka95949422013-08-27 19:40:23 +0300813 /* How many Python int digits do we need? We have
814 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
816 /* catch overflow before it happens */
817 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
818 PyErr_SetString(PyExc_OverflowError,
819 "byte array too long to convert to int");
820 return NULL;
821 }
822 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
823 v = _PyLong_New(ndigits);
824 if (v == NULL)
825 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 /* Copy the bits over. The tricky parts are computing 2's-comp on
828 the fly for signed numbers, and dealing with the mismatch between
829 8-bit bytes and (probably) 15-bit Python digits.*/
830 {
831 size_t i;
832 twodigits carry = 1; /* for 2's-comp calculation */
833 twodigits accum = 0; /* sliding register */
834 unsigned int accumbits = 0; /* number of bits in accum */
835 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
838 twodigits thisbyte = *p;
839 /* Compute correction for 2's comp, if needed. */
840 if (is_signed) {
841 thisbyte = (0xff ^ thisbyte) + carry;
842 carry = thisbyte >> 8;
843 thisbyte &= 0xff;
844 }
845 /* Because we're going LSB to MSB, thisbyte is
846 more significant than what's already in accum,
847 so needs to be prepended to accum. */
848 accum |= (twodigits)thisbyte << accumbits;
849 accumbits += 8;
850 if (accumbits >= PyLong_SHIFT) {
851 /* There's enough to fill a Python digit. */
852 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000853 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 ++idigit;
855 accum >>= PyLong_SHIFT;
856 accumbits -= PyLong_SHIFT;
857 assert(accumbits < PyLong_SHIFT);
858 }
859 }
860 assert(accumbits < PyLong_SHIFT);
861 if (accumbits) {
862 assert(idigit < ndigits);
863 v->ob_digit[idigit] = (digit)accum;
864 ++idigit;
865 }
866 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 Py_SIZE(v) = is_signed ? -idigit : idigit;
869 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000870}
871
872int
873_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 unsigned char* bytes, size_t n,
875 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000878 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000880 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
882 digit carry; /* for computing 2's-comp */
883 size_t j; /* # bytes filled */
884 unsigned char* p; /* pointer to next byte in bytes */
885 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (Py_SIZE(v) < 0) {
890 ndigits = -(Py_SIZE(v));
891 if (!is_signed) {
892 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000893 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return -1;
895 }
896 do_twos_comp = 1;
897 }
898 else {
899 ndigits = Py_SIZE(v);
900 do_twos_comp = 0;
901 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 if (little_endian) {
904 p = bytes;
905 pincr = 1;
906 }
907 else {
908 p = bytes + n - 1;
909 pincr = -1;
910 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* Copy over all the Python digits.
913 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300914 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 normalized. */
916 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
917 j = 0;
918 accum = 0;
919 accumbits = 0;
920 carry = do_twos_comp ? 1 : 0;
921 for (i = 0; i < ndigits; ++i) {
922 digit thisdigit = v->ob_digit[i];
923 if (do_twos_comp) {
924 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
925 carry = thisdigit >> PyLong_SHIFT;
926 thisdigit &= PyLong_MASK;
927 }
928 /* Because we're going LSB to MSB, thisdigit is more
929 significant than what's already in accum, so needs to be
930 prepended to accum. */
931 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* The most-significant digit may be (probably is) at least
934 partly empty. */
935 if (i == ndigits - 1) {
936 /* Count # of sign bits -- they needn't be stored,
937 * although for signed conversion we need later to
938 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000939 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 while (s != 0) {
941 s >>= 1;
942 accumbits++;
943 }
944 }
945 else
946 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* Store as many bytes as possible. */
949 while (accumbits >= 8) {
950 if (j >= n)
951 goto Overflow;
952 ++j;
953 *p = (unsigned char)(accum & 0xff);
954 p += pincr;
955 accumbits -= 8;
956 accum >>= 8;
957 }
958 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* Store the straggler (if any). */
961 assert(accumbits < 8);
962 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
963 if (accumbits > 0) {
964 if (j >= n)
965 goto Overflow;
966 ++j;
967 if (do_twos_comp) {
968 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300969 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 infinite supply of sign bits). */
971 accum |= (~(twodigits)0) << accumbits;
972 }
973 *p = (unsigned char)(accum & 0xff);
974 p += pincr;
975 }
976 else if (j == n && n > 0 && is_signed) {
977 /* The main loop filled the byte array exactly, so the code
978 just above didn't get to ensure there's a sign bit, and the
979 loop below wouldn't add one either. Make sure a sign bit
980 exists. */
981 unsigned char msb = *(p - pincr);
982 int sign_bit_set = msb >= 0x80;
983 assert(accumbits == 0);
984 if (sign_bit_set == do_twos_comp)
985 return 0;
986 else
987 goto Overflow;
988 }
Tim Peters05607ad2001-06-13 21:01:27 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 /* Fill remaining bytes with copies of the sign bit. */
991 {
992 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
993 for ( ; j < n; ++j, p += pincr)
994 *p = signbyte;
995 }
Tim Peters05607ad2001-06-13 21:01:27 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000998
Mark Dickinson22b20182010-05-10 21:27:53 +0000999 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1001 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001002
Tim Peters2a9b3672001-06-11 21:23:58 +00001003}
1004
Serhiy Storchaka95949422013-08-27 19:40:23 +03001005/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001006
1007PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001008PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001009{
Mark Dickinson91044792012-10-18 19:21:43 +01001010#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001011 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001012#else
1013
Tim Peters70128a12001-06-16 08:48:40 +00001014#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001015# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001016#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001017 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001018#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001019
Guido van Rossum78694d91998-09-18 14:14:13 +00001020}
1021
Serhiy Storchaka95949422013-08-27 19:40:23 +03001022/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001023
1024void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001025PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001026{
Tim Peters70128a12001-06-16 08:48:40 +00001027#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1031 x = PyLong_AsLong(vv);
1032 else
1033 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001034#else
Tim Peters70128a12001-06-16 08:48:40 +00001035
Tim Peters70128a12001-06-16 08:48:40 +00001036#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001037# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001038#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001039 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1042 x = PyLong_AsLongLong(vv);
1043 else
1044 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001045
1046#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (x == -1 && PyErr_Occurred())
1049 return NULL;
1050 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001051}
1052
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001053/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001054 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001055 */
1056
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001057#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001058
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001059/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001060
1061PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001062PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001065 unsigned long long abs_ival;
1066 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 int ndigits = 0;
1068 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 CHECK_SMALL_INT(ival);
1071 if (ival < 0) {
1072 /* avoid signed overflow on negation; see comments
1073 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001074 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 negative = 1;
1076 }
1077 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001078 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 /* Count the number of Python digits.
1082 We used to pick 5 ("big enough for anything"), but that's a
1083 waste of time and space given that 5*15 = 75 bits are rarely
1084 needed. */
1085 t = abs_ival;
1086 while (t) {
1087 ++ndigits;
1088 t >>= PyLong_SHIFT;
1089 }
1090 v = _PyLong_New(ndigits);
1091 if (v != NULL) {
1092 digit *p = v->ob_digit;
1093 Py_SIZE(v) = negative ? -ndigits : ndigits;
1094 t = abs_ival;
1095 while (t) {
1096 *p++ = (digit)(t & PyLong_MASK);
1097 t >>= PyLong_SHIFT;
1098 }
1099 }
1100 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001101}
1102
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001103/* Create a new int object from a C unsigned long long int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001104
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001105PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001106PyLong_FromUnsignedLongLong(unsigned long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001109 unsigned long long t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 if (ival < PyLong_BASE)
1113 return PyLong_FromLong((long)ival);
1114 /* Count the number of Python digits. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001115 t = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 while (t) {
1117 ++ndigits;
1118 t >>= PyLong_SHIFT;
1119 }
1120 v = _PyLong_New(ndigits);
1121 if (v != NULL) {
1122 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 while (ival) {
1124 *p++ = (digit)(ival & PyLong_MASK);
1125 ival >>= PyLong_SHIFT;
1126 }
1127 }
1128 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001129}
1130
Serhiy Storchaka95949422013-08-27 19:40:23 +03001131/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001132
1133PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001134PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 PyLongObject *v;
1137 size_t abs_ival;
1138 size_t t; /* unsigned so >> doesn't propagate sign bit */
1139 int ndigits = 0;
1140 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 CHECK_SMALL_INT(ival);
1143 if (ival < 0) {
1144 /* avoid signed overflow when ival = SIZE_T_MIN */
1145 abs_ival = (size_t)(-1-ival)+1;
1146 negative = 1;
1147 }
1148 else {
1149 abs_ival = (size_t)ival;
1150 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 /* Count the number of Python digits. */
1153 t = abs_ival;
1154 while (t) {
1155 ++ndigits;
1156 t >>= PyLong_SHIFT;
1157 }
1158 v = _PyLong_New(ndigits);
1159 if (v != NULL) {
1160 digit *p = v->ob_digit;
1161 Py_SIZE(v) = negative ? -ndigits : ndigits;
1162 t = abs_ival;
1163 while (t) {
1164 *p++ = (digit)(t & PyLong_MASK);
1165 t >>= PyLong_SHIFT;
1166 }
1167 }
1168 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001169}
1170
Serhiy Storchaka95949422013-08-27 19:40:23 +03001171/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001172
1173PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001174PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 PyLongObject *v;
1177 size_t t;
1178 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (ival < PyLong_BASE)
1181 return PyLong_FromLong((long)ival);
1182 /* Count the number of Python digits. */
1183 t = ival;
1184 while (t) {
1185 ++ndigits;
1186 t >>= PyLong_SHIFT;
1187 }
1188 v = _PyLong_New(ndigits);
1189 if (v != NULL) {
1190 digit *p = v->ob_digit;
1191 Py_SIZE(v) = ndigits;
1192 while (ival) {
1193 *p++ = (digit)(ival & PyLong_MASK);
1194 ival >>= PyLong_SHIFT;
1195 }
1196 }
1197 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001198}
1199
Serhiy Storchaka95949422013-08-27 19:40:23 +03001200/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001201 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001202
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001203long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001204PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001207 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001209 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 if (vv == NULL) {
1212 PyErr_BadInternalCall();
1213 return -1;
1214 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001215
1216 if (PyLong_Check(vv)) {
1217 v = (PyLongObject *)vv;
1218 }
1219 else {
1220 v = _PyLong_FromNbInt(vv);
1221 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001223 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001225
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001226 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001228 case -1:
1229 bytes = -(sdigit)v->ob_digit[0];
1230 break;
1231 case 0:
1232 bytes = 0;
1233 break;
1234 case 1:
1235 bytes = v->ob_digit[0];
1236 break;
1237 default:
1238 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001239 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001241 if (do_decref) {
1242 Py_DECREF(v);
1243 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001244
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001245 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001247 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 else
1249 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001250}
1251
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001252/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001253 Return -1 and set an error if overflow occurs. */
1254
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001255unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001256PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001259 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001261
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001262 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001264 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001266 if (!PyLong_Check(vv)) {
1267 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001268 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001269 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 v = (PyLongObject*)vv;
1272 switch(Py_SIZE(v)) {
1273 case 0: return 0;
1274 case 1: return v->ob_digit[0];
1275 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001276
Mark Dickinson22b20182010-05-10 21:27:53 +00001277 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001278 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001279
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001280 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001282 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 else
1284 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001285}
Tim Petersd1a7da62001-06-13 00:35:57 +00001286
Serhiy Storchaka95949422013-08-27 19:40:23 +03001287/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001288 Returns -1 and sets an error condition if an error occurs. */
1289
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001290static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001291_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001292{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001293 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001294 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 Py_ssize_t i;
1296 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (vv == NULL || !PyLong_Check(vv)) {
1299 PyErr_BadInternalCall();
1300 return (unsigned long) -1;
1301 }
1302 v = (PyLongObject *)vv;
1303 switch(Py_SIZE(v)) {
1304 case 0: return 0;
1305 case 1: return v->ob_digit[0];
1306 }
1307 i = Py_SIZE(v);
1308 sign = 1;
1309 x = 0;
1310 if (i < 0) {
1311 sign = -1;
1312 i = -i;
1313 }
1314 while (--i >= 0) {
1315 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1316 }
1317 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001318}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001319
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001320unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001321PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001324 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001325
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001326 if (op == NULL) {
1327 PyErr_BadInternalCall();
1328 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001330
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001331 if (PyLong_Check(op)) {
1332 return _PyLong_AsUnsignedLongLongMask(op);
1333 }
1334
1335 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001337 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001338
1339 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1340 Py_DECREF(lo);
1341 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001342}
Tim Petersd1a7da62001-06-13 00:35:57 +00001343
Serhiy Storchaka95949422013-08-27 19:40:23 +03001344/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001345 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001346
Mark Dickinson8d48b432011-10-23 20:47:14 +01001347 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1348 the result. Otherwise *overflow is 0.
1349
1350 For other errors (e.g., TypeError), return -1 and set an error condition.
1351 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001352*/
1353
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001354long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001355PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001358 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001359 unsigned long long x, prev;
1360 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 Py_ssize_t i;
1362 int sign;
1363 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 *overflow = 0;
1366 if (vv == NULL) {
1367 PyErr_BadInternalCall();
1368 return -1;
1369 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001370
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001371 if (PyLong_Check(vv)) {
1372 v = (PyLongObject *)vv;
1373 }
1374 else {
1375 v = _PyLong_FromNbInt(vv);
1376 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 return -1;
1378 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 switch (i) {
1385 case -1:
1386 res = -(sdigit)v->ob_digit[0];
1387 break;
1388 case 0:
1389 res = 0;
1390 break;
1391 case 1:
1392 res = v->ob_digit[0];
1393 break;
1394 default:
1395 sign = 1;
1396 x = 0;
1397 if (i < 0) {
1398 sign = -1;
1399 i = -(i);
1400 }
1401 while (--i >= 0) {
1402 prev = x;
1403 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1404 if ((x >> PyLong_SHIFT) != prev) {
1405 *overflow = sign;
1406 goto exit;
1407 }
1408 }
1409 /* Haven't lost any bits, but casting to long requires extra
1410 * care (see comment above).
1411 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001412 if (x <= (unsigned long long)PY_LLONG_MAX) {
1413 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 }
1415 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1416 res = PY_LLONG_MIN;
1417 }
1418 else {
1419 *overflow = sign;
1420 /* res is already set to -1 */
1421 }
1422 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001423 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001425 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 }
1427 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001428}
1429
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001430#define CHECK_BINOP(v,w) \
1431 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001432 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1433 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001434 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001435
Tim Peters877a2122002-08-12 05:09:36 +00001436/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1437 * is modified in place, by adding y to it. Carries are propagated as far as
1438 * x[m-1], and the remaining carry (0 or 1) is returned.
1439 */
1440static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001441v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 Py_ssize_t i;
1444 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 assert(m >= n);
1447 for (i = 0; i < n; ++i) {
1448 carry += x[i] + y[i];
1449 x[i] = carry & PyLong_MASK;
1450 carry >>= PyLong_SHIFT;
1451 assert((carry & 1) == carry);
1452 }
1453 for (; carry && i < m; ++i) {
1454 carry += x[i];
1455 x[i] = carry & PyLong_MASK;
1456 carry >>= PyLong_SHIFT;
1457 assert((carry & 1) == carry);
1458 }
1459 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001460}
1461
1462/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1463 * is modified in place, by subtracting y from it. Borrows are propagated as
1464 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1465 */
1466static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001467v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 Py_ssize_t i;
1470 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 assert(m >= n);
1473 for (i = 0; i < n; ++i) {
1474 borrow = x[i] - y[i] - borrow;
1475 x[i] = borrow & PyLong_MASK;
1476 borrow >>= PyLong_SHIFT;
1477 borrow &= 1; /* keep only 1 sign bit */
1478 }
1479 for (; borrow && i < m; ++i) {
1480 borrow = x[i] - borrow;
1481 x[i] = borrow & PyLong_MASK;
1482 borrow >>= PyLong_SHIFT;
1483 borrow &= 1;
1484 }
1485 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001486}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001487
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001488/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1489 * result in z[0:m], and return the d bits shifted out of the top.
1490 */
1491static digit
1492v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 Py_ssize_t i;
1495 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 assert(0 <= d && d < PyLong_SHIFT);
1498 for (i=0; i < m; i++) {
1499 twodigits acc = (twodigits)a[i] << d | carry;
1500 z[i] = (digit)acc & PyLong_MASK;
1501 carry = (digit)(acc >> PyLong_SHIFT);
1502 }
1503 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001504}
1505
1506/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1507 * result in z[0:m], and return the d bits shifted out of the bottom.
1508 */
1509static digit
1510v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 Py_ssize_t i;
1513 digit carry = 0;
1514 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 assert(0 <= d && d < PyLong_SHIFT);
1517 for (i=m; i-- > 0;) {
1518 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1519 carry = (digit)acc & mask;
1520 z[i] = (digit)(acc >> d);
1521 }
1522 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001523}
1524
Tim Peters212e6142001-07-14 12:23:19 +00001525/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1526 in pout, and returning the remainder. pin and pout point at the LSD.
1527 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001528 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001529 immutable. */
1530
1531static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001532inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 assert(n > 0 && n <= PyLong_MASK);
1537 pin += size;
1538 pout += size;
1539 while (--size >= 0) {
1540 digit hi;
1541 rem = (rem << PyLong_SHIFT) | *--pin;
1542 *--pout = hi = (digit)(rem / n);
1543 rem -= (twodigits)hi * n;
1544 }
1545 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001546}
1547
Serhiy Storchaka95949422013-08-27 19:40:23 +03001548/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001549 (as function result) and the remainder (through *prem).
1550 The sign of a is ignored; n should not be zero. */
1551
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001552static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001553divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001554{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001555 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 assert(n > 0 && n <= PyLong_MASK);
1559 z = _PyLong_New(size);
1560 if (z == NULL)
1561 return NULL;
1562 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1563 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001564}
1565
Serhiy Storchaka95949422013-08-27 19:40:23 +03001566/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001567 string. (Return value is non-shared so that callers can modify the
1568 returned value if necessary.) */
1569
Victor Stinnerd3f08822012-05-29 12:57:52 +02001570static int
1571long_to_decimal_string_internal(PyObject *aa,
1572 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001573 _PyUnicodeWriter *writer,
1574 _PyBytesWriter *bytes_writer,
1575 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001578 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 Py_ssize_t size, strlen, size_a, i, j;
1580 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001582 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001583 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 a = (PyLongObject *)aa;
1586 if (a == NULL || !PyLong_Check(a)) {
1587 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001588 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001590 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 /* quick and dirty upper bound for the number of digits
1594 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 But log2(a) < size_a * PyLong_SHIFT, and
1599 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001600 > 3.3 * _PyLong_DECIMAL_SHIFT
1601
1602 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1603 size_a + size_a / d < size_a + size_a / floor(d),
1604 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1605 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001607 d = (33 * _PyLong_DECIMAL_SHIFT) /
1608 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1609 assert(size_a < PY_SSIZE_T_MAX/2);
1610 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 scratch = _PyLong_New(size);
1612 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001613 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 /* convert array of base _PyLong_BASE digits in pin to an array of
1616 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1617 Volume 2 (3rd edn), section 4.4, Method 1b). */
1618 pin = a->ob_digit;
1619 pout = scratch->ob_digit;
1620 size = 0;
1621 for (i = size_a; --i >= 0; ) {
1622 digit hi = pin[i];
1623 for (j = 0; j < size; j++) {
1624 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1625 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1626 pout[j] = (digit)(z - (twodigits)hi *
1627 _PyLong_DECIMAL_BASE);
1628 }
1629 while (hi) {
1630 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1631 hi /= _PyLong_DECIMAL_BASE;
1632 }
1633 /* check for keyboard interrupt */
1634 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001635 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001636 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001637 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 }
1639 /* pout should have at least one digit, so that the case when a = 0
1640 works correctly */
1641 if (size == 0)
1642 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 /* calculate exact length of output string, and allocate */
1645 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1646 tenpow = 10;
1647 rem = pout[size-1];
1648 while (rem >= tenpow) {
1649 tenpow *= 10;
1650 strlen++;
1651 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001652 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001653 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1654 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001655 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001656 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001657 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001659 else if (bytes_writer) {
1660 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1661 if (*bytes_str == NULL) {
1662 Py_DECREF(scratch);
1663 return -1;
1664 }
1665 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001666 else {
1667 str = PyUnicode_New(strlen, '9');
1668 if (str == NULL) {
1669 Py_DECREF(scratch);
1670 return -1;
1671 }
1672 kind = PyUnicode_KIND(str);
1673 }
1674
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001675#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001676 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001677 /* pout[0] through pout[size-2] contribute exactly \
1678 _PyLong_DECIMAL_SHIFT digits each */ \
1679 for (i=0; i < size - 1; i++) { \
1680 rem = pout[i]; \
1681 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1682 *--p = '0' + rem % 10; \
1683 rem /= 10; \
1684 } \
1685 } \
1686 /* pout[size-1]: always produce at least one decimal digit */ \
1687 rem = pout[i]; \
1688 do { \
1689 *--p = '0' + rem % 10; \
1690 rem /= 10; \
1691 } while (rem != 0); \
1692 \
1693 /* and sign */ \
1694 if (negative) \
1695 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001696 } while (0)
1697
1698#define WRITE_UNICODE_DIGITS(TYPE) \
1699 do { \
1700 if (writer) \
1701 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1702 else \
1703 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1704 \
1705 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001706 \
1707 /* check we've counted correctly */ \
1708 if (writer) \
1709 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1710 else \
1711 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1712 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001715 if (bytes_writer) {
1716 char *p = *bytes_str + strlen;
1717 WRITE_DIGITS(p);
1718 assert(p == *bytes_str);
1719 }
1720 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001721 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001722 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001724 else if (kind == PyUnicode_2BYTE_KIND) {
1725 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001726 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001727 }
1728 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001729 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001730 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001731 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001732 }
1733#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001734#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001737 if (writer) {
1738 writer->pos += strlen;
1739 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001740 else if (bytes_writer) {
1741 (*bytes_str) += strlen;
1742 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001743 else {
1744 assert(_PyUnicode_CheckConsistency(str, 1));
1745 *p_output = (PyObject *)str;
1746 }
1747 return 0;
1748}
1749
1750static PyObject *
1751long_to_decimal_string(PyObject *aa)
1752{
1753 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001754 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001755 return NULL;
1756 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001757}
1758
Serhiy Storchaka95949422013-08-27 19:40:23 +03001759/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001760 which should be one of 2, 8 or 16. Return a string object.
1761 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1762 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001763
Victor Stinnerd3f08822012-05-29 12:57:52 +02001764static int
1765long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001766 PyObject **p_output, _PyUnicodeWriter *writer,
1767 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001768{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001769 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001770 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001771 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001773 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001774 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001776
Victor Stinnerd3f08822012-05-29 12:57:52 +02001777 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 if (a == NULL || !PyLong_Check(a)) {
1779 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001780 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001782 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001783 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 /* Compute a rough upper bound for the length of the string */
1786 switch (base) {
1787 case 16:
1788 bits = 4;
1789 break;
1790 case 8:
1791 bits = 3;
1792 break;
1793 case 2:
1794 bits = 1;
1795 break;
1796 default:
1797 assert(0); /* shouldn't ever get here */
1798 bits = 0; /* to silence gcc warning */
1799 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001800
Mark Dickinsone2846542012-04-20 21:21:24 +01001801 /* Compute exact length 'sz' of output string. */
1802 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001803 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001804 }
1805 else {
1806 Py_ssize_t size_a_in_bits;
1807 /* Ensure overflow doesn't occur during computation of sz. */
1808 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1809 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001810 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001811 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001812 }
1813 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1814 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001815 /* Allow 1 character for a '-' sign. */
1816 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1817 }
1818 if (alternate) {
1819 /* 2 characters for prefix */
1820 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001821 }
1822
Victor Stinnerd3f08822012-05-29 12:57:52 +02001823 if (writer) {
1824 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1825 return -1;
1826 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001828 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001829 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1830 if (*bytes_str == NULL)
1831 return -1;
1832 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001834 v = PyUnicode_New(sz, 'x');
1835 if (v == NULL)
1836 return -1;
1837 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001839
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001840#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001841 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001842 if (size_a == 0) { \
1843 *--p = '0'; \
1844 } \
1845 else { \
1846 /* JRH: special case for power-of-2 bases */ \
1847 twodigits accum = 0; \
1848 int accumbits = 0; /* # of bits in accum */ \
1849 Py_ssize_t i; \
1850 for (i = 0; i < size_a; ++i) { \
1851 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1852 accumbits += PyLong_SHIFT; \
1853 assert(accumbits >= bits); \
1854 do { \
1855 char cdigit; \
1856 cdigit = (char)(accum & (base - 1)); \
1857 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1858 *--p = cdigit; \
1859 accumbits -= bits; \
1860 accum >>= bits; \
1861 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1862 } \
1863 } \
1864 \
1865 if (alternate) { \
1866 if (base == 16) \
1867 *--p = 'x'; \
1868 else if (base == 8) \
1869 *--p = 'o'; \
1870 else /* (base == 2) */ \
1871 *--p = 'b'; \
1872 *--p = '0'; \
1873 } \
1874 if (negative) \
1875 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001876 } while (0)
1877
1878#define WRITE_UNICODE_DIGITS(TYPE) \
1879 do { \
1880 if (writer) \
1881 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1882 else \
1883 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1884 \
1885 WRITE_DIGITS(p); \
1886 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001887 if (writer) \
1888 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1889 else \
1890 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1891 } while (0)
1892
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001893 if (bytes_writer) {
1894 char *p = *bytes_str + sz;
1895 WRITE_DIGITS(p);
1896 assert(p == *bytes_str);
1897 }
1898 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001899 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001900 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001901 }
1902 else if (kind == PyUnicode_2BYTE_KIND) {
1903 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001904 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001905 }
1906 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001907 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001908 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001909 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001910 }
1911#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001912#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001913
1914 if (writer) {
1915 writer->pos += sz;
1916 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001917 else if (bytes_writer) {
1918 (*bytes_str) += sz;
1919 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 else {
1921 assert(_PyUnicode_CheckConsistency(v, 1));
1922 *p_output = v;
1923 }
1924 return 0;
1925}
1926
1927PyObject *
1928_PyLong_Format(PyObject *obj, int base)
1929{
1930 PyObject *str;
1931 int err;
1932 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001933 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001934 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001935 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001936 if (err == -1)
1937 return NULL;
1938 return str;
1939}
1940
1941int
1942_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1943 PyObject *obj,
1944 int base, int alternate)
1945{
1946 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001947 return long_to_decimal_string_internal(obj, NULL, writer,
1948 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001949 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001950 return long_format_binary(obj, base, alternate, NULL, writer,
1951 NULL, NULL);
1952}
1953
1954char*
1955_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1956 PyObject *obj,
1957 int base, int alternate)
1958{
1959 char *str2;
1960 int res;
1961 str2 = str;
1962 if (base == 10)
1963 res = long_to_decimal_string_internal(obj, NULL, NULL,
1964 writer, &str2);
1965 else
1966 res = long_format_binary(obj, base, alternate, NULL, NULL,
1967 writer, &str2);
1968 if (res < 0)
1969 return NULL;
1970 assert(str2 != NULL);
1971 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001972}
1973
Thomas Wouters477c8d52006-05-27 19:21:47 +00001974/* Table of digit values for 8-bit string -> integer conversion.
1975 * '0' maps to 0, ..., '9' maps to 9.
1976 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1977 * All other indices map to 37.
1978 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001979 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001980 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001981unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1983 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1984 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1985 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1986 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1987 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1988 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1989 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1990 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1991 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1992 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1993 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1994 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1995 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1996 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1997 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001998};
1999
2000/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002001 * 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 +03002002 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002003 * The point to this routine is that it takes time linear in the number of
2004 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002005 *
2006 * Return values:
2007 * -1 on syntax error (exception needs to be set, *res is untouched)
2008 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002009 */
Brett Cannona721aba2016-09-09 14:57:09 -07002010static int
2011long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002012{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002013 const char *p = *str;
2014 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002015 char prev = 0;
2016 int digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 int bits_per_char;
2018 Py_ssize_t n;
2019 PyLongObject *z;
2020 twodigits accum;
2021 int bits_in_accum;
2022 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2025 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002026 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002028 }
2029 /* count digits and set p to end-of-string */
2030 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2031 if (*p == '_') {
2032 if (prev == '_') {
2033 *str = p - 1;
2034 return -1;
2035 }
2036 } else {
2037 ++digits;
2038 }
2039 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002041 }
2042 if (prev == '_') {
2043 /* Trailing underscore not allowed. */
2044 *str = p - 1;
2045 return -1;
2046 }
2047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 *str = p;
2049 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
Brett Cannona721aba2016-09-09 14:57:09 -07002050 n = digits * bits_per_char + PyLong_SHIFT - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (n / bits_per_char < p - start) {
2052 PyErr_SetString(PyExc_ValueError,
2053 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002054 *res = NULL;
2055 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 }
2057 n = n / PyLong_SHIFT;
2058 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002059 if (z == NULL) {
2060 *res = NULL;
2061 return 0;
2062 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002063 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 * from least to most significant in both.
2065 */
2066 accum = 0;
2067 bits_in_accum = 0;
2068 pdigit = z->ob_digit;
2069 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002070 int k;
2071 if (*p == '_') {
2072 continue;
2073 }
2074 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 assert(k >= 0 && k < base);
2076 accum |= (twodigits)k << bits_in_accum;
2077 bits_in_accum += bits_per_char;
2078 if (bits_in_accum >= PyLong_SHIFT) {
2079 *pdigit++ = (digit)(accum & PyLong_MASK);
2080 assert(pdigit - z->ob_digit <= n);
2081 accum >>= PyLong_SHIFT;
2082 bits_in_accum -= PyLong_SHIFT;
2083 assert(bits_in_accum < PyLong_SHIFT);
2084 }
2085 }
2086 if (bits_in_accum) {
2087 assert(bits_in_accum <= PyLong_SHIFT);
2088 *pdigit++ = (digit)accum;
2089 assert(pdigit - z->ob_digit <= n);
2090 }
2091 while (pdigit - z->ob_digit < n)
2092 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002093 *res = long_normalize(z);
2094 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002095}
2096
Serhiy Storchaka95949422013-08-27 19:40:23 +03002097/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002098 * ignored.
2099 *
2100 * If successful, a PyLong object will be returned and 'pend' will be pointing
2101 * to the first unused byte unless it's NULL.
2102 *
2103 * If unsuccessful, NULL will be returned.
2104 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002105PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002106PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002109 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 PyLongObject *z = NULL;
2111 PyObject *strobj;
2112 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 if ((base != 0 && base < 2) || base > 36) {
2115 PyErr_SetString(PyExc_ValueError,
2116 "int() arg 2 must be >= 2 and <= 36");
2117 return NULL;
2118 }
Brett Cannona721aba2016-09-09 14:57:09 -07002119 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002121 }
2122 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 else if (*str == '-') {
2126 ++str;
2127 sign = -1;
2128 }
2129 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002130 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002132 }
2133 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002135 }
2136 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002138 }
2139 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002141 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 else {
2143 /* "old" (C-style) octal literal, now invalid.
2144 it might still be zero though */
2145 error_if_nonzero = 1;
2146 base = 10;
2147 }
2148 }
2149 if (str[0] == '0' &&
2150 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2151 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002152 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002154 /* One underscore allowed here. */
2155 if (*str == '_') {
2156 ++str;
2157 }
2158 }
2159 if (str[0] == '_') {
2160 /* May not start with underscores. */
2161 goto onError;
2162 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002165 if ((base & (base - 1)) == 0) {
2166 int res = long_from_binary_base(&str, base, &z);
2167 if (res < 0) {
2168 /* Syntax error. */
2169 goto onError;
2170 }
2171 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002173/***
2174Binary bases can be converted in time linear in the number of digits, because
2175Python's representation base is binary. Other bases (including decimal!) use
2176the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002177
Thomas Wouters477c8d52006-05-27 19:21:47 +00002178First some math: the largest integer that can be expressed in N base-B digits
2179is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2180case number of Python digits needed to hold it is the smallest integer n s.t.
2181
2182 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2183 BASE**n >= B**N [taking logs to base BASE]
2184 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2185
2186The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002187this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002188and the result is computed into it.
2189
2190The input string is actually treated as being in base base**i (i.e., i digits
2191are processed at a time), where two more static arrays hold:
2192
2193 convwidth_base[base] = the largest integer i such that base**i <= BASE
2194 convmultmax_base[base] = base ** convwidth_base[base]
2195
2196The first of these is the largest i such that i consecutive input digits
2197must fit in a single Python digit. The second is effectively the input
2198base we're really using.
2199
2200Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2201convmultmax_base[base], the result is "simply"
2202
2203 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2204
2205where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002206
2207Error analysis: as above, the number of Python digits `n` needed is worst-
2208case
2209
2210 n >= N * log(B)/log(BASE)
2211
2212where `N` is the number of input digits in base `B`. This is computed via
2213
2214 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2215
2216below. Two numeric concerns are how much space this can waste, and whether
2217the computed result can be too small. To be concrete, assume BASE = 2**15,
2218which is the default (and it's unlikely anyone changes that).
2219
2220Waste isn't a problem: provided the first input digit isn't 0, the difference
2221between the worst-case input with N digits and the smallest input with N
2222digits is about a factor of B, but B is small compared to BASE so at most
2223one allocated Python digit can remain unused on that count. If
2224N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2225and adding 1 returns a result 1 larger than necessary. However, that can't
2226happen: whenever B is a power of 2, long_from_binary_base() is called
2227instead, and it's impossible for B**i to be an integer power of 2**15 when
2228B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2229an exact integer when B is not a power of 2, since B**i has a prime factor
2230other than 2 in that case, but (2**15)**j's only prime factor is 2).
2231
2232The computed result can be too small if the true value of N*log(B)/log(BASE)
2233is a little bit larger than an exact integer, but due to roundoff errors (in
2234computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2235yields a numeric result a little less than that integer. Unfortunately, "how
2236close can a transcendental function get to an integer over some range?"
2237questions are generally theoretically intractable. Computer analysis via
2238continued fractions is practical: expand log(B)/log(BASE) via continued
2239fractions, giving a sequence i/j of "the best" rational approximations. Then
2240j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2241we can get very close to being in trouble, but very rarely. For example,
224276573 is a denominator in one of the continued-fraction approximations to
2243log(10)/log(2**15), and indeed:
2244
2245 >>> log(10)/log(2**15)*76573
2246 16958.000000654003
2247
2248is very close to an integer. If we were working with IEEE single-precision,
2249rounding errors could kill us. Finding worst cases in IEEE double-precision
2250requires better-than-double-precision log() functions, and Tim didn't bother.
2251Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002252new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002253This should happen extremely rarely, and in fact I don't have a test case
2254that triggers it(!). Instead the code was tested by artificially allocating
2255just 1 digit at the start, so that the copying code was exercised for every
2256digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002257***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002258 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 Py_ssize_t size_z;
Brett Cannona721aba2016-09-09 14:57:09 -07002260 int digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 int i;
2262 int convwidth;
2263 twodigits convmultmax, convmult;
2264 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002265 const char *scan, *lastdigit;
2266 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 static double log_base_BASE[37] = {0.0e0,};
2269 static int convwidth_base[37] = {0,};
2270 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 if (log_base_BASE[base] == 0.0) {
2273 twodigits convmax = base;
2274 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002275
Mark Dickinson22b20182010-05-10 21:27:53 +00002276 log_base_BASE[base] = (log((double)base) /
2277 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 for (;;) {
2279 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002280 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002282 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 convmax = next;
2284 ++i;
2285 }
2286 convmultmax_base[base] = convmax;
2287 assert(i > 0);
2288 convwidth_base[base] = i;
2289 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 /* Find length of the string of numeric characters. */
2292 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002293 lastdigit = str;
2294
2295 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2296 if (*scan == '_') {
2297 if (prev == '_') {
2298 /* Only one underscore allowed. */
2299 str = lastdigit + 1;
2300 goto onError;
2301 }
2302 }
2303 else {
2304 ++digits;
2305 lastdigit = scan;
2306 }
2307 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002309 }
2310 if (prev == '_') {
2311 /* Trailing underscore not allowed. */
2312 /* Set error pointer to first underscore. */
2313 str = lastdigit + 1;
2314 goto onError;
2315 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002316
Serhiy Storchaka95949422013-08-27 19:40:23 +03002317 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 * integer with this base and length. Note that there's no
2319 * need to initialize z->ob_digit -- no slot is read up before
2320 * being stored into.
2321 */
Brett Cannona721aba2016-09-09 14:57:09 -07002322 size_z = (Py_ssize_t)(digits * log_base_BASE[base]) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 /* Uncomment next line to test exceedingly rare copy code */
2324 /* size_z = 1; */
2325 assert(size_z > 0);
2326 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002327 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002329 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* `convwidth` consecutive input digits are treated as a single
2333 * digit in base `convmultmax`.
2334 */
2335 convwidth = convwidth_base[base];
2336 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 /* Work ;-) */
2339 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002340 if (*str == '_') {
2341 str++;
2342 continue;
2343 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 /* grab up to convwidth digits from the input string */
2345 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002346 for (i = 1; i < convwidth && str != scan; ++str) {
2347 if (*str == '_') {
2348 continue;
2349 }
2350 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002352 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 assert(c < PyLong_BASE);
2354 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 convmult = convmultmax;
2357 /* Calculate the shift only if we couldn't get
2358 * convwidth digits.
2359 */
2360 if (i != convwidth) {
2361 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002362 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* Multiply z by convmult, and add c. */
2368 pz = z->ob_digit;
2369 pzstop = pz + Py_SIZE(z);
2370 for (; pz < pzstop; ++pz) {
2371 c += (twodigits)*pz * convmult;
2372 *pz = (digit)(c & PyLong_MASK);
2373 c >>= PyLong_SHIFT;
2374 }
2375 /* carry off the current end? */
2376 if (c) {
2377 assert(c < PyLong_BASE);
2378 if (Py_SIZE(z) < size_z) {
2379 *pz = (digit)c;
2380 ++Py_SIZE(z);
2381 }
2382 else {
2383 PyLongObject *tmp;
2384 /* Extremely rare. Get more space. */
2385 assert(Py_SIZE(z) == size_z);
2386 tmp = _PyLong_New(size_z + 1);
2387 if (tmp == NULL) {
2388 Py_DECREF(z);
2389 return NULL;
2390 }
2391 memcpy(tmp->ob_digit,
2392 z->ob_digit,
2393 sizeof(digit) * size_z);
2394 Py_DECREF(z);
2395 z = tmp;
2396 z->ob_digit[size_z] = (digit)c;
2397 ++size_z;
2398 }
2399 }
2400 }
2401 }
Brett Cannona721aba2016-09-09 14:57:09 -07002402 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002404 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 if (error_if_nonzero) {
2406 /* reset the base to 0, else the exception message
2407 doesn't make too much sense */
2408 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002409 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002411 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 /* there might still be other problems, therefore base
2413 remains zero here for the same reason */
2414 }
Brett Cannona721aba2016-09-09 14:57:09 -07002415 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002417 }
2418 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002420 }
2421 while (*str && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002423 }
2424 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002426 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002428 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002429 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002430 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002431 }
2432 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002433 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002434 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002435 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002436
Mark Dickinson22b20182010-05-10 21:27:53 +00002437 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002438 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002439 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002440 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 Py_XDECREF(z);
2442 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2443 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002444 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002448 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 base, strobj);
2450 Py_DECREF(strobj);
2451 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002452}
2453
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002454/* Since PyLong_FromString doesn't have a length parameter,
2455 * check here for possible NULs in the string.
2456 *
2457 * Reports an invalid literal as a bytes object.
2458 */
2459PyObject *
2460_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2461{
2462 PyObject *result, *strobj;
2463 char *end = NULL;
2464
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002465 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002466 if (end == NULL || (result != NULL && end == s + len))
2467 return result;
2468 Py_XDECREF(result);
2469 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2470 if (strobj != NULL) {
2471 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002472 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002473 base, strobj);
2474 Py_DECREF(strobj);
2475 }
2476 return NULL;
2477}
2478
Guido van Rossum9e896b32000-04-05 20:11:21 +00002479PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002480PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002481{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002482 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002483 if (unicode == NULL)
2484 return NULL;
2485 v = PyLong_FromUnicodeObject(unicode, base);
2486 Py_DECREF(unicode);
2487 return v;
2488}
2489
2490PyObject *
2491PyLong_FromUnicodeObject(PyObject *u, int base)
2492{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002493 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002494 const char *buffer;
2495 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002496 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002497
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002498 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002499 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002501 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002502 if (buffer == NULL) {
2503 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002504 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2505 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002507 else {
2508 result = PyLong_FromString(buffer, &end, base);
2509 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2510 Py_DECREF(asciidig);
2511 return result;
2512 }
2513 Py_DECREF(asciidig);
2514 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002515 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002516 PyErr_Format(PyExc_ValueError,
2517 "invalid literal for int() with base %d: %.200R",
2518 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002519 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002520}
2521
Tim Peters9f688bf2000-07-07 15:53:28 +00002522/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002523static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002525static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002526
Serhiy Storchaka95949422013-08-27 19:40:23 +03002527/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002528
Guido van Rossume32e0141992-01-19 16:31:05 +00002529static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002530long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002532{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002533 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (size_b == 0) {
2537 PyErr_SetString(PyExc_ZeroDivisionError,
2538 "integer division or modulo by zero");
2539 return -1;
2540 }
2541 if (size_a < size_b ||
2542 (size_a == size_b &&
2543 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2544 /* |a| < |b|. */
2545 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2546 if (*pdiv == NULL)
2547 return -1;
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002548 *prem = (PyLongObject *)long_long((PyObject *)a);
2549 if (*prem == NULL) {
2550 Py_CLEAR(*pdiv);
2551 return -1;
2552 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 return 0;
2554 }
2555 if (size_b == 1) {
2556 digit rem = 0;
2557 z = divrem1(a, b->ob_digit[0], &rem);
2558 if (z == NULL)
2559 return -1;
2560 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2561 if (*prem == NULL) {
2562 Py_DECREF(z);
2563 return -1;
2564 }
2565 }
2566 else {
2567 z = x_divrem(a, b, prem);
2568 if (z == NULL)
2569 return -1;
2570 }
2571 /* Set the signs.
2572 The quotient z has the sign of a*b;
2573 the remainder r has the sign of a,
2574 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002575 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2576 _PyLong_Negate(&z);
2577 if (z == NULL) {
2578 Py_CLEAR(*prem);
2579 return -1;
2580 }
2581 }
2582 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2583 _PyLong_Negate(prem);
2584 if (*prem == NULL) {
2585 Py_DECREF(z);
2586 Py_CLEAR(*prem);
2587 return -1;
2588 }
2589 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 *pdiv = maybe_small_long(z);
2591 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002592}
2593
Serhiy Storchaka95949422013-08-27 19:40:23 +03002594/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002595 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002596
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002597static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002598x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 PyLongObject *v, *w, *a;
2601 Py_ssize_t i, k, size_v, size_w;
2602 int d;
2603 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2604 twodigits vv;
2605 sdigit zhi;
2606 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2609 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2610 handle the special case when the initial estimate q for a quotient
2611 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2612 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002615 size_v = Py_ABS(Py_SIZE(v1));
2616 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2618 v = _PyLong_New(size_v+1);
2619 if (v == NULL) {
2620 *prem = NULL;
2621 return NULL;
2622 }
2623 w = _PyLong_New(size_w);
2624 if (w == NULL) {
2625 Py_DECREF(v);
2626 *prem = NULL;
2627 return NULL;
2628 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2631 shift v1 left by the same amount. Results go into w and v. */
2632 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2633 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2634 assert(carry == 0);
2635 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2636 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2637 v->ob_digit[size_v] = carry;
2638 size_v++;
2639 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2642 at most (and usually exactly) k = size_v - size_w digits. */
2643 k = size_v - size_w;
2644 assert(k >= 0);
2645 a = _PyLong_New(k);
2646 if (a == NULL) {
2647 Py_DECREF(w);
2648 Py_DECREF(v);
2649 *prem = NULL;
2650 return NULL;
2651 }
2652 v0 = v->ob_digit;
2653 w0 = w->ob_digit;
2654 wm1 = w0[size_w-1];
2655 wm2 = w0[size_w-2];
2656 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2657 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2658 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002661 Py_DECREF(a);
2662 Py_DECREF(w);
2663 Py_DECREF(v);
2664 *prem = NULL;
2665 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002666 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 /* estimate quotient digit q; may overestimate by 1 (rare) */
2669 vtop = vk[size_w];
2670 assert(vtop <= wm1);
2671 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2672 q = (digit)(vv / wm1);
2673 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2674 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2675 | vk[size_w-2])) {
2676 --q;
2677 r += wm1;
2678 if (r >= PyLong_BASE)
2679 break;
2680 }
2681 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2684 zhi = 0;
2685 for (i = 0; i < size_w; ++i) {
2686 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2687 -PyLong_BASE * q <= z < PyLong_BASE */
2688 z = (sdigit)vk[i] + zhi -
2689 (stwodigits)q * (stwodigits)w0[i];
2690 vk[i] = (digit)z & PyLong_MASK;
2691 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002692 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 /* add w back if q was too large (this branch taken rarely) */
2696 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2697 if ((sdigit)vtop + zhi < 0) {
2698 carry = 0;
2699 for (i = 0; i < size_w; ++i) {
2700 carry += vk[i] + w0[i];
2701 vk[i] = carry & PyLong_MASK;
2702 carry >>= PyLong_SHIFT;
2703 }
2704 --q;
2705 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 /* store quotient digit */
2708 assert(q < PyLong_BASE);
2709 *--ak = q;
2710 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 /* unshift remainder; we reuse w to store the result */
2713 carry = v_rshift(w0, v0, size_w, d);
2714 assert(carry==0);
2715 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 *prem = long_normalize(w);
2718 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002719}
2720
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002721/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2722 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2723 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2724 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2725 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2726 -1.0. */
2727
2728/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2729#if DBL_MANT_DIG == 53
2730#define EXP2_DBL_MANT_DIG 9007199254740992.0
2731#else
2732#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2733#endif
2734
2735double
2736_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2739 /* See below for why x_digits is always large enough. */
2740 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2741 double dx;
2742 /* Correction term for round-half-to-even rounding. For a digit x,
2743 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2744 multiple of 4, rounding ties to a multiple of 8. */
2745 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002746
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002747 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 if (a_size == 0) {
2749 /* Special case for 0: significand 0.0, exponent 0. */
2750 *e = 0;
2751 return 0.0;
2752 }
2753 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2754 /* The following is an overflow-free version of the check
2755 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2756 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2757 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2758 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002759 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2763 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 Number of digits needed for result: write // for floor division.
2766 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2775 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2778 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2779 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 in both cases.
2786 */
2787 if (a_bits <= DBL_MANT_DIG + 2) {
2788 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2789 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2790 x_size = 0;
2791 while (x_size < shift_digits)
2792 x_digits[x_size++] = 0;
2793 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2794 (int)shift_bits);
2795 x_size += a_size;
2796 x_digits[x_size++] = rem;
2797 }
2798 else {
2799 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2800 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2801 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2802 a_size - shift_digits, (int)shift_bits);
2803 x_size = a_size - shift_digits;
2804 /* For correct rounding below, we need the least significant
2805 bit of x to be 'sticky' for this shift: if any of the bits
2806 shifted out was nonzero, we set the least significant bit
2807 of x. */
2808 if (rem)
2809 x_digits[0] |= 1;
2810 else
2811 while (shift_digits > 0)
2812 if (a->ob_digit[--shift_digits]) {
2813 x_digits[0] |= 1;
2814 break;
2815 }
2816 }
Victor Stinner63941882011-09-29 00:42:28 +02002817 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 /* Round, and convert to double. */
2820 x_digits[0] += half_even_correction[x_digits[0] & 7];
2821 dx = x_digits[--x_size];
2822 while (x_size > 0)
2823 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 /* Rescale; make correction if result is 1.0. */
2826 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2827 if (dx == 1.0) {
2828 if (a_bits == PY_SSIZE_T_MAX)
2829 goto overflow;
2830 dx = 0.5;
2831 a_bits += 1;
2832 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 *e = a_bits;
2835 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002836
2837 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 /* exponent > PY_SSIZE_T_MAX */
2839 PyErr_SetString(PyExc_OverflowError,
2840 "huge integer: number of bits overflows a Py_ssize_t");
2841 *e = 0;
2842 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002843}
2844
Serhiy Storchaka95949422013-08-27 19:40:23 +03002845/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002846 using the round-half-to-even rule in the case of a tie. */
2847
2848double
2849PyLong_AsDouble(PyObject *v)
2850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 Py_ssize_t exponent;
2852 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002853
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002854 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 PyErr_BadInternalCall();
2856 return -1.0;
2857 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002858 if (!PyLong_Check(v)) {
2859 PyErr_SetString(PyExc_TypeError, "an integer is required");
2860 return -1.0;
2861 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002862 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002863 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002864 to double. This improves performance of FP/long operations
2865 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002866 */
2867 return (double)MEDIUM_VALUE((PyLongObject *)v);
2868 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2870 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2871 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002872 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 return -1.0;
2874 }
2875 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002876}
2877
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002878/* Methods */
2879
2880static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002881long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002884}
2885
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002886static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002887long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 if (Py_SIZE(a) != Py_SIZE(b)) {
2892 sign = Py_SIZE(a) - Py_SIZE(b);
2893 }
2894 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002895 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2897 ;
2898 if (i < 0)
2899 sign = 0;
2900 else {
2901 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2902 if (Py_SIZE(a) < 0)
2903 sign = -sign;
2904 }
2905 }
2906 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002907}
2908
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002909#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002911
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002912static PyObject *
2913long_richcompare(PyObject *self, PyObject *other, int op)
2914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 int result;
2916 PyObject *v;
2917 CHECK_BINOP(self, other);
2918 if (self == other)
2919 result = 0;
2920 else
2921 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2922 /* Convert the return value to a Boolean */
2923 switch (op) {
2924 case Py_EQ:
2925 v = TEST_COND(result == 0);
2926 break;
2927 case Py_NE:
2928 v = TEST_COND(result != 0);
2929 break;
2930 case Py_LE:
2931 v = TEST_COND(result <= 0);
2932 break;
2933 case Py_GE:
2934 v = TEST_COND(result >= 0);
2935 break;
2936 case Py_LT:
2937 v = TEST_COND(result == -1);
2938 break;
2939 case Py_GT:
2940 v = TEST_COND(result == 1);
2941 break;
2942 default:
2943 PyErr_BadArgument();
2944 return NULL;
2945 }
2946 Py_INCREF(v);
2947 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002948}
2949
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002950static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002951long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002952{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002953 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 Py_ssize_t i;
2955 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 i = Py_SIZE(v);
2958 switch(i) {
2959 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2960 case 0: return 0;
2961 case 1: return v->ob_digit[0];
2962 }
2963 sign = 1;
2964 x = 0;
2965 if (i < 0) {
2966 sign = -1;
2967 i = -(i);
2968 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002970 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2971 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2972 _PyHASH_MODULUS.
2973
2974 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2975 amounts to a rotation of the bits of x. To see this, write
2976
2977 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2978
2979 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2980 PyLong_SHIFT bits of x (those that are shifted out of the
2981 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2982 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2983 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2984 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2985 congruent to y modulo _PyHASH_MODULUS. So
2986
2987 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2988
2989 The right-hand side is just the result of rotating the
2990 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2991 not all _PyHASH_BITS bits of x are 1s, the same is true
2992 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2993 the reduction of x*2**PyLong_SHIFT modulo
2994 _PyHASH_MODULUS. */
2995 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2996 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002998 if (x >= _PyHASH_MODULUS)
2999 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 }
3001 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003002 if (x == (Py_uhash_t)-1)
3003 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003004 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003005}
3006
3007
Serhiy Storchaka95949422013-08-27 19:40:23 +03003008/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003009
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003010static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003011x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003012{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003013 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 PyLongObject *z;
3015 Py_ssize_t i;
3016 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 /* Ensure a is the larger of the two: */
3019 if (size_a < size_b) {
3020 { PyLongObject *temp = a; a = b; b = temp; }
3021 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003022 size_a = size_b;
3023 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 }
3025 z = _PyLong_New(size_a+1);
3026 if (z == NULL)
3027 return NULL;
3028 for (i = 0; i < size_b; ++i) {
3029 carry += a->ob_digit[i] + b->ob_digit[i];
3030 z->ob_digit[i] = carry & PyLong_MASK;
3031 carry >>= PyLong_SHIFT;
3032 }
3033 for (; i < size_a; ++i) {
3034 carry += a->ob_digit[i];
3035 z->ob_digit[i] = carry & PyLong_MASK;
3036 carry >>= PyLong_SHIFT;
3037 }
3038 z->ob_digit[i] = carry;
3039 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003040}
3041
3042/* Subtract the absolute values of two integers. */
3043
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003044static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003045x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003046{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003047 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 PyLongObject *z;
3049 Py_ssize_t i;
3050 int sign = 1;
3051 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 /* Ensure a is the larger of the two: */
3054 if (size_a < size_b) {
3055 sign = -1;
3056 { PyLongObject *temp = a; a = b; b = temp; }
3057 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003058 size_a = size_b;
3059 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 }
3061 else if (size_a == size_b) {
3062 /* Find highest digit where a and b differ: */
3063 i = size_a;
3064 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3065 ;
3066 if (i < 0)
3067 return (PyLongObject *)PyLong_FromLong(0);
3068 if (a->ob_digit[i] < b->ob_digit[i]) {
3069 sign = -1;
3070 { PyLongObject *temp = a; a = b; b = temp; }
3071 }
3072 size_a = size_b = i+1;
3073 }
3074 z = _PyLong_New(size_a);
3075 if (z == NULL)
3076 return NULL;
3077 for (i = 0; i < size_b; ++i) {
3078 /* The following assumes unsigned arithmetic
3079 works module 2**N for some N>PyLong_SHIFT. */
3080 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3081 z->ob_digit[i] = borrow & PyLong_MASK;
3082 borrow >>= PyLong_SHIFT;
3083 borrow &= 1; /* Keep only one sign bit */
3084 }
3085 for (; i < size_a; ++i) {
3086 borrow = a->ob_digit[i] - borrow;
3087 z->ob_digit[i] = borrow & PyLong_MASK;
3088 borrow >>= PyLong_SHIFT;
3089 borrow &= 1; /* Keep only one sign bit */
3090 }
3091 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003092 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003093 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003094 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003096}
3097
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003098static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003099long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003104
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003105 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003106 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 }
3108 if (Py_SIZE(a) < 0) {
3109 if (Py_SIZE(b) < 0) {
3110 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003111 if (z != NULL) {
3112 /* x_add received at least one multiple-digit int,
3113 and thus z must be a multiple-digit int.
3114 That also means z is not an element of
3115 small_ints, so negating it in-place is safe. */
3116 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 }
3120 else
3121 z = x_sub(b, a);
3122 }
3123 else {
3124 if (Py_SIZE(b) < 0)
3125 z = x_sub(a, b);
3126 else
3127 z = x_add(a, b);
3128 }
3129 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003130}
3131
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003132static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003133long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003138
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003139 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003140 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 }
3142 if (Py_SIZE(a) < 0) {
3143 if (Py_SIZE(b) < 0)
3144 z = x_sub(a, b);
3145 else
3146 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003147 if (z != NULL) {
3148 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003150 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 }
3152 else {
3153 if (Py_SIZE(b) < 0)
3154 z = x_add(a, b);
3155 else
3156 z = x_sub(a, b);
3157 }
3158 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003159}
3160
Tim Peters5af4e6c2002-08-12 02:31:19 +00003161/* Grade school multiplication, ignoring the signs.
3162 * Returns the absolute value of the product, or NULL if error.
3163 */
3164static PyLongObject *
3165x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003168 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3169 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 z = _PyLong_New(size_a + size_b);
3173 if (z == NULL)
3174 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3177 if (a == b) {
3178 /* Efficient squaring per HAC, Algorithm 14.16:
3179 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3180 * Gives slightly less than a 2x speedup when a == b,
3181 * via exploiting that each entry in the multiplication
3182 * pyramid appears twice (except for the size_a squares).
3183 */
3184 for (i = 0; i < size_a; ++i) {
3185 twodigits carry;
3186 twodigits f = a->ob_digit[i];
3187 digit *pz = z->ob_digit + (i << 1);
3188 digit *pa = a->ob_digit + i + 1;
3189 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003192 Py_DECREF(z);
3193 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003194 });
Tim Peters0973b992004-08-29 22:16:50 +00003195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 carry = *pz + f * f;
3197 *pz++ = (digit)(carry & PyLong_MASK);
3198 carry >>= PyLong_SHIFT;
3199 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 /* Now f is added in twice in each column of the
3202 * pyramid it appears. Same as adding f<<1 once.
3203 */
3204 f <<= 1;
3205 while (pa < paend) {
3206 carry += *pz + *pa++ * f;
3207 *pz++ = (digit)(carry & PyLong_MASK);
3208 carry >>= PyLong_SHIFT;
3209 assert(carry <= (PyLong_MASK << 1));
3210 }
3211 if (carry) {
3212 carry += *pz;
3213 *pz++ = (digit)(carry & PyLong_MASK);
3214 carry >>= PyLong_SHIFT;
3215 }
3216 if (carry)
3217 *pz += (digit)(carry & PyLong_MASK);
3218 assert((carry >> PyLong_SHIFT) == 0);
3219 }
3220 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003221 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 for (i = 0; i < size_a; ++i) {
3223 twodigits carry = 0;
3224 twodigits f = a->ob_digit[i];
3225 digit *pz = z->ob_digit + i;
3226 digit *pb = b->ob_digit;
3227 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003230 Py_DECREF(z);
3231 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003232 });
Tim Peters0973b992004-08-29 22:16:50 +00003233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 while (pb < pbend) {
3235 carry += *pz + *pb++ * f;
3236 *pz++ = (digit)(carry & PyLong_MASK);
3237 carry >>= PyLong_SHIFT;
3238 assert(carry <= PyLong_MASK);
3239 }
3240 if (carry)
3241 *pz += (digit)(carry & PyLong_MASK);
3242 assert((carry >> PyLong_SHIFT) == 0);
3243 }
3244 }
3245 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003246}
3247
3248/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003249 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003250 split, and sets low and high such that abs(n) == (high << size) + low,
3251 viewing the shift as being by digits. The sign bit is ignored, and
3252 the return values are >= 0.
3253 Returns 0 on success, -1 on failure.
3254*/
3255static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003256kmul_split(PyLongObject *n,
3257 Py_ssize_t size,
3258 PyLongObject **high,
3259 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 PyLongObject *hi, *lo;
3262 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003263 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003264
Victor Stinner640c35c2013-06-04 23:14:37 +02003265 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 if ((hi = _PyLong_New(size_hi)) == NULL)
3269 return -1;
3270 if ((lo = _PyLong_New(size_lo)) == NULL) {
3271 Py_DECREF(hi);
3272 return -1;
3273 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3276 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 *high = long_normalize(hi);
3279 *low = long_normalize(lo);
3280 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003281}
3282
Tim Peters60004642002-08-12 22:01:34 +00003283static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3284
Tim Peters5af4e6c2002-08-12 02:31:19 +00003285/* Karatsuba multiplication. Ignores the input signs, and returns the
3286 * absolute value of the product (or NULL if error).
3287 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3288 */
3289static PyLongObject *
3290k_mul(PyLongObject *a, PyLongObject *b)
3291{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003292 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3293 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 PyLongObject *ah = NULL;
3295 PyLongObject *al = NULL;
3296 PyLongObject *bh = NULL;
3297 PyLongObject *bl = NULL;
3298 PyLongObject *ret = NULL;
3299 PyLongObject *t1, *t2, *t3;
3300 Py_ssize_t shift; /* the number of digits we split off */
3301 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3304 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3305 * Then the original product is
3306 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3307 * By picking X to be a power of 2, "*X" is just shifting, and it's
3308 * been reduced to 3 multiplies on numbers half the size.
3309 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 /* We want to split based on the larger number; fiddle so that b
3312 * is largest.
3313 */
3314 if (asize > bsize) {
3315 t1 = a;
3316 a = b;
3317 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 i = asize;
3320 asize = bsize;
3321 bsize = i;
3322 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 /* Use gradeschool math when either number is too small. */
3325 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3326 if (asize <= i) {
3327 if (asize == 0)
3328 return (PyLongObject *)PyLong_FromLong(0);
3329 else
3330 return x_mul(a, b);
3331 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 /* If a is small compared to b, splitting on b gives a degenerate
3334 * case with ah==0, and Karatsuba may be (even much) less efficient
3335 * than "grade school" then. However, we can still win, by viewing
3336 * b as a string of "big digits", each of width a->ob_size. That
3337 * leads to a sequence of balanced calls to k_mul.
3338 */
3339 if (2 * asize <= bsize)
3340 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 /* Split a & b into hi & lo pieces. */
3343 shift = bsize >> 1;
3344 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3345 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 if (a == b) {
3348 bh = ah;
3349 bl = al;
3350 Py_INCREF(bh);
3351 Py_INCREF(bl);
3352 }
3353 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 /* The plan:
3356 * 1. Allocate result space (asize + bsize digits: that's always
3357 * enough).
3358 * 2. Compute ah*bh, and copy into result at 2*shift.
3359 * 3. Compute al*bl, and copy into result at 0. Note that this
3360 * can't overlap with #2.
3361 * 4. Subtract al*bl from the result, starting at shift. This may
3362 * underflow (borrow out of the high digit), but we don't care:
3363 * we're effectively doing unsigned arithmetic mod
3364 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3365 * borrows and carries out of the high digit can be ignored.
3366 * 5. Subtract ah*bh from the result, starting at shift.
3367 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3368 * at shift.
3369 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 /* 1. Allocate result space. */
3372 ret = _PyLong_New(asize + bsize);
3373 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003374#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 /* Fill with trash, to catch reference to uninitialized digits. */
3376 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003377#endif
Tim Peters44121a62002-08-12 06:17:58 +00003378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3380 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3381 assert(Py_SIZE(t1) >= 0);
3382 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3383 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3384 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 /* Zero-out the digits higher than the ah*bh copy. */
3387 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3388 if (i)
3389 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3390 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 /* 3. t2 <- al*bl, and copy into the low digits. */
3393 if ((t2 = k_mul(al, bl)) == NULL) {
3394 Py_DECREF(t1);
3395 goto fail;
3396 }
3397 assert(Py_SIZE(t2) >= 0);
3398 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3399 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 /* Zero out remaining digits. */
3402 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3403 if (i)
3404 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3407 * because it's fresher in cache.
3408 */
3409 i = Py_SIZE(ret) - shift; /* # digits after shift */
3410 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3411 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3414 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3417 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3418 Py_DECREF(ah);
3419 Py_DECREF(al);
3420 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 if (a == b) {
3423 t2 = t1;
3424 Py_INCREF(t2);
3425 }
3426 else if ((t2 = x_add(bh, bl)) == NULL) {
3427 Py_DECREF(t1);
3428 goto fail;
3429 }
3430 Py_DECREF(bh);
3431 Py_DECREF(bl);
3432 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 t3 = k_mul(t1, t2);
3435 Py_DECREF(t1);
3436 Py_DECREF(t2);
3437 if (t3 == NULL) goto fail;
3438 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 /* Add t3. It's not obvious why we can't run out of room here.
3441 * See the (*) comment after this function.
3442 */
3443 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3444 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003447
Mark Dickinson22b20182010-05-10 21:27:53 +00003448 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 Py_XDECREF(ret);
3450 Py_XDECREF(ah);
3451 Py_XDECREF(al);
3452 Py_XDECREF(bh);
3453 Py_XDECREF(bl);
3454 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003455}
3456
Tim Petersd6974a52002-08-13 20:37:51 +00003457/* (*) Why adding t3 can't "run out of room" above.
3458
Tim Petersab86c2b2002-08-15 20:06:00 +00003459Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3460to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003461
Tim Petersab86c2b2002-08-15 20:06:00 +000034621. For any integer i, i = c(i/2) + f(i/2). In particular,
3463 bsize = c(bsize/2) + f(bsize/2).
34642. shift = f(bsize/2)
34653. asize <= bsize
34664. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3467 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003468
Tim Petersab86c2b2002-08-15 20:06:00 +00003469We allocated asize + bsize result digits, and add t3 into them at an offset
3470of shift. This leaves asize+bsize-shift allocated digit positions for t3
3471to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3472asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003473
Tim Petersab86c2b2002-08-15 20:06:00 +00003474bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3475at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003476
Tim Petersab86c2b2002-08-15 20:06:00 +00003477If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3478digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3479most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003480
Tim Petersab86c2b2002-08-15 20:06:00 +00003481The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003482
Tim Petersab86c2b2002-08-15 20:06:00 +00003483 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003484
Tim Petersab86c2b2002-08-15 20:06:00 +00003485and we have asize + c(bsize/2) available digit positions. We need to show
3486this is always enough. An instance of c(bsize/2) cancels out in both, so
3487the question reduces to whether asize digits is enough to hold
3488(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3489then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3490asize 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 +00003491digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003492asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003493c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3494is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3495bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003496
Tim Peters48d52c02002-08-14 17:07:32 +00003497Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3498clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3499ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003500*/
3501
Tim Peters60004642002-08-12 22:01:34 +00003502/* b has at least twice the digits of a, and a is big enough that Karatsuba
3503 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3504 * of slices, each with a->ob_size digits, and multiply the slices by a,
3505 * one at a time. This gives k_mul balanced inputs to work with, and is
3506 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003507 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003508 * single-width slice overlap between successive partial sums).
3509 */
3510static PyLongObject *
3511k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3512{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003513 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3514 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 Py_ssize_t nbdone; /* # of b digits already multiplied */
3516 PyLongObject *ret;
3517 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 assert(asize > KARATSUBA_CUTOFF);
3520 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 /* Allocate result space, and zero it out. */
3523 ret = _PyLong_New(asize + bsize);
3524 if (ret == NULL)
3525 return NULL;
3526 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 /* Successive slices of b are copied into bslice. */
3529 bslice = _PyLong_New(asize);
3530 if (bslice == NULL)
3531 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 nbdone = 0;
3534 while (bsize > 0) {
3535 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003536 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 /* Multiply the next slice of b by a. */
3539 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3540 nbtouse * sizeof(digit));
3541 Py_SIZE(bslice) = nbtouse;
3542 product = k_mul(a, bslice);
3543 if (product == NULL)
3544 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 /* Add into result. */
3547 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3548 product->ob_digit, Py_SIZE(product));
3549 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 bsize -= nbtouse;
3552 nbdone += nbtouse;
3553 }
Tim Peters60004642002-08-12 22:01:34 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 Py_DECREF(bslice);
3556 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003557
Mark Dickinson22b20182010-05-10 21:27:53 +00003558 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 Py_DECREF(ret);
3560 Py_XDECREF(bslice);
3561 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003562}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003563
3564static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003565long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003572 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003574 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 z = k_mul(a, b);
3578 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003579 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3580 _PyLong_Negate(&z);
3581 if (z == NULL)
3582 return NULL;
3583 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003585}
3586
Yury Selivanove0b23092016-02-11 10:26:27 -05003587/* Fast modulo division for single-digit longs. */
3588static PyObject *
3589fast_mod(PyLongObject *a, PyLongObject *b)
3590{
3591 sdigit left = a->ob_digit[0];
3592 sdigit right = b->ob_digit[0];
3593 sdigit mod;
3594
3595 assert(Py_ABS(Py_SIZE(a)) == 1);
3596 assert(Py_ABS(Py_SIZE(b)) == 1);
3597
3598 if (Py_SIZE(a) == Py_SIZE(b)) {
3599 /* 'a' and 'b' have the same sign. */
3600 mod = left % right;
3601 }
3602 else {
3603 /* Either 'a' or 'b' is negative. */
3604 mod = right - 1 - (left - 1) % right;
3605 }
3606
Victor Stinnerf963c132016-03-23 18:36:54 +01003607 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003608}
3609
3610/* Fast floor division for single-digit longs. */
3611static PyObject *
3612fast_floor_div(PyLongObject *a, PyLongObject *b)
3613{
3614 sdigit left = a->ob_digit[0];
3615 sdigit right = b->ob_digit[0];
3616 sdigit div;
3617
3618 assert(Py_ABS(Py_SIZE(a)) == 1);
3619 assert(Py_ABS(Py_SIZE(b)) == 1);
3620
3621 if (Py_SIZE(a) == Py_SIZE(b)) {
3622 /* 'a' and 'b' have the same sign. */
3623 div = left / right;
3624 }
3625 else {
3626 /* Either 'a' or 'b' is negative. */
3627 div = -1 - (left - 1) / right;
3628 }
3629
3630 return PyLong_FromLong(div);
3631}
3632
Guido van Rossume32e0141992-01-19 16:31:05 +00003633/* The / and % operators are now defined in terms of divmod().
3634 The expression a mod b has the value a - b*floor(a/b).
3635 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003636 |a| by |b|, with the sign of a. This is also expressed
3637 as a - b*trunc(a/b), if trunc truncates towards zero.
3638 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 a b a rem b a mod b
3640 13 10 3 3
3641 -13 10 -3 7
3642 13 -10 3 -7
3643 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003644 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003645 have different signs. We then subtract one from the 'div'
3646 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003647
Tim Peters47e52ee2004-08-30 02:44:38 +00003648/* Compute
3649 * *pdiv, *pmod = divmod(v, w)
3650 * NULL can be passed for pdiv or pmod, in which case that part of
3651 * the result is simply thrown away. The caller owns a reference to
3652 * each of these it requests (does not pass NULL for).
3653 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003654static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003655l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003659
Yury Selivanove0b23092016-02-11 10:26:27 -05003660 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3661 /* Fast path for single-digit longs */
3662 div = NULL;
3663 if (pdiv != NULL) {
3664 div = (PyLongObject *)fast_floor_div(v, w);
3665 if (div == NULL) {
3666 return -1;
3667 }
3668 }
3669 if (pmod != NULL) {
3670 mod = (PyLongObject *)fast_mod(v, w);
3671 if (mod == NULL) {
3672 Py_XDECREF(div);
3673 return -1;
3674 }
3675 *pmod = mod;
3676 }
3677 if (pdiv != NULL) {
3678 /* We only want to set `*pdiv` when `*pmod` is
3679 set successfully. */
3680 *pdiv = div;
3681 }
3682 return 0;
3683 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 if (long_divrem(v, w, &div, &mod) < 0)
3685 return -1;
3686 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3687 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3688 PyLongObject *temp;
3689 PyLongObject *one;
3690 temp = (PyLongObject *) long_add(mod, w);
3691 Py_DECREF(mod);
3692 mod = temp;
3693 if (mod == NULL) {
3694 Py_DECREF(div);
3695 return -1;
3696 }
3697 one = (PyLongObject *) PyLong_FromLong(1L);
3698 if (one == NULL ||
3699 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3700 Py_DECREF(mod);
3701 Py_DECREF(div);
3702 Py_XDECREF(one);
3703 return -1;
3704 }
3705 Py_DECREF(one);
3706 Py_DECREF(div);
3707 div = temp;
3708 }
3709 if (pdiv != NULL)
3710 *pdiv = div;
3711 else
3712 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 if (pmod != NULL)
3715 *pmod = mod;
3716 else
3717 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003720}
3721
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003722static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003723long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003728
3729 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3730 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3731 }
3732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3734 div = NULL;
3735 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003736}
3737
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003738/* PyLong/PyLong -> float, with correctly rounded result. */
3739
3740#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3741#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3742
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003743static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003744long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 PyLongObject *a, *b, *x;
3747 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3748 digit mask, low;
3749 int inexact, negate, a_is_small, b_is_small;
3750 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 CHECK_BINOP(v, w);
3753 a = (PyLongObject *)v;
3754 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 /*
3757 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3760 1. choose a suitable integer 'shift'
3761 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3762 3. adjust x for correct rounding
3763 4. convert x to a double dx with the same value
3764 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3769 returns either 0.0 or -0.0, depending on the sign of b. For a and
3770 b both nonzero, ignore signs of a and b, and add the sign back in
3771 at the end. Now write a_bits and b_bits for the bit lengths of a
3772 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3773 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3778 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3779 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3780 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 1. The integer 'shift' is chosen so that x has the right number of
3785 bits for a double, plus two or three extra bits that will be used
3786 in the rounding decisions. Writing a_bits and b_bits for the
3787 number of significant bits in a and b respectively, a
3788 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 This is fine in the usual case, but if a/b is smaller than the
3793 smallest normal float then it can lead to double rounding on an
3794 IEEE 754 platform, giving incorrectly rounded results. So we
3795 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 2. The quantity x is computed by first shifting a (left -shift bits
3800 if shift <= 0, right shift bits if shift > 0) and then dividing by
3801 b. For both the shift and the division, we keep track of whether
3802 the result is inexact, in a flag 'inexact'; this information is
3803 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 With the choice of shift above, together with our assumption that
3806 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3807 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3810 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 For float representability, we need x/2**extra_bits <
3815 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3816 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 To round, we just modify the bottom digit of x in-place; this can
3821 end up giving a digit with value > PyLONG_MASK, but that's not a
3822 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 With the original choices for shift above, extra_bits will always
3825 be 2 or 3. Then rounding under the round-half-to-even rule, we
3826 round up iff the most significant of the extra bits is 1, and
3827 either: (a) the computation of x in step 2 had an inexact result,
3828 or (b) at least one other of the extra bits is 1, or (c) the least
3829 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 4. Conversion to a double is straightforward; all floating-point
3832 operations involved in the conversion are exact, so there's no
3833 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3836 The result will always be exactly representable as a double, except
3837 in the case that it overflows. To avoid dependence on the exact
3838 behaviour of ldexp on overflow, we check for overflow before
3839 applying ldexp. The result of ldexp is adjusted for sign before
3840 returning.
3841 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003844 a_size = Py_ABS(Py_SIZE(a));
3845 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3847 if (b_size == 0) {
3848 PyErr_SetString(PyExc_ZeroDivisionError,
3849 "division by zero");
3850 goto error;
3851 }
3852 if (a_size == 0)
3853 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 /* Fast path for a and b small (exactly representable in a double).
3856 Relies on floating-point division being correctly rounded; results
3857 may be subject to double rounding on x86 machines that operate with
3858 the x87 FPU set to 64-bit precision. */
3859 a_is_small = a_size <= MANT_DIG_DIGITS ||
3860 (a_size == MANT_DIG_DIGITS+1 &&
3861 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3862 b_is_small = b_size <= MANT_DIG_DIGITS ||
3863 (b_size == MANT_DIG_DIGITS+1 &&
3864 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3865 if (a_is_small && b_is_small) {
3866 double da, db;
3867 da = a->ob_digit[--a_size];
3868 while (a_size > 0)
3869 da = da * PyLong_BASE + a->ob_digit[--a_size];
3870 db = b->ob_digit[--b_size];
3871 while (b_size > 0)
3872 db = db * PyLong_BASE + b->ob_digit[--b_size];
3873 result = da / db;
3874 goto success;
3875 }
Tim Peterse2a60002001-09-04 06:17:36 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 /* Catch obvious cases of underflow and overflow */
3878 diff = a_size - b_size;
3879 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3880 /* Extreme overflow */
3881 goto overflow;
3882 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3883 /* Extreme underflow */
3884 goto underflow_or_zero;
3885 /* Next line is now safe from overflowing a Py_ssize_t */
3886 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3887 bits_in_digit(b->ob_digit[b_size - 1]);
3888 /* Now diff = a_bits - b_bits. */
3889 if (diff > DBL_MAX_EXP)
3890 goto overflow;
3891 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3892 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003895 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 /* x = abs(a * 2**-shift) */
3900 if (shift <= 0) {
3901 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3902 digit rem;
3903 /* x = a << -shift */
3904 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3905 /* In practice, it's probably impossible to end up
3906 here. Both a and b would have to be enormous,
3907 using close to SIZE_T_MAX bytes of memory each. */
3908 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003909 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 goto error;
3911 }
3912 x = _PyLong_New(a_size + shift_digits + 1);
3913 if (x == NULL)
3914 goto error;
3915 for (i = 0; i < shift_digits; i++)
3916 x->ob_digit[i] = 0;
3917 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3918 a_size, -shift % PyLong_SHIFT);
3919 x->ob_digit[a_size + shift_digits] = rem;
3920 }
3921 else {
3922 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3923 digit rem;
3924 /* x = a >> shift */
3925 assert(a_size >= shift_digits);
3926 x = _PyLong_New(a_size - shift_digits);
3927 if (x == NULL)
3928 goto error;
3929 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3930 a_size - shift_digits, shift % PyLong_SHIFT);
3931 /* set inexact if any of the bits shifted out is nonzero */
3932 if (rem)
3933 inexact = 1;
3934 while (!inexact && shift_digits > 0)
3935 if (a->ob_digit[--shift_digits])
3936 inexact = 1;
3937 }
3938 long_normalize(x);
3939 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3942 reference to x, so it's safe to modify it in-place. */
3943 if (b_size == 1) {
3944 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3945 b->ob_digit[0]);
3946 long_normalize(x);
3947 if (rem)
3948 inexact = 1;
3949 }
3950 else {
3951 PyLongObject *div, *rem;
3952 div = x_divrem(x, b, &rem);
3953 Py_DECREF(x);
3954 x = div;
3955 if (x == NULL)
3956 goto error;
3957 if (Py_SIZE(rem))
3958 inexact = 1;
3959 Py_DECREF(rem);
3960 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003961 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 assert(x_size > 0); /* result of division is never zero */
3963 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003966 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 /* Round by directly modifying the low digit of x. */
3970 mask = (digit)1 << (extra_bits - 1);
3971 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003972 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003974 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 /* Convert x to a double dx; the conversion is exact. */
3977 dx = x->ob_digit[--x_size];
3978 while (x_size > 0)
3979 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3980 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 /* Check whether ldexp result will overflow a double. */
3983 if (shift + x_bits >= DBL_MAX_EXP &&
3984 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3985 goto overflow;
3986 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003987
3988 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003990
3991 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003993
3994 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 PyErr_SetString(PyExc_OverflowError,
3996 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003997 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003999}
4000
4001static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004002long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 CHECK_BINOP(a, b);
4007
Yury Selivanove0b23092016-02-11 10:26:27 -05004008 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4009 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4010 }
4011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4013 mod = NULL;
4014 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004015}
4016
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004017static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004018long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 PyLongObject *div, *mod;
4021 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4026 return NULL;
4027 }
4028 z = PyTuple_New(2);
4029 if (z != NULL) {
4030 PyTuple_SetItem(z, 0, (PyObject *) div);
4031 PyTuple_SetItem(z, 1, (PyObject *) mod);
4032 }
4033 else {
4034 Py_DECREF(div);
4035 Py_DECREF(mod);
4036 }
4037 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004038}
4039
Tim Peters47e52ee2004-08-30 02:44:38 +00004040/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004041static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004042long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4045 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 PyLongObject *z = NULL; /* accumulated result */
4048 Py_ssize_t i, j, k; /* counters */
4049 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 /* 5-ary values. If the exponent is large enough, table is
4052 * precomputed so that table[i] == a**i % c for i in range(32).
4053 */
4054 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4055 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 /* a, b, c = v, w, x */
4058 CHECK_BINOP(v, w);
4059 a = (PyLongObject*)v; Py_INCREF(a);
4060 b = (PyLongObject*)w; Py_INCREF(b);
4061 if (PyLong_Check(x)) {
4062 c = (PyLongObject *)x;
4063 Py_INCREF(x);
4064 }
4065 else if (x == Py_None)
4066 c = NULL;
4067 else {
4068 Py_DECREF(a);
4069 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004070 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 }
Tim Peters4c483c42001-09-05 06:24:58 +00004072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 if (Py_SIZE(b) < 0) { /* if exponent is negative */
4074 if (c) {
Mark Dickinson0c346d82014-04-11 14:34:40 -04004075 PyErr_SetString(PyExc_ValueError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00004076 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 goto Error;
4078 }
4079 else {
4080 /* else return a float. This works because we know
4081 that this calls float_pow() which converts its
4082 arguments to double. */
4083 Py_DECREF(a);
4084 Py_DECREF(b);
4085 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
4086 }
4087 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 if (c) {
4090 /* if modulus == 0:
4091 raise ValueError() */
4092 if (Py_SIZE(c) == 0) {
4093 PyErr_SetString(PyExc_ValueError,
4094 "pow() 3rd argument cannot be 0");
4095 goto Error;
4096 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 /* if modulus < 0:
4099 negativeOutput = True
4100 modulus = -modulus */
4101 if (Py_SIZE(c) < 0) {
4102 negativeOutput = 1;
4103 temp = (PyLongObject *)_PyLong_Copy(c);
4104 if (temp == NULL)
4105 goto Error;
4106 Py_DECREF(c);
4107 c = temp;
4108 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004109 _PyLong_Negate(&c);
4110 if (c == NULL)
4111 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 /* if modulus == 1:
4115 return 0 */
4116 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4117 z = (PyLongObject *)PyLong_FromLong(0L);
4118 goto Done;
4119 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004120
Tim Peters81a93152013-10-05 16:53:52 -05004121 /* Reduce base by modulus in some cases:
4122 1. If base < 0. Forcing the base non-negative makes things easier.
4123 2. If base is obviously larger than the modulus. The "small
4124 exponent" case later can multiply directly by base repeatedly,
4125 while the "large exponent" case multiplies directly by base 31
4126 times. It can be unboundedly faster to multiply by
4127 base % modulus instead.
4128 We could _always_ do this reduction, but l_divmod() isn't cheap,
4129 so we only do it when it buys something. */
4130 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 if (l_divmod(a, c, NULL, &temp) < 0)
4132 goto Error;
4133 Py_DECREF(a);
4134 a = temp;
4135 temp = NULL;
4136 }
4137 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 /* At this point a, b, and c are guaranteed non-negative UNLESS
4140 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 z = (PyLongObject *)PyLong_FromLong(1L);
4143 if (z == NULL)
4144 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 /* Perform a modular reduction, X = X % c, but leave X alone if c
4147 * is NULL.
4148 */
4149#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004150 do { \
4151 if (c != NULL) { \
4152 if (l_divmod(X, c, NULL, &temp) < 0) \
4153 goto Error; \
4154 Py_XDECREF(X); \
4155 X = temp; \
4156 temp = NULL; \
4157 } \
4158 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 /* Multiply two values, then reduce the result:
4161 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004162#define MULT(X, Y, result) \
4163 do { \
4164 temp = (PyLongObject *)long_mul(X, Y); \
4165 if (temp == NULL) \
4166 goto Error; \
4167 Py_XDECREF(result); \
4168 result = temp; \
4169 temp = NULL; \
4170 REDUCE(result); \
4171 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4174 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4175 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4176 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4177 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004180 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004182 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 }
4184 }
4185 }
4186 else {
4187 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4188 Py_INCREF(z); /* still holds 1L */
4189 table[0] = z;
4190 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004191 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4194 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4197 const int index = (bi >> j) & 0x1f;
4198 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004199 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004201 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 }
4203 }
4204 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 if (negativeOutput && (Py_SIZE(z) != 0)) {
4207 temp = (PyLongObject *)long_sub(z, c);
4208 if (temp == NULL)
4209 goto Error;
4210 Py_DECREF(z);
4211 z = temp;
4212 temp = NULL;
4213 }
4214 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004215
Mark Dickinson22b20182010-05-10 21:27:53 +00004216 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004217 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004219 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4221 for (i = 0; i < 32; ++i)
4222 Py_XDECREF(table[i]);
4223 }
4224 Py_DECREF(a);
4225 Py_DECREF(b);
4226 Py_XDECREF(c);
4227 Py_XDECREF(temp);
4228 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004229}
4230
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004231static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004232long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 /* Implement ~x as -(x+1) */
4235 PyLongObject *x;
4236 PyLongObject *w;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004237 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
4239 w = (PyLongObject *)PyLong_FromLong(1L);
4240 if (w == NULL)
4241 return NULL;
4242 x = (PyLongObject *) long_add(v, w);
4243 Py_DECREF(w);
4244 if (x == NULL)
4245 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004246 _PyLong_Negate(&x);
4247 /* No need for maybe_small_long here, since any small
4248 longs will have been caught in the Py_SIZE <= 1 fast path. */
4249 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004250}
4251
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004252static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004253long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004256 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 return PyLong_FromLong(-MEDIUM_VALUE(v));
4258 z = (PyLongObject *)_PyLong_Copy(v);
4259 if (z != NULL)
4260 Py_SIZE(z) = -(Py_SIZE(v));
4261 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004262}
4263
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004264static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004265long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 if (Py_SIZE(v) < 0)
4268 return long_neg(v);
4269 else
4270 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004271}
4272
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004273static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004274long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004277}
4278
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004279static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004280long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 PyLongObject *z = NULL;
4283 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4284 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 if (Py_SIZE(a) < 0) {
4289 /* Right shifting negative numbers is harder */
4290 PyLongObject *a1, *a2;
4291 a1 = (PyLongObject *) long_invert(a);
4292 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004293 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 a2 = (PyLongObject *) long_rshift(a1, b);
4295 Py_DECREF(a1);
4296 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004297 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 z = (PyLongObject *) long_invert(a2);
4299 Py_DECREF(a2);
4300 }
4301 else {
4302 shiftby = PyLong_AsSsize_t((PyObject *)b);
4303 if (shiftby == -1L && PyErr_Occurred())
Mark Dickinson92ca5352016-09-17 17:50:50 +01004304 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 if (shiftby < 0) {
4306 PyErr_SetString(PyExc_ValueError,
4307 "negative shift count");
Mark Dickinson92ca5352016-09-17 17:50:50 +01004308 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 }
4310 wordshift = shiftby / PyLong_SHIFT;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004311 newsize = Py_ABS(Py_SIZE(a)) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 if (newsize <= 0)
4313 return PyLong_FromLong(0);
4314 loshift = shiftby % PyLong_SHIFT;
4315 hishift = PyLong_SHIFT - loshift;
4316 lomask = ((digit)1 << hishift) - 1;
4317 himask = PyLong_MASK ^ lomask;
4318 z = _PyLong_New(newsize);
4319 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004320 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4322 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4323 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004324 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004326 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004328 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004329}
4330
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004331static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004332long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 /* This version due to Tim Peters */
4335 PyLongObject *a = (PyLongObject*)v;
4336 PyLongObject *b = (PyLongObject*)w;
4337 PyLongObject *z = NULL;
4338 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4339 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 shiftby = PyLong_AsSsize_t((PyObject *)b);
4344 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004345 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 if (shiftby < 0) {
4347 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004348 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004350
4351 if (Py_SIZE(a) == 0) {
4352 return PyLong_FromLong(0);
4353 }
4354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4356 wordshift = shiftby / PyLong_SHIFT;
4357 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004358
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004359 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 newsize = oldsize + wordshift;
4361 if (remshift)
4362 ++newsize;
4363 z = _PyLong_New(newsize);
4364 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004365 return NULL;
4366 if (Py_SIZE(a) < 0) {
4367 assert(Py_REFCNT(z) == 1);
4368 Py_SIZE(z) = -Py_SIZE(z);
4369 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 for (i = 0; i < wordshift; i++)
4371 z->ob_digit[i] = 0;
4372 accum = 0;
4373 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4374 accum |= (twodigits)a->ob_digit[j] << remshift;
4375 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4376 accum >>= PyLong_SHIFT;
4377 }
4378 if (remshift)
4379 z->ob_digit[newsize-1] = (digit)accum;
4380 else
4381 assert(!accum);
4382 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004384}
4385
Mark Dickinson27a87a22009-10-25 20:43:34 +00004386/* Compute two's complement of digit vector a[0:m], writing result to
4387 z[0:m]. The digit vector a need not be normalized, but should not
4388 be entirely zero. a and z may point to the same digit vector. */
4389
4390static void
4391v_complement(digit *z, digit *a, Py_ssize_t m)
4392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 Py_ssize_t i;
4394 digit carry = 1;
4395 for (i = 0; i < m; ++i) {
4396 carry += a[i] ^ PyLong_MASK;
4397 z[i] = carry & PyLong_MASK;
4398 carry >>= PyLong_SHIFT;
4399 }
4400 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004401}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004402
4403/* Bitwise and/xor/or operations */
4404
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004405static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004406long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004407 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004408 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 int nega, negb, negz;
4411 Py_ssize_t size_a, size_b, size_z, i;
4412 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 /* Bitwise operations for negative numbers operate as though
4415 on a two's complement representation. So convert arguments
4416 from sign-magnitude to two's complement, and convert the
4417 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004420 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 nega = Py_SIZE(a) < 0;
4422 if (nega) {
4423 z = _PyLong_New(size_a);
4424 if (z == NULL)
4425 return NULL;
4426 v_complement(z->ob_digit, a->ob_digit, size_a);
4427 a = z;
4428 }
4429 else
4430 /* Keep reference count consistent. */
4431 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004434 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 negb = Py_SIZE(b) < 0;
4436 if (negb) {
4437 z = _PyLong_New(size_b);
4438 if (z == NULL) {
4439 Py_DECREF(a);
4440 return NULL;
4441 }
4442 v_complement(z->ob_digit, b->ob_digit, size_b);
4443 b = z;
4444 }
4445 else
4446 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 /* Swap a and b if necessary to ensure size_a >= size_b. */
4449 if (size_a < size_b) {
4450 z = a; a = b; b = z;
4451 size_z = size_a; size_a = size_b; size_b = size_z;
4452 negz = nega; nega = negb; negb = negz;
4453 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 /* JRH: The original logic here was to allocate the result value (z)
4456 as the longer of the two operands. However, there are some cases
4457 where the result is guaranteed to be shorter than that: AND of two
4458 positives, OR of two negatives: use the shorter number. AND with
4459 mixed signs: use the positive number. OR with mixed signs: use the
4460 negative number.
4461 */
4462 switch (op) {
4463 case '^':
4464 negz = nega ^ negb;
4465 size_z = size_a;
4466 break;
4467 case '&':
4468 negz = nega & negb;
4469 size_z = negb ? size_a : size_b;
4470 break;
4471 case '|':
4472 negz = nega | negb;
4473 size_z = negb ? size_b : size_a;
4474 break;
4475 default:
4476 PyErr_BadArgument();
4477 return NULL;
4478 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 /* We allow an extra digit if z is negative, to make sure that
4481 the final two's complement of z doesn't overflow. */
4482 z = _PyLong_New(size_z + negz);
4483 if (z == NULL) {
4484 Py_DECREF(a);
4485 Py_DECREF(b);
4486 return NULL;
4487 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 /* Compute digits for overlap of a and b. */
4490 switch(op) {
4491 case '&':
4492 for (i = 0; i < size_b; ++i)
4493 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4494 break;
4495 case '|':
4496 for (i = 0; i < size_b; ++i)
4497 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4498 break;
4499 case '^':
4500 for (i = 0; i < size_b; ++i)
4501 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4502 break;
4503 default:
4504 PyErr_BadArgument();
4505 return NULL;
4506 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 /* Copy any remaining digits of a, inverting if necessary. */
4509 if (op == '^' && negb)
4510 for (; i < size_z; ++i)
4511 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4512 else if (i < size_z)
4513 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4514 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 /* Complement result if negative. */
4517 if (negz) {
4518 Py_SIZE(z) = -(Py_SIZE(z));
4519 z->ob_digit[size_z] = PyLong_MASK;
4520 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4521 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 Py_DECREF(a);
4524 Py_DECREF(b);
4525 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004526}
4527
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004528static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004529long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 PyObject *c;
4532 CHECK_BINOP(a, b);
4533 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4534 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004535}
4536
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004537static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004538long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 PyObject *c;
4541 CHECK_BINOP(a, b);
4542 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4543 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004544}
4545
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004546static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004547long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 PyObject *c;
4550 CHECK_BINOP(a, b);
4551 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4552 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004553}
4554
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004555static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004556long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 if (PyLong_CheckExact(v))
4559 Py_INCREF(v);
4560 else
4561 v = _PyLong_Copy((PyLongObject *)v);
4562 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004563}
4564
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004565PyObject *
4566_PyLong_GCD(PyObject *aarg, PyObject *barg)
4567{
4568 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4569 stwodigits x, y, q, s, t, c_carry, d_carry;
4570 stwodigits A, B, C, D, T;
4571 int nbits, k;
4572 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4573 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4574
4575 a = (PyLongObject *)aarg;
4576 b = (PyLongObject *)barg;
4577 size_a = Py_SIZE(a);
4578 size_b = Py_SIZE(b);
4579 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4580 Py_INCREF(a);
4581 Py_INCREF(b);
4582 goto simple;
4583 }
4584
4585 /* Initial reduction: make sure that 0 <= b <= a. */
4586 a = (PyLongObject *)long_abs(a);
4587 if (a == NULL)
4588 return NULL;
4589 b = (PyLongObject *)long_abs(b);
4590 if (b == NULL) {
4591 Py_DECREF(a);
4592 return NULL;
4593 }
4594 if (long_compare(a, b) < 0) {
4595 r = a;
4596 a = b;
4597 b = r;
4598 }
4599 /* We now own references to a and b */
4600
4601 alloc_a = Py_SIZE(a);
4602 alloc_b = Py_SIZE(b);
4603 /* reduce until a fits into 2 digits */
4604 while ((size_a = Py_SIZE(a)) > 2) {
4605 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4606 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4607 corresponding bits of b into y */
4608 size_b = Py_SIZE(b);
4609 assert(size_b <= size_a);
4610 if (size_b == 0) {
4611 if (size_a < alloc_a) {
4612 r = (PyLongObject *)_PyLong_Copy(a);
4613 Py_DECREF(a);
4614 }
4615 else
4616 r = a;
4617 Py_DECREF(b);
4618 Py_XDECREF(c);
4619 Py_XDECREF(d);
4620 return (PyObject *)r;
4621 }
4622 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4623 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4624 (a->ob_digit[size_a-3] >> nbits));
4625
4626 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4627 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4628 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4629
4630 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4631 larger than PyLong_MASK during the algorithm. */
4632 A = 1; B = 0; C = 0; D = 1;
4633 for (k=0;; k++) {
4634 if (y-C == 0)
4635 break;
4636 q = (x+(A-1))/(y-C);
4637 s = B+q*D;
4638 t = x-q*y;
4639 if (s > t)
4640 break;
4641 x = y; y = t;
4642 t = A+q*C; A = D; B = C; C = s; D = t;
4643 }
4644
4645 if (k == 0) {
4646 /* no progress; do a Euclidean step */
4647 if (l_divmod(a, b, NULL, &r) < 0)
4648 goto error;
4649 Py_DECREF(a);
4650 a = b;
4651 b = r;
4652 alloc_a = alloc_b;
4653 alloc_b = Py_SIZE(b);
4654 continue;
4655 }
4656
4657 /*
4658 a, b = A*b-B*a, D*a-C*b if k is odd
4659 a, b = A*a-B*b, D*b-C*a if k is even
4660 */
4661 if (k&1) {
4662 T = -A; A = -B; B = T;
4663 T = -C; C = -D; D = T;
4664 }
4665 if (c != NULL)
4666 Py_SIZE(c) = size_a;
4667 else if (Py_REFCNT(a) == 1) {
4668 Py_INCREF(a);
4669 c = a;
4670 }
4671 else {
4672 alloc_a = size_a;
4673 c = _PyLong_New(size_a);
4674 if (c == NULL)
4675 goto error;
4676 }
4677
4678 if (d != NULL)
4679 Py_SIZE(d) = size_a;
4680 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4681 Py_INCREF(b);
4682 d = b;
4683 Py_SIZE(d) = size_a;
4684 }
4685 else {
4686 alloc_b = size_a;
4687 d = _PyLong_New(size_a);
4688 if (d == NULL)
4689 goto error;
4690 }
4691 a_end = a->ob_digit + size_a;
4692 b_end = b->ob_digit + size_b;
4693
4694 /* compute new a and new b in parallel */
4695 a_digit = a->ob_digit;
4696 b_digit = b->ob_digit;
4697 c_digit = c->ob_digit;
4698 d_digit = d->ob_digit;
4699 c_carry = 0;
4700 d_carry = 0;
4701 while (b_digit < b_end) {
4702 c_carry += (A * *a_digit) - (B * *b_digit);
4703 d_carry += (D * *b_digit++) - (C * *a_digit++);
4704 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4705 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4706 c_carry >>= PyLong_SHIFT;
4707 d_carry >>= PyLong_SHIFT;
4708 }
4709 while (a_digit < a_end) {
4710 c_carry += A * *a_digit;
4711 d_carry -= C * *a_digit++;
4712 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4713 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4714 c_carry >>= PyLong_SHIFT;
4715 d_carry >>= PyLong_SHIFT;
4716 }
4717 assert(c_carry == 0);
4718 assert(d_carry == 0);
4719
4720 Py_INCREF(c);
4721 Py_INCREF(d);
4722 Py_DECREF(a);
4723 Py_DECREF(b);
4724 a = long_normalize(c);
4725 b = long_normalize(d);
4726 }
4727 Py_XDECREF(c);
4728 Py_XDECREF(d);
4729
4730simple:
4731 assert(Py_REFCNT(a) > 0);
4732 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004733/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4734 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4735#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004736 /* a fits into a long, so b must too */
4737 x = PyLong_AsLong((PyObject *)a);
4738 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004739#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004740 x = PyLong_AsLongLong((PyObject *)a);
4741 y = PyLong_AsLongLong((PyObject *)b);
4742#else
4743# error "_PyLong_GCD"
4744#endif
4745 x = Py_ABS(x);
4746 y = Py_ABS(y);
4747 Py_DECREF(a);
4748 Py_DECREF(b);
4749
4750 /* usual Euclidean algorithm for longs */
4751 while (y != 0) {
4752 t = y;
4753 y = x % y;
4754 x = t;
4755 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004756#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004757 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004758#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004759 return PyLong_FromLongLong(x);
4760#else
4761# error "_PyLong_GCD"
4762#endif
4763
4764error:
4765 Py_DECREF(a);
4766 Py_DECREF(b);
4767 Py_XDECREF(c);
4768 Py_XDECREF(d);
4769 return NULL;
4770}
4771
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004772static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004773long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 double result;
4776 result = PyLong_AsDouble(v);
4777 if (result == -1.0 && PyErr_Occurred())
4778 return NULL;
4779 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004780}
4781
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004782static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004783long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004784
Tim Peters6d6c1a32001-08-02 04:15:00 +00004785static PyObject *
4786long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4787{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004788 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004789 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004792 if (type != &PyLong_Type)
4793 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004794 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4795 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004797 if (x == NULL) {
4798 if (obase != NULL) {
4799 PyErr_SetString(PyExc_TypeError,
4800 "int() missing string argument");
4801 return NULL;
4802 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004804 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004805 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004807
Gregory P. Smitha689e522012-12-25 22:38:32 -08004808 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004809 if (base == -1 && PyErr_Occurred())
4810 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004811 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004812 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004813 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004814 return NULL;
4815 }
4816
4817 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004818 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004819 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004820 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004821 if (PyByteArray_Check(x))
4822 string = PyByteArray_AS_STRING(x);
4823 else
4824 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004825 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 }
4827 else {
4828 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004829 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 return NULL;
4831 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004832}
4833
Serhiy Storchaka95949422013-08-27 19:40:23 +03004834/* Wimpy, slow approach to tp_new calls for subtypes of int:
4835 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004836 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004837 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004838*/
4839static PyObject *
4840long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 PyLongObject *tmp, *newobj;
4843 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 assert(PyType_IsSubtype(type, &PyLong_Type));
4846 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4847 if (tmp == NULL)
4848 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004849 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 n = Py_SIZE(tmp);
4851 if (n < 0)
4852 n = -n;
4853 newobj = (PyLongObject *)type->tp_alloc(type, n);
4854 if (newobj == NULL) {
4855 Py_DECREF(tmp);
4856 return NULL;
4857 }
4858 assert(PyLong_Check(newobj));
4859 Py_SIZE(newobj) = Py_SIZE(tmp);
4860 for (i = 0; i < n; i++)
4861 newobj->ob_digit[i] = tmp->ob_digit[i];
4862 Py_DECREF(tmp);
4863 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004864}
4865
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004866static PyObject *
4867long_getnewargs(PyLongObject *v)
4868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004870}
4871
Guido van Rossumb43daf72007-08-01 18:08:08 +00004872static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004873long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004874 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004875}
4876
4877static PyObject *
4878long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004879 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004880}
4881
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004882static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004883long__format__(PyObject *self, PyObject *args)
4884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004886 _PyUnicodeWriter writer;
4887 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4890 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004891
Victor Stinner8f674cc2013-04-17 23:02:17 +02004892 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004893 ret = _PyLong_FormatAdvancedWriter(
4894 &writer,
4895 self,
4896 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4897 if (ret == -1) {
4898 _PyUnicodeWriter_Dealloc(&writer);
4899 return NULL;
4900 }
4901 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004902}
4903
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004904/* Return a pair (q, r) such that a = b * q + r, and
4905 abs(r) <= abs(b)/2, with equality possible only if q is even.
4906 In other words, q == a / b, rounded to the nearest integer using
4907 round-half-to-even. */
4908
4909PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004910_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004911{
4912 PyLongObject *quo = NULL, *rem = NULL;
4913 PyObject *one = NULL, *twice_rem, *result, *temp;
4914 int cmp, quo_is_odd, quo_is_neg;
4915
4916 /* Equivalent Python code:
4917
4918 def divmod_near(a, b):
4919 q, r = divmod(a, b)
4920 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4921 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4922 # positive, 2 * r < b if b negative.
4923 greater_than_half = 2*r > b if b > 0 else 2*r < b
4924 exactly_half = 2*r == b
4925 if greater_than_half or exactly_half and q % 2 == 1:
4926 q += 1
4927 r -= b
4928 return q, r
4929
4930 */
4931 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4932 PyErr_SetString(PyExc_TypeError,
4933 "non-integer arguments in division");
4934 return NULL;
4935 }
4936
4937 /* Do a and b have different signs? If so, quotient is negative. */
4938 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4939
4940 one = PyLong_FromLong(1L);
4941 if (one == NULL)
4942 return NULL;
4943
4944 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4945 goto error;
4946
4947 /* compare twice the remainder with the divisor, to see
4948 if we need to adjust the quotient and remainder */
4949 twice_rem = long_lshift((PyObject *)rem, one);
4950 if (twice_rem == NULL)
4951 goto error;
4952 if (quo_is_neg) {
4953 temp = long_neg((PyLongObject*)twice_rem);
4954 Py_DECREF(twice_rem);
4955 twice_rem = temp;
4956 if (twice_rem == NULL)
4957 goto error;
4958 }
4959 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4960 Py_DECREF(twice_rem);
4961
4962 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4963 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4964 /* fix up quotient */
4965 if (quo_is_neg)
4966 temp = long_sub(quo, (PyLongObject *)one);
4967 else
4968 temp = long_add(quo, (PyLongObject *)one);
4969 Py_DECREF(quo);
4970 quo = (PyLongObject *)temp;
4971 if (quo == NULL)
4972 goto error;
4973 /* and remainder */
4974 if (quo_is_neg)
4975 temp = long_add(rem, (PyLongObject *)b);
4976 else
4977 temp = long_sub(rem, (PyLongObject *)b);
4978 Py_DECREF(rem);
4979 rem = (PyLongObject *)temp;
4980 if (rem == NULL)
4981 goto error;
4982 }
4983
4984 result = PyTuple_New(2);
4985 if (result == NULL)
4986 goto error;
4987
4988 /* PyTuple_SET_ITEM steals references */
4989 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4990 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4991 Py_DECREF(one);
4992 return result;
4993
4994 error:
4995 Py_XDECREF(quo);
4996 Py_XDECREF(rem);
4997 Py_XDECREF(one);
4998 return NULL;
4999}
5000
Eric Smith8c663262007-08-25 02:26:07 +00005001static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005002long_round(PyObject *self, PyObject *args)
5003{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005004 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005005
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005006 /* To round an integer m to the nearest 10**n (n positive), we make use of
5007 * the divmod_near operation, defined by:
5008 *
5009 * divmod_near(a, b) = (q, r)
5010 *
5011 * where q is the nearest integer to the quotient a / b (the
5012 * nearest even integer in the case of a tie) and r == a - q * b.
5013 * Hence q * b = a - r is the nearest multiple of b to a,
5014 * preferring even multiples in the case of a tie.
5015 *
5016 * So the nearest multiple of 10**n to m is:
5017 *
5018 * m - divmod_near(m, 10**n)[1].
5019 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5021 return NULL;
5022 if (o_ndigits == NULL)
5023 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005024
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005025 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 if (ndigits == NULL)
5027 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005028
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005029 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 if (Py_SIZE(ndigits) >= 0) {
5031 Py_DECREF(ndigits);
5032 return long_long(self);
5033 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005034
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005035 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5036 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005038 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005040 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005041
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005042 result = PyLong_FromLong(10L);
5043 if (result == NULL) {
5044 Py_DECREF(ndigits);
5045 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005047
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005048 temp = long_pow(result, ndigits, Py_None);
5049 Py_DECREF(ndigits);
5050 Py_DECREF(result);
5051 result = temp;
5052 if (result == NULL)
5053 return NULL;
5054
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005055 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005056 Py_DECREF(result);
5057 result = temp;
5058 if (result == NULL)
5059 return NULL;
5060
5061 temp = long_sub((PyLongObject *)self,
5062 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5063 Py_DECREF(result);
5064 result = temp;
5065
5066 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005067}
5068
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005069static PyObject *
5070long_sizeof(PyLongObject *v)
5071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005072 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005073
Victor Stinner45e8e2f2014-05-14 17:24:35 +02005074 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(v))*sizeof(digit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005076}
5077
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005078static PyObject *
5079long_bit_length(PyLongObject *v)
5080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005081 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005082 Py_ssize_t ndigits;
5083 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005086 assert(v != NULL);
5087 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005088
Victor Stinner45e8e2f2014-05-14 17:24:35 +02005089 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005090 if (ndigits == 0)
5091 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 msd = v->ob_digit[ndigits-1];
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005094 msd_bits = bits_in_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5097 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 /* expression above may overflow; use Python integers instead */
5100 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5101 if (result == NULL)
5102 return NULL;
5103 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5104 if (x == NULL)
5105 goto error;
5106 y = (PyLongObject *)long_mul(result, x);
5107 Py_DECREF(x);
5108 if (y == NULL)
5109 goto error;
5110 Py_DECREF(result);
5111 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5114 if (x == NULL)
5115 goto error;
5116 y = (PyLongObject *)long_add(result, x);
5117 Py_DECREF(x);
5118 if (y == NULL)
5119 goto error;
5120 Py_DECREF(result);
5121 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005124
Mark Dickinson22b20182010-05-10 21:27:53 +00005125 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 Py_DECREF(result);
5127 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005128}
5129
5130PyDoc_STRVAR(long_bit_length_doc,
5131"int.bit_length() -> int\n\
5132\n\
5133Number of bits necessary to represent self in binary.\n\
5134>>> bin(37)\n\
5135'0b100101'\n\
5136>>> (37).bit_length()\n\
51376");
5138
Christian Heimes53876d92008-04-19 00:31:39 +00005139#if 0
5140static PyObject *
5141long_is_finite(PyObject *v)
5142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005143 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005144}
5145#endif
5146
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005147
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005148static PyObject *
5149long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
5150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005151 PyObject *byteorder_str;
5152 PyObject *is_signed_obj = NULL;
5153 Py_ssize_t length;
5154 int little_endian;
5155 int is_signed;
5156 PyObject *bytes;
5157 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005159 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
5160 &length, &byteorder_str,
5161 &is_signed_obj))
5162 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 if (args != NULL && Py_SIZE(args) > 2) {
5165 PyErr_SetString(PyExc_TypeError,
5166 "'signed' is a keyword-only argument");
5167 return NULL;
5168 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005169
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02005170 if (_PyUnicode_EqualToASCIIString(byteorder_str, "little"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 little_endian = 1;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02005172 else if (_PyUnicode_EqualToASCIIString(byteorder_str, "big"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 little_endian = 0;
5174 else {
5175 PyErr_SetString(PyExc_ValueError,
5176 "byteorder must be either 'little' or 'big'");
5177 return NULL;
5178 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 if (is_signed_obj != NULL) {
5181 int cmp = PyObject_IsTrue(is_signed_obj);
5182 if (cmp < 0)
5183 return NULL;
5184 is_signed = cmp ? 1 : 0;
5185 }
5186 else {
5187 /* If the signed argument was omitted, use False as the
5188 default. */
5189 is_signed = 0;
5190 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 if (length < 0) {
5193 PyErr_SetString(PyExc_ValueError,
5194 "length argument must be non-negative");
5195 return NULL;
5196 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 bytes = PyBytes_FromStringAndSize(NULL, length);
5199 if (bytes == NULL)
5200 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
5203 length, little_endian, is_signed) < 0) {
5204 Py_DECREF(bytes);
5205 return NULL;
5206 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005209}
5210
Mark Dickinson078c2532010-01-30 18:06:17 +00005211PyDoc_STRVAR(long_to_bytes_doc,
5212"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005213\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005214Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005215\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005217raised if the integer is not representable with the given number of\n\
5218bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005219\n\
5220The byteorder argument determines the byte order used to represent the\n\
5221integer. If byteorder is 'big', the most significant byte is at the\n\
5222beginning of the byte array. If byteorder is 'little', the most\n\
5223significant byte is at the end of the byte array. To request the native\n\
5224byte order of the host system, use `sys.byteorder' as the byte order value.\n\
5225\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005226The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005227used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005228is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005229
5230static PyObject *
5231long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
5232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 PyObject *byteorder_str;
5234 PyObject *is_signed_obj = NULL;
5235 int little_endian;
5236 int is_signed;
5237 PyObject *obj;
5238 PyObject *bytes;
5239 PyObject *long_obj;
5240 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005242 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
5243 &obj, &byteorder_str,
5244 &is_signed_obj))
5245 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 if (args != NULL && Py_SIZE(args) > 2) {
5248 PyErr_SetString(PyExc_TypeError,
5249 "'signed' is a keyword-only argument");
5250 return NULL;
5251 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005252
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02005253 if (_PyUnicode_EqualToASCIIString(byteorder_str, "little"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005254 little_endian = 1;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02005255 else if (_PyUnicode_EqualToASCIIString(byteorder_str, "big"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 little_endian = 0;
5257 else {
5258 PyErr_SetString(PyExc_ValueError,
5259 "byteorder must be either 'little' or 'big'");
5260 return NULL;
5261 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 if (is_signed_obj != NULL) {
5264 int cmp = PyObject_IsTrue(is_signed_obj);
5265 if (cmp < 0)
5266 return NULL;
5267 is_signed = cmp ? 1 : 0;
5268 }
5269 else {
5270 /* If the signed argument was omitted, use False as the
5271 default. */
5272 is_signed = 0;
5273 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 bytes = PyObject_Bytes(obj);
5276 if (bytes == NULL)
5277 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 long_obj = _PyLong_FromByteArray(
5280 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5281 little_endian, is_signed);
5282 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005283
Serhiy Storchakaea36c942016-05-12 10:37:58 +03005284 if (type != &PyLong_Type) {
Victor Stinner27580c12016-12-01 14:43:22 +01005285 Py_SETREF(long_obj, _PyObject_CallArg1((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005289}
5290
Mark Dickinson078c2532010-01-30 18:06:17 +00005291PyDoc_STRVAR(long_from_bytes_doc,
5292"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
5293\n\
5294Return the integer represented by the given array of bytes.\n\
5295\n\
R David Murray861470c2014-10-05 11:47:01 -04005296The bytes argument must be a bytes-like object (e.g. bytes or bytearray).\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00005297\n\
5298The byteorder argument determines the byte order used to represent the\n\
5299integer. If byteorder is 'big', the most significant byte is at the\n\
5300beginning of the byte array. If byteorder is 'little', the most\n\
5301significant byte is at the end of the byte array. To request the native\n\
5302byte order of the host system, use `sys.byteorder' as the byte order value.\n\
5303\n\
5304The signed keyword-only argument indicates whether two's complement is\n\
5305used to represent the integer.");
5306
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005307static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
5309 "Returns self, the complex conjugate of any int."},
5310 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
5311 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00005312#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5314 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005315#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 {"to_bytes", (PyCFunction)long_to_bytes,
5317 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
5318 {"from_bytes", (PyCFunction)long_from_bytes,
5319 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
5320 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
5321 "Truncating an Integral returns itself."},
5322 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
5323 "Flooring an Integral returns itself."},
5324 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
5325 "Ceiling of an Integral returns itself."},
5326 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5327 "Rounding an Integral returns itself.\n"
5328 "Rounding with an ndigits argument also returns an integer."},
5329 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
5330 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
5331 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
5332 "Returns size in memory, in bytes"},
5333 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005334};
5335
Guido van Rossumb43daf72007-08-01 18:08:08 +00005336static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005337 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005338 (getter)long_long, (setter)NULL,
5339 "the real part of a complex number",
5340 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005341 {"imag",
5342 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005343 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005344 NULL},
5345 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005346 (getter)long_long, (setter)NULL,
5347 "the numerator of a rational number in lowest terms",
5348 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005349 {"denominator",
5350 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005351 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005352 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005353 {NULL} /* Sentinel */
5354};
5355
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005356PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005357"int(x=0) -> integer\n\
5358int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005359\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005360Convert a number or string to an integer, or return 0 if no arguments\n\
5361are given. If x is a number, return x.__int__(). For floating point\n\
5362numbers, this truncates towards zero.\n\
5363\n\
5364If x is not a number or if base is given, then x must be a string,\n\
5365bytes, or bytearray instance representing an integer literal in the\n\
5366given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5367by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5368Base 0 means to interpret the base from the string as an integer literal.\n\
5369>>> int('0b100', base=0)\n\
53704");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005371
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005372static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005373 (binaryfunc)long_add, /*nb_add*/
5374 (binaryfunc)long_sub, /*nb_subtract*/
5375 (binaryfunc)long_mul, /*nb_multiply*/
5376 long_mod, /*nb_remainder*/
5377 long_divmod, /*nb_divmod*/
5378 long_pow, /*nb_power*/
5379 (unaryfunc)long_neg, /*nb_negative*/
5380 (unaryfunc)long_long, /*tp_positive*/
5381 (unaryfunc)long_abs, /*tp_absolute*/
5382 (inquiry)long_bool, /*tp_bool*/
5383 (unaryfunc)long_invert, /*nb_invert*/
5384 long_lshift, /*nb_lshift*/
5385 (binaryfunc)long_rshift, /*nb_rshift*/
5386 long_and, /*nb_and*/
5387 long_xor, /*nb_xor*/
5388 long_or, /*nb_or*/
5389 long_long, /*nb_int*/
5390 0, /*nb_reserved*/
5391 long_float, /*nb_float*/
5392 0, /* nb_inplace_add */
5393 0, /* nb_inplace_subtract */
5394 0, /* nb_inplace_multiply */
5395 0, /* nb_inplace_remainder */
5396 0, /* nb_inplace_power */
5397 0, /* nb_inplace_lshift */
5398 0, /* nb_inplace_rshift */
5399 0, /* nb_inplace_and */
5400 0, /* nb_inplace_xor */
5401 0, /* nb_inplace_or */
5402 long_div, /* nb_floor_divide */
5403 long_true_divide, /* nb_true_divide */
5404 0, /* nb_inplace_floor_divide */
5405 0, /* nb_inplace_true_divide */
5406 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005407};
5408
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005409PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5411 "int", /* tp_name */
5412 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5413 sizeof(digit), /* tp_itemsize */
5414 long_dealloc, /* tp_dealloc */
5415 0, /* tp_print */
5416 0, /* tp_getattr */
5417 0, /* tp_setattr */
5418 0, /* tp_reserved */
5419 long_to_decimal_string, /* tp_repr */
5420 &long_as_number, /* tp_as_number */
5421 0, /* tp_as_sequence */
5422 0, /* tp_as_mapping */
5423 (hashfunc)long_hash, /* tp_hash */
5424 0, /* tp_call */
5425 long_to_decimal_string, /* tp_str */
5426 PyObject_GenericGetAttr, /* tp_getattro */
5427 0, /* tp_setattro */
5428 0, /* tp_as_buffer */
5429 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5430 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5431 long_doc, /* tp_doc */
5432 0, /* tp_traverse */
5433 0, /* tp_clear */
5434 long_richcompare, /* tp_richcompare */
5435 0, /* tp_weaklistoffset */
5436 0, /* tp_iter */
5437 0, /* tp_iternext */
5438 long_methods, /* tp_methods */
5439 0, /* tp_members */
5440 long_getset, /* tp_getset */
5441 0, /* tp_base */
5442 0, /* tp_dict */
5443 0, /* tp_descr_get */
5444 0, /* tp_descr_set */
5445 0, /* tp_dictoffset */
5446 0, /* tp_init */
5447 0, /* tp_alloc */
5448 long_new, /* tp_new */
5449 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005450};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005451
Mark Dickinsonbd792642009-03-18 20:06:12 +00005452static PyTypeObject Int_InfoType;
5453
5454PyDoc_STRVAR(int_info__doc__,
5455"sys.int_info\n\
5456\n\
5457A struct sequence that holds information about Python's\n\
5458internal representation of integers. The attributes are read only.");
5459
5460static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005462 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005463 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005464};
5465
5466static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 "sys.int_info", /* name */
5468 int_info__doc__, /* doc */
5469 int_info_fields, /* fields */
5470 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005471};
5472
5473PyObject *
5474PyLong_GetInfo(void)
5475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 PyObject* int_info;
5477 int field = 0;
5478 int_info = PyStructSequence_New(&Int_InfoType);
5479 if (int_info == NULL)
5480 return NULL;
5481 PyStructSequence_SET_ITEM(int_info, field++,
5482 PyLong_FromLong(PyLong_SHIFT));
5483 PyStructSequence_SET_ITEM(int_info, field++,
5484 PyLong_FromLong(sizeof(digit)));
5485 if (PyErr_Occurred()) {
5486 Py_CLEAR(int_info);
5487 return NULL;
5488 }
5489 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005490}
5491
Guido van Rossumddefaf32007-01-14 03:31:43 +00005492int
5493_PyLong_Init(void)
5494{
5495#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005496 int ival, size;
5497 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5500 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5501 if (Py_TYPE(v) == &PyLong_Type) {
5502 /* The element is already initialized, most likely
5503 * the Python interpreter was initialized before.
5504 */
5505 Py_ssize_t refcnt;
5506 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5509 _Py_NewReference(op);
5510 /* _Py_NewReference sets the ref count to 1 but
5511 * the ref count might be larger. Set the refcnt
5512 * to the original refcnt + 1 */
5513 Py_REFCNT(op) = refcnt + 1;
5514 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005515 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 }
5517 else {
Christian Heimesd3afe782013-12-04 09:27:47 +01005518 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 }
5520 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005521 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005522 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005523#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005524 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005525 if (Int_InfoType.tp_name == NULL) {
5526 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5527 return 0;
5528 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005531}
5532
5533void
5534PyLong_Fini(void)
5535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 /* Integers are currently statically allocated. Py_DECREF is not
5537 needed, but Python must forget about the reference or multiple
5538 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005539#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005540 int i;
5541 PyLongObject *v = small_ints;
5542 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5543 _Py_DEC_REFTOTAL;
5544 _Py_ForgetReference((PyObject*)v);
5545 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005546#endif
5547}