blob: f42683e9d024ce7e0c2e11e7a90cf0ab635f9e0b [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
Serhiy Storchaka495e8802017-02-01 23:12:20 +020012#include "clinic/longobject.c.h"
13/*[clinic input]
14class int "PyObject *" "&PyLong_Type"
15[clinic start generated code]*/
16/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
17
Guido van Rossumddefaf32007-01-14 03:31:43 +000018#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000020#endif
21#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000023#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020025_Py_IDENTIFIER(little);
26_Py_IDENTIFIER(big);
27
Mark Dickinsone4416742009-02-15 15:14:57 +000028/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020029#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
30 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 (Py_SIZE(x) == 0 ? (sdigit)0 : \
32 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000033
Serhiy Storchakaba85d692017-03-30 09:09:41 +030034PyObject *_PyLong_Zero = NULL;
35PyObject *_PyLong_One = NULL;
36
Guido van Rossumddefaf32007-01-14 03:31:43 +000037#if NSMALLNEGINTS + NSMALLPOSINTS > 0
38/* Small integers are preallocated in this array so that they
39 can be shared.
40 The integers that are preallocated are those in the range
41 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
42*/
43static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
44#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +000045Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
47
Guido van Rossum7eaf8222007-06-18 17:58:50 +000048static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000049get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000050{
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050051 PyObject *v;
Benjamin Peterson041c38a2014-03-14 21:47:23 -050052 assert(-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS);
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050053 v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000055#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 if (ival >= 0)
Pablo Galindo49c75a82018-10-28 15:02:17 +000057 _Py_quick_int_allocs++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 else
Pablo Galindo49c75a82018-10-28 15:02:17 +000059 _Py_quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000060#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000062}
63#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
65 return get_small_int((sdigit)ival); \
66 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069maybe_small_long(PyLongObject *v)
70{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020071 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 sdigit ival = MEDIUM_VALUE(v);
73 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
74 Py_DECREF(v);
75 return (PyLongObject *)get_small_int(ival);
76 }
77 }
78 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000079}
Guido van Rossumddefaf32007-01-14 03:31:43 +000080#else
81#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000082#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000083#endif
84
Serhiy Storchaka95949422013-08-27 19:40:23 +030085/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000086 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020087Py_LOCAL_INLINE(void)
88_PyLong_Negate(PyLongObject **x_p)
89{
90 PyLongObject *x;
91
92 x = (PyLongObject *)*x_p;
93 if (Py_REFCNT(x) == 1) {
94 Py_SIZE(x) = -Py_SIZE(x);
95 return;
96 }
97
98 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
99 Py_DECREF(x);
100}
101
Serhiy Storchaka95949422013-08-27 19:40:23 +0300102/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +0000103 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +0300104 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +0000105 */
Tim Peters0973b992004-08-29 22:16:50 +0000106#define KARATSUBA_CUTOFF 70
107#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +0000108
Tim Peters47e52ee2004-08-30 02:44:38 +0000109/* For exponentiation, use the binary left-to-right algorithm
110 * unless the exponent contains more than FIVEARY_CUTOFF digits.
111 * In that case, do 5 bits at a time. The potential drawback is that
112 * a table of 2**5 intermediate results is computed.
113 */
114#define FIVEARY_CUTOFF 8
115
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000116#define SIGCHECK(PyTryBlock) \
117 do { \
118 if (PyErr_CheckSignals()) PyTryBlock \
119 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000120
Serhiy Storchaka95949422013-08-27 19:40:23 +0300121/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000122 Doesn't attempt to free the storage--in most cases, due to the nature
123 of the algorithms used, this could save at most be one word anyway. */
124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200126long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200128 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 while (i > 0 && v->ob_digit[i-1] == 0)
132 --i;
133 if (i != j)
134 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
135 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000136}
137
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200138/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
139 using the nb_int slot, if available. Raise TypeError if either the
140 nb_int slot is not available or the result of the call to nb_int
141 returns something not of type int.
142*/
143PyLongObject *
144_PyLong_FromNbInt(PyObject *integral)
145{
146 PyNumberMethods *nb;
147 PyObject *result;
148
149 /* Fast path for the case that we already have an int. */
150 if (PyLong_CheckExact(integral)) {
151 Py_INCREF(integral);
152 return (PyLongObject *)integral;
153 }
154
155 nb = Py_TYPE(integral)->tp_as_number;
156 if (nb == NULL || nb->nb_int == NULL) {
157 PyErr_Format(PyExc_TypeError,
158 "an integer is required (got type %.200s)",
159 Py_TYPE(integral)->tp_name);
160 return NULL;
161 }
162
163 /* Convert using the nb_int slot, which should return something
164 of exact type int. */
165 result = nb->nb_int(integral);
166 if (!result || PyLong_CheckExact(result))
167 return (PyLongObject *)result;
168 if (!PyLong_Check(result)) {
169 PyErr_Format(PyExc_TypeError,
170 "__int__ returned non-int (type %.200s)",
171 result->ob_type->tp_name);
172 Py_DECREF(result);
173 return NULL;
174 }
175 /* Issue #17576: warn if 'result' not of exact type int. */
176 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
177 "__int__ returned non-int (type %.200s). "
178 "The ability to return an instance of a strict subclass of int "
179 "is deprecated, and may be removed in a future version of Python.",
180 result->ob_type->tp_name)) {
181 Py_DECREF(result);
182 return NULL;
183 }
184 return (PyLongObject *)result;
185}
186
187
Serhiy Storchaka95949422013-08-27 19:40:23 +0300188/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000189 Return NULL and set exception if we run out of memory. */
190
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000191#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000193
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000194PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000195_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 PyLongObject *result;
198 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
199 sizeof(digit)*size. Previous incarnations of this code used
200 sizeof(PyVarObject) instead of the offsetof, but this risks being
201 incorrect in the presence of padding between the PyVarObject header
202 and the digits. */
203 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
204 PyErr_SetString(PyExc_OverflowError,
205 "too many digits in integer");
206 return NULL;
207 }
208 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
209 size*sizeof(digit));
210 if (!result) {
211 PyErr_NoMemory();
212 return NULL;
213 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100214 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000215}
216
Tim Peters64b5ce32001-09-10 20:52:51 +0000217PyObject *
218_PyLong_Copy(PyLongObject *src)
219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 PyLongObject *result;
221 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 assert(src != NULL);
224 i = Py_SIZE(src);
225 if (i < 0)
226 i = -(i);
227 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100228 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 CHECK_SMALL_INT(ival);
230 }
231 result = _PyLong_New(i);
232 if (result != NULL) {
233 Py_SIZE(result) = Py_SIZE(src);
234 while (--i >= 0)
235 result->ob_digit[i] = src->ob_digit[i];
236 }
237 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000238}
239
Serhiy Storchaka95949422013-08-27 19:40:23 +0300240/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000241
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000243PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyLongObject *v;
246 unsigned long abs_ival;
247 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
248 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100249 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (ival < 0) {
254 /* negate: can't write this as abs_ival = -ival since that
255 invokes undefined behaviour when ival is LONG_MIN */
256 abs_ival = 0U-(unsigned long)ival;
257 sign = -1;
258 }
259 else {
260 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100261 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 /* Fast path for single-digit ints */
265 if (!(abs_ival >> PyLong_SHIFT)) {
266 v = _PyLong_New(1);
267 if (v) {
268 Py_SIZE(v) = sign;
269 v->ob_digit[0] = Py_SAFE_DOWNCAST(
270 abs_ival, unsigned long, digit);
271 }
272 return (PyObject*)v;
273 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000274
Mark Dickinson249b8982009-04-27 19:41:00 +0000275#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* 2 digits */
277 if (!(abs_ival >> 2*PyLong_SHIFT)) {
278 v = _PyLong_New(2);
279 if (v) {
280 Py_SIZE(v) = 2*sign;
281 v->ob_digit[0] = Py_SAFE_DOWNCAST(
282 abs_ival & PyLong_MASK, unsigned long, digit);
283 v->ob_digit[1] = Py_SAFE_DOWNCAST(
284 abs_ival >> PyLong_SHIFT, unsigned long, digit);
285 }
286 return (PyObject*)v;
287 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000288#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 /* Larger numbers: loop to determine number of digits */
291 t = abs_ival;
292 while (t) {
293 ++ndigits;
294 t >>= PyLong_SHIFT;
295 }
296 v = _PyLong_New(ndigits);
297 if (v != NULL) {
298 digit *p = v->ob_digit;
299 Py_SIZE(v) = ndigits*sign;
300 t = abs_ival;
301 while (t) {
302 *p++ = Py_SAFE_DOWNCAST(
303 t & PyLong_MASK, unsigned long, digit);
304 t >>= PyLong_SHIFT;
305 }
306 }
307 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000308}
309
Serhiy Storchaka95949422013-08-27 19:40:23 +0300310/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000311
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000313PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyLongObject *v;
316 unsigned long t;
317 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 if (ival < PyLong_BASE)
320 return PyLong_FromLong(ival);
321 /* Count the number of Python digits. */
orenmn86aa2692017-03-06 10:42:47 +0200322 t = ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 while (t) {
324 ++ndigits;
325 t >>= PyLong_SHIFT;
326 }
327 v = _PyLong_New(ndigits);
328 if (v != NULL) {
329 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 while (ival) {
331 *p++ = (digit)(ival & PyLong_MASK);
332 ival >>= PyLong_SHIFT;
333 }
334 }
335 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000336}
337
Serhiy Storchaka95949422013-08-27 19:40:23 +0300338/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000339
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 PyLongObject *v;
344 double frac;
345 int i, ndig, expo, neg;
346 neg = 0;
347 if (Py_IS_INFINITY(dval)) {
348 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000349 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 return NULL;
351 }
352 if (Py_IS_NAN(dval)) {
353 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000354 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 return NULL;
356 }
357 if (dval < 0.0) {
358 neg = 1;
359 dval = -dval;
360 }
361 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
362 if (expo <= 0)
363 return PyLong_FromLong(0L);
364 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
365 v = _PyLong_New(ndig);
366 if (v == NULL)
367 return NULL;
368 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
369 for (i = ndig; --i >= 0; ) {
370 digit bits = (digit)frac;
371 v->ob_digit[i] = bits;
372 frac = frac - (double)bits;
373 frac = ldexp(frac, PyLong_SHIFT);
374 }
375 if (neg)
376 Py_SIZE(v) = -(Py_SIZE(v));
377 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000378}
379
Thomas Wouters89f507f2006-12-13 04:49:30 +0000380/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
381 * anything about what happens when a signed integer operation overflows,
382 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700383 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000384 * (unsigned long)LONG_MAX, and for the smallest negative signed long
385 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
386 * However, some other compilers warn about applying unary minus to an
387 * unsigned operand. Hence the weird "0-".
388 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
390#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000391
Serhiy Storchaka95949422013-08-27 19:40:23 +0300392/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100393 method.
394
395 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
396 the result. Otherwise *overflow is 0.
397
398 For other errors (e.g., TypeError), return -1 and set an error condition.
399 In this case *overflow will be 0.
400*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000401
402long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000403PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200406 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 unsigned long x, prev;
408 long res;
409 Py_ssize_t i;
410 int sign;
411 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 *overflow = 0;
414 if (vv == NULL) {
415 PyErr_BadInternalCall();
416 return -1;
417 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000418
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200419 if (PyLong_Check(vv)) {
420 v = (PyLongObject *)vv;
421 }
422 else {
423 v = _PyLong_FromNbInt(vv);
424 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 return -1;
426 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 switch (i) {
433 case -1:
434 res = -(sdigit)v->ob_digit[0];
435 break;
436 case 0:
437 res = 0;
438 break;
439 case 1:
440 res = v->ob_digit[0];
441 break;
442 default:
443 sign = 1;
444 x = 0;
445 if (i < 0) {
446 sign = -1;
447 i = -(i);
448 }
449 while (--i >= 0) {
450 prev = x;
451 x = (x << PyLong_SHIFT) | v->ob_digit[i];
452 if ((x >> PyLong_SHIFT) != prev) {
453 *overflow = sign;
454 goto exit;
455 }
456 }
457 /* Haven't lost any bits, but casting to long requires extra
458 * care (see comment above).
459 */
460 if (x <= (unsigned long)LONG_MAX) {
461 res = (long)x * sign;
462 }
463 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
464 res = LONG_MIN;
465 }
466 else {
467 *overflow = sign;
468 /* res is already set to -1 */
469 }
470 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000471 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200473 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 }
475 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000476}
477
Serhiy Storchaka95949422013-08-27 19:40:23 +0300478/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100479 method. Return -1 and set an error if overflow occurs. */
480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000482PyLong_AsLong(PyObject *obj)
483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 int overflow;
485 long result = PyLong_AsLongAndOverflow(obj, &overflow);
486 if (overflow) {
487 /* XXX: could be cute and give a different
488 message for overflow == -1 */
489 PyErr_SetString(PyExc_OverflowError,
490 "Python int too large to convert to C long");
491 }
492 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000493}
494
Serhiy Storchaka95949422013-08-27 19:40:23 +0300495/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200496 method. Return -1 and set an error if overflow occurs. */
497
498int
499_PyLong_AsInt(PyObject *obj)
500{
501 int overflow;
502 long result = PyLong_AsLongAndOverflow(obj, &overflow);
503 if (overflow || result > INT_MAX || result < INT_MIN) {
504 /* XXX: could be cute and give a different
505 message for overflow == -1 */
506 PyErr_SetString(PyExc_OverflowError,
507 "Python int too large to convert to C int");
508 return -1;
509 }
510 return (int)result;
511}
512
Serhiy Storchaka95949422013-08-27 19:40:23 +0300513/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000514 Returns -1 and sets an error condition if overflow occurs. */
515
516Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000517PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200518 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 size_t x, prev;
520 Py_ssize_t i;
521 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (vv == NULL) {
524 PyErr_BadInternalCall();
525 return -1;
526 }
527 if (!PyLong_Check(vv)) {
528 PyErr_SetString(PyExc_TypeError, "an integer is required");
529 return -1;
530 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 v = (PyLongObject *)vv;
533 i = Py_SIZE(v);
534 switch (i) {
535 case -1: return -(sdigit)v->ob_digit[0];
536 case 0: return 0;
537 case 1: return v->ob_digit[0];
538 }
539 sign = 1;
540 x = 0;
541 if (i < 0) {
542 sign = -1;
543 i = -(i);
544 }
545 while (--i >= 0) {
546 prev = x;
547 x = (x << PyLong_SHIFT) | v->ob_digit[i];
548 if ((x >> PyLong_SHIFT) != prev)
549 goto overflow;
550 }
551 /* Haven't lost any bits, but casting to a signed type requires
552 * extra care (see comment above).
553 */
554 if (x <= (size_t)PY_SSIZE_T_MAX) {
555 return (Py_ssize_t)x * sign;
556 }
557 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
558 return PY_SSIZE_T_MIN;
559 }
560 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000561
Mark Dickinson22b20182010-05-10 21:27:53 +0000562 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 PyErr_SetString(PyExc_OverflowError,
564 "Python int too large to convert to C ssize_t");
565 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000566}
567
Serhiy Storchaka95949422013-08-27 19:40:23 +0300568/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000569 Returns -1 and sets an error condition if overflow occurs. */
570
571unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000572PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000573{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200574 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 unsigned long x, prev;
576 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (vv == NULL) {
579 PyErr_BadInternalCall();
580 return (unsigned long)-1;
581 }
582 if (!PyLong_Check(vv)) {
583 PyErr_SetString(PyExc_TypeError, "an integer is required");
584 return (unsigned long)-1;
585 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 v = (PyLongObject *)vv;
588 i = Py_SIZE(v);
589 x = 0;
590 if (i < 0) {
591 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000592 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 return (unsigned long) -1;
594 }
595 switch (i) {
596 case 0: return 0;
597 case 1: return v->ob_digit[0];
598 }
599 while (--i >= 0) {
600 prev = x;
601 x = (x << PyLong_SHIFT) | v->ob_digit[i];
602 if ((x >> PyLong_SHIFT) != prev) {
603 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100604 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000605 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 return (unsigned long) -1;
607 }
608 }
609 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000610}
611
Serhiy Storchaka95949422013-08-27 19:40:23 +0300612/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200613 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000614
615size_t
616PyLong_AsSize_t(PyObject *vv)
617{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200618 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 size_t x, prev;
620 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (vv == NULL) {
623 PyErr_BadInternalCall();
624 return (size_t) -1;
625 }
626 if (!PyLong_Check(vv)) {
627 PyErr_SetString(PyExc_TypeError, "an integer is required");
628 return (size_t)-1;
629 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 v = (PyLongObject *)vv;
632 i = Py_SIZE(v);
633 x = 0;
634 if (i < 0) {
635 PyErr_SetString(PyExc_OverflowError,
636 "can't convert negative value to size_t");
637 return (size_t) -1;
638 }
639 switch (i) {
640 case 0: return 0;
641 case 1: return v->ob_digit[0];
642 }
643 while (--i >= 0) {
644 prev = x;
645 x = (x << PyLong_SHIFT) | v->ob_digit[i];
646 if ((x >> PyLong_SHIFT) != prev) {
647 PyErr_SetString(PyExc_OverflowError,
648 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200649 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 }
651 }
652 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000653}
654
Serhiy Storchaka95949422013-08-27 19:40:23 +0300655/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000656 Returns -1 and sets an error condition if an error occurs. */
657
Guido van Rossumddefaf32007-01-14 03:31:43 +0000658static unsigned long
659_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000660{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200661 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 unsigned long x;
663 Py_ssize_t i;
664 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 if (vv == NULL || !PyLong_Check(vv)) {
667 PyErr_BadInternalCall();
668 return (unsigned long) -1;
669 }
670 v = (PyLongObject *)vv;
671 i = Py_SIZE(v);
672 switch (i) {
673 case 0: return 0;
674 case 1: return v->ob_digit[0];
675 }
676 sign = 1;
677 x = 0;
678 if (i < 0) {
679 sign = -1;
680 i = -i;
681 }
682 while (--i >= 0) {
683 x = (x << PyLong_SHIFT) | v->ob_digit[i];
684 }
685 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000686}
687
Guido van Rossumddefaf32007-01-14 03:31:43 +0000688unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200689PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 PyLongObject *lo;
692 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000693
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200694 if (op == NULL) {
695 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 return (unsigned long)-1;
697 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000698
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200699 if (PyLong_Check(op)) {
700 return _PyLong_AsUnsignedLongMask(op);
701 }
702
703 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (lo == NULL)
705 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200706
707 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
708 Py_DECREF(lo);
709 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000710}
711
Tim Peters5b8132f2003-01-31 15:52:05 +0000712int
713_PyLong_Sign(PyObject *vv)
714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 assert(v != NULL);
718 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000721}
722
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200723/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
724 2**k if d is nonzero, else 0. */
725
726static const unsigned char BitLengthTable[32] = {
727 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
728 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
729};
730
731static int
732bits_in_digit(digit d)
733{
734 int d_bits = 0;
735 while (d >= 32) {
736 d_bits += 6;
737 d >>= 6;
738 }
739 d_bits += (int)BitLengthTable[d];
740 return d_bits;
741}
742
Tim Petersbaefd9e2003-01-28 20:37:45 +0000743size_t
744_PyLong_NumBits(PyObject *vv)
745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyLongObject *v = (PyLongObject *)vv;
747 size_t result = 0;
748 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200749 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 assert(v != NULL);
752 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200753 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
755 if (ndigits > 0) {
756 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700757 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100759 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200760 msd_bits = bits_in_digit(msd);
761 if (SIZE_MAX - msd_bits < result)
762 goto Overflow;
763 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 }
765 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000766
Mark Dickinson22b20182010-05-10 21:27:53 +0000767 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
769 "to express in a platform size_t");
770 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000771}
772
Tim Peters2a9b3672001-06-11 21:23:58 +0000773PyObject *
774_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000776{
Mark Dickinson22b20182010-05-10 21:27:53 +0000777 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 int incr; /* direction to move pstartbyte */
779 const unsigned char* pendbyte; /* MSB of bytes */
780 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300781 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyLongObject* v; /* result */
783 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (n == 0)
786 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 if (little_endian) {
789 pstartbyte = bytes;
790 pendbyte = bytes + n - 1;
791 incr = 1;
792 }
793 else {
794 pstartbyte = bytes + n - 1;
795 pendbyte = bytes;
796 incr = -1;
797 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (is_signed)
800 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200803 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 is positive, and leading 0xff bytes if negative. */
805 {
806 size_t i;
807 const unsigned char* p = pendbyte;
808 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000809 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000812 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 break;
814 }
815 numsignificantbytes = n - i;
816 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
817 actually has 2 significant bytes. OTOH, 0xff0001 ==
818 -0x00ffff, so we wouldn't *need* to bump it there; but we
819 do for 0xffff = -0x0001. To be safe without bothering to
820 check every case, bump it regardless. */
821 if (is_signed && numsignificantbytes < n)
822 ++numsignificantbytes;
823 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000824
Serhiy Storchaka95949422013-08-27 19:40:23 +0300825 /* How many Python int digits do we need? We have
826 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
828 /* catch overflow before it happens */
829 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
830 PyErr_SetString(PyExc_OverflowError,
831 "byte array too long to convert to int");
832 return NULL;
833 }
834 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
835 v = _PyLong_New(ndigits);
836 if (v == NULL)
837 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 /* Copy the bits over. The tricky parts are computing 2's-comp on
840 the fly for signed numbers, and dealing with the mismatch between
841 8-bit bytes and (probably) 15-bit Python digits.*/
842 {
843 size_t i;
844 twodigits carry = 1; /* for 2's-comp calculation */
845 twodigits accum = 0; /* sliding register */
846 unsigned int accumbits = 0; /* number of bits in accum */
847 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
850 twodigits thisbyte = *p;
851 /* Compute correction for 2's comp, if needed. */
852 if (is_signed) {
853 thisbyte = (0xff ^ thisbyte) + carry;
854 carry = thisbyte >> 8;
855 thisbyte &= 0xff;
856 }
857 /* Because we're going LSB to MSB, thisbyte is
858 more significant than what's already in accum,
859 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200860 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 accumbits += 8;
862 if (accumbits >= PyLong_SHIFT) {
863 /* There's enough to fill a Python digit. */
864 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000865 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 ++idigit;
867 accum >>= PyLong_SHIFT;
868 accumbits -= PyLong_SHIFT;
869 assert(accumbits < PyLong_SHIFT);
870 }
871 }
872 assert(accumbits < PyLong_SHIFT);
873 if (accumbits) {
874 assert(idigit < ndigits);
875 v->ob_digit[idigit] = (digit)accum;
876 ++idigit;
877 }
878 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 Py_SIZE(v) = is_signed ? -idigit : idigit;
881 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000882}
883
884int
885_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 unsigned char* bytes, size_t n,
887 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000890 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000892 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
894 digit carry; /* for computing 2's-comp */
895 size_t j; /* # bytes filled */
896 unsigned char* p; /* pointer to next byte in bytes */
897 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 if (Py_SIZE(v) < 0) {
902 ndigits = -(Py_SIZE(v));
903 if (!is_signed) {
904 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000905 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 return -1;
907 }
908 do_twos_comp = 1;
909 }
910 else {
911 ndigits = Py_SIZE(v);
912 do_twos_comp = 0;
913 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 if (little_endian) {
916 p = bytes;
917 pincr = 1;
918 }
919 else {
920 p = bytes + n - 1;
921 pincr = -1;
922 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Copy over all the Python digits.
925 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300926 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 normalized. */
928 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
929 j = 0;
930 accum = 0;
931 accumbits = 0;
932 carry = do_twos_comp ? 1 : 0;
933 for (i = 0; i < ndigits; ++i) {
934 digit thisdigit = v->ob_digit[i];
935 if (do_twos_comp) {
936 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
937 carry = thisdigit >> PyLong_SHIFT;
938 thisdigit &= PyLong_MASK;
939 }
940 /* Because we're going LSB to MSB, thisdigit is more
941 significant than what's already in accum, so needs to be
942 prepended to accum. */
943 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* The most-significant digit may be (probably is) at least
946 partly empty. */
947 if (i == ndigits - 1) {
948 /* Count # of sign bits -- they needn't be stored,
949 * although for signed conversion we need later to
950 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000951 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 while (s != 0) {
953 s >>= 1;
954 accumbits++;
955 }
956 }
957 else
958 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* Store as many bytes as possible. */
961 while (accumbits >= 8) {
962 if (j >= n)
963 goto Overflow;
964 ++j;
965 *p = (unsigned char)(accum & 0xff);
966 p += pincr;
967 accumbits -= 8;
968 accum >>= 8;
969 }
970 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 /* Store the straggler (if any). */
973 assert(accumbits < 8);
974 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
975 if (accumbits > 0) {
976 if (j >= n)
977 goto Overflow;
978 ++j;
979 if (do_twos_comp) {
980 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300981 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 infinite supply of sign bits). */
983 accum |= (~(twodigits)0) << accumbits;
984 }
985 *p = (unsigned char)(accum & 0xff);
986 p += pincr;
987 }
988 else if (j == n && n > 0 && is_signed) {
989 /* The main loop filled the byte array exactly, so the code
990 just above didn't get to ensure there's a sign bit, and the
991 loop below wouldn't add one either. Make sure a sign bit
992 exists. */
993 unsigned char msb = *(p - pincr);
994 int sign_bit_set = msb >= 0x80;
995 assert(accumbits == 0);
996 if (sign_bit_set == do_twos_comp)
997 return 0;
998 else
999 goto Overflow;
1000 }
Tim Peters05607ad2001-06-13 21:01:27 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* Fill remaining bytes with copies of the sign bit. */
1003 {
1004 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1005 for ( ; j < n; ++j, p += pincr)
1006 *p = signbyte;
1007 }
Tim Peters05607ad2001-06-13 21:01:27 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001010
Mark Dickinson22b20182010-05-10 21:27:53 +00001011 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1013 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001014
Tim Peters2a9b3672001-06-11 21:23:58 +00001015}
1016
Serhiy Storchaka95949422013-08-27 19:40:23 +03001017/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001018
1019PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001020PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001021{
Mark Dickinson91044792012-10-18 19:21:43 +01001022#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001023 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001024#else
1025
Tim Peters70128a12001-06-16 08:48:40 +00001026#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001027# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001028#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001029 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001030#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001031
Guido van Rossum78694d91998-09-18 14:14:13 +00001032}
1033
Serhiy Storchaka95949422013-08-27 19:40:23 +03001034/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001035
1036void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001037PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001038{
Tim Peters70128a12001-06-16 08:48:40 +00001039#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1043 x = PyLong_AsLong(vv);
1044 else
1045 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001046#else
Tim Peters70128a12001-06-16 08:48:40 +00001047
Tim Peters70128a12001-06-16 08:48:40 +00001048#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001049# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001050#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001051 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1054 x = PyLong_AsLongLong(vv);
1055 else
1056 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001057
1058#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 if (x == -1 && PyErr_Occurred())
1061 return NULL;
1062 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001063}
1064
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001065/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001066 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001067 */
1068
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001069#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001070
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001071/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001072
1073PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001074PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001077 unsigned long long abs_ival;
1078 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 int ndigits = 0;
1080 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 CHECK_SMALL_INT(ival);
1083 if (ival < 0) {
1084 /* avoid signed overflow on negation; see comments
1085 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001086 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 negative = 1;
1088 }
1089 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001090 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 /* Count the number of Python digits.
1094 We used to pick 5 ("big enough for anything"), but that's a
1095 waste of time and space given that 5*15 = 75 bits are rarely
1096 needed. */
1097 t = abs_ival;
1098 while (t) {
1099 ++ndigits;
1100 t >>= PyLong_SHIFT;
1101 }
1102 v = _PyLong_New(ndigits);
1103 if (v != NULL) {
1104 digit *p = v->ob_digit;
1105 Py_SIZE(v) = negative ? -ndigits : ndigits;
1106 t = abs_ival;
1107 while (t) {
1108 *p++ = (digit)(t & PyLong_MASK);
1109 t >>= PyLong_SHIFT;
1110 }
1111 }
1112 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001113}
1114
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001115/* Create a new int object from a C unsigned long long int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001116
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001117PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001118PyLong_FromUnsignedLongLong(unsigned long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001121 unsigned long long t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (ival < PyLong_BASE)
1125 return PyLong_FromLong((long)ival);
1126 /* Count the number of Python digits. */
orenmn86aa2692017-03-06 10:42:47 +02001127 t = ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 while (t) {
1129 ++ndigits;
1130 t >>= PyLong_SHIFT;
1131 }
1132 v = _PyLong_New(ndigits);
1133 if (v != NULL) {
1134 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 while (ival) {
1136 *p++ = (digit)(ival & PyLong_MASK);
1137 ival >>= PyLong_SHIFT;
1138 }
1139 }
1140 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001141}
1142
Serhiy Storchaka95949422013-08-27 19:40:23 +03001143/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001144
1145PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001146PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 PyLongObject *v;
1149 size_t abs_ival;
1150 size_t t; /* unsigned so >> doesn't propagate sign bit */
1151 int ndigits = 0;
1152 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 CHECK_SMALL_INT(ival);
1155 if (ival < 0) {
1156 /* avoid signed overflow when ival = SIZE_T_MIN */
1157 abs_ival = (size_t)(-1-ival)+1;
1158 negative = 1;
1159 }
1160 else {
1161 abs_ival = (size_t)ival;
1162 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 /* Count the number of Python digits. */
1165 t = abs_ival;
1166 while (t) {
1167 ++ndigits;
1168 t >>= PyLong_SHIFT;
1169 }
1170 v = _PyLong_New(ndigits);
1171 if (v != NULL) {
1172 digit *p = v->ob_digit;
1173 Py_SIZE(v) = negative ? -ndigits : ndigits;
1174 t = abs_ival;
1175 while (t) {
1176 *p++ = (digit)(t & PyLong_MASK);
1177 t >>= PyLong_SHIFT;
1178 }
1179 }
1180 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001181}
1182
Serhiy Storchaka95949422013-08-27 19:40:23 +03001183/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001184
1185PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001186PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyLongObject *v;
1189 size_t t;
1190 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (ival < PyLong_BASE)
1193 return PyLong_FromLong((long)ival);
1194 /* Count the number of Python digits. */
1195 t = ival;
1196 while (t) {
1197 ++ndigits;
1198 t >>= PyLong_SHIFT;
1199 }
1200 v = _PyLong_New(ndigits);
1201 if (v != NULL) {
1202 digit *p = v->ob_digit;
1203 Py_SIZE(v) = ndigits;
1204 while (ival) {
1205 *p++ = (digit)(ival & PyLong_MASK);
1206 ival >>= PyLong_SHIFT;
1207 }
1208 }
1209 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001210}
1211
Serhiy Storchaka95949422013-08-27 19:40:23 +03001212/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001213 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001214
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001215long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001216PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001219 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001221 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (vv == NULL) {
1224 PyErr_BadInternalCall();
1225 return -1;
1226 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001227
1228 if (PyLong_Check(vv)) {
1229 v = (PyLongObject *)vv;
1230 }
1231 else {
1232 v = _PyLong_FromNbInt(vv);
1233 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001235 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001237
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001238 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001240 case -1:
1241 bytes = -(sdigit)v->ob_digit[0];
1242 break;
1243 case 0:
1244 bytes = 0;
1245 break;
1246 case 1:
1247 bytes = v->ob_digit[0];
1248 break;
1249 default:
1250 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001251 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001253 if (do_decref) {
1254 Py_DECREF(v);
1255 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001256
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001257 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001259 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 else
1261 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001262}
1263
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001264/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001265 Return -1 and set an error if overflow occurs. */
1266
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001267unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001268PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001271 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001273
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001274 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001276 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001278 if (!PyLong_Check(vv)) {
1279 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001280 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001281 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 v = (PyLongObject*)vv;
1284 switch(Py_SIZE(v)) {
1285 case 0: return 0;
1286 case 1: return v->ob_digit[0];
1287 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001288
Mark Dickinson22b20182010-05-10 21:27:53 +00001289 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001290 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001291
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001292 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001294 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 else
1296 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001297}
Tim Petersd1a7da62001-06-13 00:35:57 +00001298
Serhiy Storchaka95949422013-08-27 19:40:23 +03001299/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001300 Returns -1 and sets an error condition if an error occurs. */
1301
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001302static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001303_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001304{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001305 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001306 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 Py_ssize_t i;
1308 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (vv == NULL || !PyLong_Check(vv)) {
1311 PyErr_BadInternalCall();
1312 return (unsigned long) -1;
1313 }
1314 v = (PyLongObject *)vv;
1315 switch(Py_SIZE(v)) {
1316 case 0: return 0;
1317 case 1: return v->ob_digit[0];
1318 }
1319 i = Py_SIZE(v);
1320 sign = 1;
1321 x = 0;
1322 if (i < 0) {
1323 sign = -1;
1324 i = -i;
1325 }
1326 while (--i >= 0) {
1327 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1328 }
1329 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001330}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001331
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001332unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001333PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001336 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001337
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001338 if (op == NULL) {
1339 PyErr_BadInternalCall();
1340 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001342
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001343 if (PyLong_Check(op)) {
1344 return _PyLong_AsUnsignedLongLongMask(op);
1345 }
1346
1347 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001349 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001350
1351 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1352 Py_DECREF(lo);
1353 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001354}
Tim Petersd1a7da62001-06-13 00:35:57 +00001355
Serhiy Storchaka95949422013-08-27 19:40:23 +03001356/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001357 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001358
Mark Dickinson8d48b432011-10-23 20:47:14 +01001359 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1360 the result. Otherwise *overflow is 0.
1361
1362 For other errors (e.g., TypeError), return -1 and set an error condition.
1363 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001364*/
1365
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001366long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001367PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001370 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001371 unsigned long long x, prev;
1372 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 Py_ssize_t i;
1374 int sign;
1375 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 *overflow = 0;
1378 if (vv == NULL) {
1379 PyErr_BadInternalCall();
1380 return -1;
1381 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001382
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001383 if (PyLong_Check(vv)) {
1384 v = (PyLongObject *)vv;
1385 }
1386 else {
1387 v = _PyLong_FromNbInt(vv);
1388 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 return -1;
1390 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 switch (i) {
1397 case -1:
1398 res = -(sdigit)v->ob_digit[0];
1399 break;
1400 case 0:
1401 res = 0;
1402 break;
1403 case 1:
1404 res = v->ob_digit[0];
1405 break;
1406 default:
1407 sign = 1;
1408 x = 0;
1409 if (i < 0) {
1410 sign = -1;
1411 i = -(i);
1412 }
1413 while (--i >= 0) {
1414 prev = x;
1415 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1416 if ((x >> PyLong_SHIFT) != prev) {
1417 *overflow = sign;
1418 goto exit;
1419 }
1420 }
1421 /* Haven't lost any bits, but casting to long requires extra
1422 * care (see comment above).
1423 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001424 if (x <= (unsigned long long)PY_LLONG_MAX) {
1425 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 }
1427 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1428 res = PY_LLONG_MIN;
1429 }
1430 else {
1431 *overflow = sign;
1432 /* res is already set to -1 */
1433 }
1434 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001435 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001437 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 }
1439 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001440}
1441
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001442int
1443_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1444{
1445 unsigned long uval;
1446
1447 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1448 PyErr_SetString(PyExc_ValueError, "value must be positive");
1449 return 0;
1450 }
1451 uval = PyLong_AsUnsignedLong(obj);
1452 if (uval == (unsigned long)-1 && PyErr_Occurred())
1453 return 0;
1454 if (uval > USHRT_MAX) {
1455 PyErr_SetString(PyExc_OverflowError,
1456 "Python int too large for C unsigned short");
1457 return 0;
1458 }
1459
1460 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1461 return 1;
1462}
1463
1464int
1465_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1466{
1467 unsigned long uval;
1468
1469 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1470 PyErr_SetString(PyExc_ValueError, "value must be positive");
1471 return 0;
1472 }
1473 uval = PyLong_AsUnsignedLong(obj);
1474 if (uval == (unsigned long)-1 && PyErr_Occurred())
1475 return 0;
1476 if (uval > UINT_MAX) {
1477 PyErr_SetString(PyExc_OverflowError,
1478 "Python int too large for C unsigned int");
1479 return 0;
1480 }
1481
1482 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1483 return 1;
1484}
1485
1486int
1487_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1488{
1489 unsigned long uval;
1490
1491 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1492 PyErr_SetString(PyExc_ValueError, "value must be positive");
1493 return 0;
1494 }
1495 uval = PyLong_AsUnsignedLong(obj);
1496 if (uval == (unsigned long)-1 && PyErr_Occurred())
1497 return 0;
1498
1499 *(unsigned long *)ptr = uval;
1500 return 1;
1501}
1502
1503int
1504_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1505{
1506 unsigned long long uval;
1507
1508 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1509 PyErr_SetString(PyExc_ValueError, "value must be positive");
1510 return 0;
1511 }
1512 uval = PyLong_AsUnsignedLongLong(obj);
1513 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1514 return 0;
1515
1516 *(unsigned long long *)ptr = uval;
1517 return 1;
1518}
1519
1520int
1521_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1522{
1523 size_t uval;
1524
1525 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1526 PyErr_SetString(PyExc_ValueError, "value must be positive");
1527 return 0;
1528 }
1529 uval = PyLong_AsSize_t(obj);
1530 if (uval == (size_t)-1 && PyErr_Occurred())
1531 return 0;
1532
1533 *(size_t *)ptr = uval;
1534 return 1;
1535}
1536
1537
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001538#define CHECK_BINOP(v,w) \
1539 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001540 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1541 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001542 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001543
Tim Peters877a2122002-08-12 05:09:36 +00001544/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1545 * is modified in place, by adding y to it. Carries are propagated as far as
1546 * x[m-1], and the remaining carry (0 or 1) is returned.
1547 */
1548static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001549v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 Py_ssize_t i;
1552 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 assert(m >= n);
1555 for (i = 0; i < n; ++i) {
1556 carry += x[i] + y[i];
1557 x[i] = carry & PyLong_MASK;
1558 carry >>= PyLong_SHIFT;
1559 assert((carry & 1) == carry);
1560 }
1561 for (; carry && i < m; ++i) {
1562 carry += x[i];
1563 x[i] = carry & PyLong_MASK;
1564 carry >>= PyLong_SHIFT;
1565 assert((carry & 1) == carry);
1566 }
1567 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001568}
1569
1570/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1571 * is modified in place, by subtracting y from it. Borrows are propagated as
1572 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1573 */
1574static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001575v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 Py_ssize_t i;
1578 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 assert(m >= n);
1581 for (i = 0; i < n; ++i) {
1582 borrow = x[i] - y[i] - borrow;
1583 x[i] = borrow & PyLong_MASK;
1584 borrow >>= PyLong_SHIFT;
1585 borrow &= 1; /* keep only 1 sign bit */
1586 }
1587 for (; borrow && i < m; ++i) {
1588 borrow = x[i] - borrow;
1589 x[i] = borrow & PyLong_MASK;
1590 borrow >>= PyLong_SHIFT;
1591 borrow &= 1;
1592 }
1593 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001594}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001595
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001596/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1597 * result in z[0:m], and return the d bits shifted out of the top.
1598 */
1599static digit
1600v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 Py_ssize_t i;
1603 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 assert(0 <= d && d < PyLong_SHIFT);
1606 for (i=0; i < m; i++) {
1607 twodigits acc = (twodigits)a[i] << d | carry;
1608 z[i] = (digit)acc & PyLong_MASK;
1609 carry = (digit)(acc >> PyLong_SHIFT);
1610 }
1611 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001612}
1613
1614/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1615 * result in z[0:m], and return the d bits shifted out of the bottom.
1616 */
1617static digit
1618v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 Py_ssize_t i;
1621 digit carry = 0;
1622 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 assert(0 <= d && d < PyLong_SHIFT);
1625 for (i=m; i-- > 0;) {
1626 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1627 carry = (digit)acc & mask;
1628 z[i] = (digit)(acc >> d);
1629 }
1630 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001631}
1632
Tim Peters212e6142001-07-14 12:23:19 +00001633/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1634 in pout, and returning the remainder. pin and pout point at the LSD.
1635 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001636 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001637 immutable. */
1638
1639static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001640inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 assert(n > 0 && n <= PyLong_MASK);
1645 pin += size;
1646 pout += size;
1647 while (--size >= 0) {
1648 digit hi;
1649 rem = (rem << PyLong_SHIFT) | *--pin;
1650 *--pout = hi = (digit)(rem / n);
1651 rem -= (twodigits)hi * n;
1652 }
1653 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001654}
1655
Serhiy Storchaka95949422013-08-27 19:40:23 +03001656/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001657 (as function result) and the remainder (through *prem).
1658 The sign of a is ignored; n should not be zero. */
1659
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001660static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001661divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001662{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001663 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 assert(n > 0 && n <= PyLong_MASK);
1667 z = _PyLong_New(size);
1668 if (z == NULL)
1669 return NULL;
1670 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1671 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001672}
1673
Serhiy Storchaka95949422013-08-27 19:40:23 +03001674/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001675 string. (Return value is non-shared so that callers can modify the
1676 returned value if necessary.) */
1677
Victor Stinnerd3f08822012-05-29 12:57:52 +02001678static int
1679long_to_decimal_string_internal(PyObject *aa,
1680 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001681 _PyUnicodeWriter *writer,
1682 _PyBytesWriter *bytes_writer,
1683 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001686 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 Py_ssize_t size, strlen, size_a, i, j;
1688 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001690 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001691 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 a = (PyLongObject *)aa;
1694 if (a == NULL || !PyLong_Check(a)) {
1695 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001696 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001698 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* quick and dirty upper bound for the number of digits
1702 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 But log2(a) < size_a * PyLong_SHIFT, and
1707 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001708 > 3.3 * _PyLong_DECIMAL_SHIFT
1709
1710 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1711 size_a + size_a / d < size_a + size_a / floor(d),
1712 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1713 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001715 d = (33 * _PyLong_DECIMAL_SHIFT) /
1716 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1717 assert(size_a < PY_SSIZE_T_MAX/2);
1718 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 scratch = _PyLong_New(size);
1720 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001721 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 /* convert array of base _PyLong_BASE digits in pin to an array of
1724 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1725 Volume 2 (3rd edn), section 4.4, Method 1b). */
1726 pin = a->ob_digit;
1727 pout = scratch->ob_digit;
1728 size = 0;
1729 for (i = size_a; --i >= 0; ) {
1730 digit hi = pin[i];
1731 for (j = 0; j < size; j++) {
1732 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1733 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1734 pout[j] = (digit)(z - (twodigits)hi *
1735 _PyLong_DECIMAL_BASE);
1736 }
1737 while (hi) {
1738 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1739 hi /= _PyLong_DECIMAL_BASE;
1740 }
1741 /* check for keyboard interrupt */
1742 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001743 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001744 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001745 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 }
1747 /* pout should have at least one digit, so that the case when a = 0
1748 works correctly */
1749 if (size == 0)
1750 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 /* calculate exact length of output string, and allocate */
1753 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1754 tenpow = 10;
1755 rem = pout[size-1];
1756 while (rem >= tenpow) {
1757 tenpow *= 10;
1758 strlen++;
1759 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001760 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001761 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1762 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001763 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001764 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001765 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001767 else if (bytes_writer) {
1768 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1769 if (*bytes_str == NULL) {
1770 Py_DECREF(scratch);
1771 return -1;
1772 }
1773 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001774 else {
1775 str = PyUnicode_New(strlen, '9');
1776 if (str == NULL) {
1777 Py_DECREF(scratch);
1778 return -1;
1779 }
1780 kind = PyUnicode_KIND(str);
1781 }
1782
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001783#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001784 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001785 /* pout[0] through pout[size-2] contribute exactly \
1786 _PyLong_DECIMAL_SHIFT digits each */ \
1787 for (i=0; i < size - 1; i++) { \
1788 rem = pout[i]; \
1789 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1790 *--p = '0' + rem % 10; \
1791 rem /= 10; \
1792 } \
1793 } \
1794 /* pout[size-1]: always produce at least one decimal digit */ \
1795 rem = pout[i]; \
1796 do { \
1797 *--p = '0' + rem % 10; \
1798 rem /= 10; \
1799 } while (rem != 0); \
1800 \
1801 /* and sign */ \
1802 if (negative) \
1803 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001804 } while (0)
1805
1806#define WRITE_UNICODE_DIGITS(TYPE) \
1807 do { \
1808 if (writer) \
1809 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1810 else \
1811 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1812 \
1813 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001814 \
1815 /* check we've counted correctly */ \
1816 if (writer) \
1817 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1818 else \
1819 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1820 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001823 if (bytes_writer) {
1824 char *p = *bytes_str + strlen;
1825 WRITE_DIGITS(p);
1826 assert(p == *bytes_str);
1827 }
1828 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001829 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001830 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001832 else if (kind == PyUnicode_2BYTE_KIND) {
1833 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001834 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001835 }
1836 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001837 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001838 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001839 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001840 }
1841#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001842#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001845 if (writer) {
1846 writer->pos += strlen;
1847 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001848 else if (bytes_writer) {
1849 (*bytes_str) += strlen;
1850 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001851 else {
1852 assert(_PyUnicode_CheckConsistency(str, 1));
1853 *p_output = (PyObject *)str;
1854 }
1855 return 0;
1856}
1857
1858static PyObject *
1859long_to_decimal_string(PyObject *aa)
1860{
1861 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001862 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001863 return NULL;
1864 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001865}
1866
Serhiy Storchaka95949422013-08-27 19:40:23 +03001867/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001868 which should be one of 2, 8 or 16. Return a string object.
1869 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1870 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001871
Victor Stinnerd3f08822012-05-29 12:57:52 +02001872static int
1873long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001874 PyObject **p_output, _PyUnicodeWriter *writer,
1875 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001876{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001877 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001878 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001879 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001881 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001882 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001884
Victor Stinnerd3f08822012-05-29 12:57:52 +02001885 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (a == NULL || !PyLong_Check(a)) {
1887 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001888 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001890 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001891 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 /* Compute a rough upper bound for the length of the string */
1894 switch (base) {
1895 case 16:
1896 bits = 4;
1897 break;
1898 case 8:
1899 bits = 3;
1900 break;
1901 case 2:
1902 bits = 1;
1903 break;
1904 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001905 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001907
Mark Dickinsone2846542012-04-20 21:21:24 +01001908 /* Compute exact length 'sz' of output string. */
1909 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001910 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001911 }
1912 else {
1913 Py_ssize_t size_a_in_bits;
1914 /* Ensure overflow doesn't occur during computation of sz. */
1915 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1916 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001917 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001918 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001919 }
1920 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1921 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001922 /* Allow 1 character for a '-' sign. */
1923 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1924 }
1925 if (alternate) {
1926 /* 2 characters for prefix */
1927 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001928 }
1929
Victor Stinnerd3f08822012-05-29 12:57:52 +02001930 if (writer) {
1931 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1932 return -1;
1933 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001935 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001936 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1937 if (*bytes_str == NULL)
1938 return -1;
1939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001941 v = PyUnicode_New(sz, 'x');
1942 if (v == NULL)
1943 return -1;
1944 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001946
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001947#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001948 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001949 if (size_a == 0) { \
1950 *--p = '0'; \
1951 } \
1952 else { \
1953 /* JRH: special case for power-of-2 bases */ \
1954 twodigits accum = 0; \
1955 int accumbits = 0; /* # of bits in accum */ \
1956 Py_ssize_t i; \
1957 for (i = 0; i < size_a; ++i) { \
1958 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1959 accumbits += PyLong_SHIFT; \
1960 assert(accumbits >= bits); \
1961 do { \
1962 char cdigit; \
1963 cdigit = (char)(accum & (base - 1)); \
1964 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1965 *--p = cdigit; \
1966 accumbits -= bits; \
1967 accum >>= bits; \
1968 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1969 } \
1970 } \
1971 \
1972 if (alternate) { \
1973 if (base == 16) \
1974 *--p = 'x'; \
1975 else if (base == 8) \
1976 *--p = 'o'; \
1977 else /* (base == 2) */ \
1978 *--p = 'b'; \
1979 *--p = '0'; \
1980 } \
1981 if (negative) \
1982 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001983 } while (0)
1984
1985#define WRITE_UNICODE_DIGITS(TYPE) \
1986 do { \
1987 if (writer) \
1988 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1989 else \
1990 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1991 \
1992 WRITE_DIGITS(p); \
1993 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001994 if (writer) \
1995 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1996 else \
1997 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1998 } while (0)
1999
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002000 if (bytes_writer) {
2001 char *p = *bytes_str + sz;
2002 WRITE_DIGITS(p);
2003 assert(p == *bytes_str);
2004 }
2005 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002006 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002007 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002008 }
2009 else if (kind == PyUnicode_2BYTE_KIND) {
2010 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002011 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002012 }
2013 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002014 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002015 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002016 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002017 }
2018#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002019#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002020
2021 if (writer) {
2022 writer->pos += sz;
2023 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002024 else if (bytes_writer) {
2025 (*bytes_str) += sz;
2026 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002027 else {
2028 assert(_PyUnicode_CheckConsistency(v, 1));
2029 *p_output = v;
2030 }
2031 return 0;
2032}
2033
2034PyObject *
2035_PyLong_Format(PyObject *obj, int base)
2036{
2037 PyObject *str;
2038 int err;
2039 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002040 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002041 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002042 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002043 if (err == -1)
2044 return NULL;
2045 return str;
2046}
2047
2048int
2049_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2050 PyObject *obj,
2051 int base, int alternate)
2052{
2053 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002054 return long_to_decimal_string_internal(obj, NULL, writer,
2055 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002056 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002057 return long_format_binary(obj, base, alternate, NULL, writer,
2058 NULL, NULL);
2059}
2060
2061char*
2062_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2063 PyObject *obj,
2064 int base, int alternate)
2065{
2066 char *str2;
2067 int res;
2068 str2 = str;
2069 if (base == 10)
2070 res = long_to_decimal_string_internal(obj, NULL, NULL,
2071 writer, &str2);
2072 else
2073 res = long_format_binary(obj, base, alternate, NULL, NULL,
2074 writer, &str2);
2075 if (res < 0)
2076 return NULL;
2077 assert(str2 != NULL);
2078 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079}
2080
Thomas Wouters477c8d52006-05-27 19:21:47 +00002081/* Table of digit values for 8-bit string -> integer conversion.
2082 * '0' maps to 0, ..., '9' maps to 9.
2083 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2084 * All other indices map to 37.
2085 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002086 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002087 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002088unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2090 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2091 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2092 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2093 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2094 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2095 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2096 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2097 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2098 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2099 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2100 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2101 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2102 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2103 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2104 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002105};
2106
2107/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002108 * 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 +03002109 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002110 * The point to this routine is that it takes time linear in the number of
2111 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002112 *
2113 * Return values:
2114 * -1 on syntax error (exception needs to be set, *res is untouched)
2115 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002116 */
Brett Cannona721aba2016-09-09 14:57:09 -07002117static int
2118long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002119{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002120 const char *p = *str;
2121 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002122 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002123 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 int bits_per_char;
2125 Py_ssize_t n;
2126 PyLongObject *z;
2127 twodigits accum;
2128 int bits_in_accum;
2129 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2132 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002133 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002135 }
2136 /* count digits and set p to end-of-string */
2137 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2138 if (*p == '_') {
2139 if (prev == '_') {
2140 *str = p - 1;
2141 return -1;
2142 }
2143 } else {
2144 ++digits;
2145 }
2146 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002148 }
2149 if (prev == '_') {
2150 /* Trailing underscore not allowed. */
2151 *str = p - 1;
2152 return -1;
2153 }
2154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002156 /* n <- the number of Python digits needed,
2157 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2158 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 PyErr_SetString(PyExc_ValueError,
2160 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002161 *res = NULL;
2162 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002164 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002166 if (z == NULL) {
2167 *res = NULL;
2168 return 0;
2169 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002170 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 * from least to most significant in both.
2172 */
2173 accum = 0;
2174 bits_in_accum = 0;
2175 pdigit = z->ob_digit;
2176 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002177 int k;
2178 if (*p == '_') {
2179 continue;
2180 }
2181 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 assert(k >= 0 && k < base);
2183 accum |= (twodigits)k << bits_in_accum;
2184 bits_in_accum += bits_per_char;
2185 if (bits_in_accum >= PyLong_SHIFT) {
2186 *pdigit++ = (digit)(accum & PyLong_MASK);
2187 assert(pdigit - z->ob_digit <= n);
2188 accum >>= PyLong_SHIFT;
2189 bits_in_accum -= PyLong_SHIFT;
2190 assert(bits_in_accum < PyLong_SHIFT);
2191 }
2192 }
2193 if (bits_in_accum) {
2194 assert(bits_in_accum <= PyLong_SHIFT);
2195 *pdigit++ = (digit)accum;
2196 assert(pdigit - z->ob_digit <= n);
2197 }
2198 while (pdigit - z->ob_digit < n)
2199 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002200 *res = long_normalize(z);
2201 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002202}
2203
Serhiy Storchaka95949422013-08-27 19:40:23 +03002204/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002205 * ignored.
2206 *
2207 * If successful, a PyLong object will be returned and 'pend' will be pointing
2208 * to the first unused byte unless it's NULL.
2209 *
2210 * If unsuccessful, NULL will be returned.
2211 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002212PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002213PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002216 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 PyLongObject *z = NULL;
2218 PyObject *strobj;
2219 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 if ((base != 0 && base < 2) || base > 36) {
2222 PyErr_SetString(PyExc_ValueError,
2223 "int() arg 2 must be >= 2 and <= 36");
2224 return NULL;
2225 }
Brett Cannona721aba2016-09-09 14:57:09 -07002226 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002228 }
2229 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002231 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 else if (*str == '-') {
2233 ++str;
2234 sign = -1;
2235 }
2236 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002237 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002239 }
2240 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002242 }
2243 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002245 }
2246 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002248 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 else {
2250 /* "old" (C-style) octal literal, now invalid.
2251 it might still be zero though */
2252 error_if_nonzero = 1;
2253 base = 10;
2254 }
2255 }
2256 if (str[0] == '0' &&
2257 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2258 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002259 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002261 /* One underscore allowed here. */
2262 if (*str == '_') {
2263 ++str;
2264 }
2265 }
2266 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002267 /* May not start with underscores. */
2268 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002269 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002272 if ((base & (base - 1)) == 0) {
2273 int res = long_from_binary_base(&str, base, &z);
2274 if (res < 0) {
2275 /* Syntax error. */
2276 goto onError;
2277 }
2278 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002280/***
2281Binary bases can be converted in time linear in the number of digits, because
2282Python's representation base is binary. Other bases (including decimal!) use
2283the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002284
Thomas Wouters477c8d52006-05-27 19:21:47 +00002285First some math: the largest integer that can be expressed in N base-B digits
2286is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2287case number of Python digits needed to hold it is the smallest integer n s.t.
2288
2289 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2290 BASE**n >= B**N [taking logs to base BASE]
2291 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2292
2293The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002294this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002295and the result is computed into it.
2296
2297The input string is actually treated as being in base base**i (i.e., i digits
2298are processed at a time), where two more static arrays hold:
2299
2300 convwidth_base[base] = the largest integer i such that base**i <= BASE
2301 convmultmax_base[base] = base ** convwidth_base[base]
2302
2303The first of these is the largest i such that i consecutive input digits
2304must fit in a single Python digit. The second is effectively the input
2305base we're really using.
2306
2307Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2308convmultmax_base[base], the result is "simply"
2309
2310 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2311
2312where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002313
2314Error analysis: as above, the number of Python digits `n` needed is worst-
2315case
2316
2317 n >= N * log(B)/log(BASE)
2318
2319where `N` is the number of input digits in base `B`. This is computed via
2320
2321 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2322
2323below. Two numeric concerns are how much space this can waste, and whether
2324the computed result can be too small. To be concrete, assume BASE = 2**15,
2325which is the default (and it's unlikely anyone changes that).
2326
2327Waste isn't a problem: provided the first input digit isn't 0, the difference
2328between the worst-case input with N digits and the smallest input with N
2329digits is about a factor of B, but B is small compared to BASE so at most
2330one allocated Python digit can remain unused on that count. If
2331N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2332and adding 1 returns a result 1 larger than necessary. However, that can't
2333happen: whenever B is a power of 2, long_from_binary_base() is called
2334instead, and it's impossible for B**i to be an integer power of 2**15 when
2335B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2336an exact integer when B is not a power of 2, since B**i has a prime factor
2337other than 2 in that case, but (2**15)**j's only prime factor is 2).
2338
2339The computed result can be too small if the true value of N*log(B)/log(BASE)
2340is a little bit larger than an exact integer, but due to roundoff errors (in
2341computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2342yields a numeric result a little less than that integer. Unfortunately, "how
2343close can a transcendental function get to an integer over some range?"
2344questions are generally theoretically intractable. Computer analysis via
2345continued fractions is practical: expand log(B)/log(BASE) via continued
2346fractions, giving a sequence i/j of "the best" rational approximations. Then
2347j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2348we can get very close to being in trouble, but very rarely. For example,
234976573 is a denominator in one of the continued-fraction approximations to
2350log(10)/log(2**15), and indeed:
2351
2352 >>> log(10)/log(2**15)*76573
2353 16958.000000654003
2354
2355is very close to an integer. If we were working with IEEE single-precision,
2356rounding errors could kill us. Finding worst cases in IEEE double-precision
2357requires better-than-double-precision log() functions, and Tim didn't bother.
2358Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002359new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002360This should happen extremely rarely, and in fact I don't have a test case
2361that triggers it(!). Instead the code was tested by artificially allocating
2362just 1 digit at the start, so that the copying code was exercised for every
2363digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002364***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002365 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002367 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 int i;
2369 int convwidth;
2370 twodigits convmultmax, convmult;
2371 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002372 const char *scan, *lastdigit;
2373 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 static double log_base_BASE[37] = {0.0e0,};
2376 static int convwidth_base[37] = {0,};
2377 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 if (log_base_BASE[base] == 0.0) {
2380 twodigits convmax = base;
2381 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002382
Mark Dickinson22b20182010-05-10 21:27:53 +00002383 log_base_BASE[base] = (log((double)base) /
2384 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 for (;;) {
2386 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002387 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002389 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 convmax = next;
2391 ++i;
2392 }
2393 convmultmax_base[base] = convmax;
2394 assert(i > 0);
2395 convwidth_base[base] = i;
2396 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 /* Find length of the string of numeric characters. */
2399 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002400 lastdigit = str;
2401
2402 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2403 if (*scan == '_') {
2404 if (prev == '_') {
2405 /* Only one underscore allowed. */
2406 str = lastdigit + 1;
2407 goto onError;
2408 }
2409 }
2410 else {
2411 ++digits;
2412 lastdigit = scan;
2413 }
2414 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002416 }
2417 if (prev == '_') {
2418 /* Trailing underscore not allowed. */
2419 /* Set error pointer to first underscore. */
2420 str = lastdigit + 1;
2421 goto onError;
2422 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002423
Serhiy Storchaka95949422013-08-27 19:40:23 +03002424 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 * integer with this base and length. Note that there's no
2426 * need to initialize z->ob_digit -- no slot is read up before
2427 * being stored into.
2428 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002429 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2430 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002431 /* The same exception as in _PyLong_New(). */
2432 PyErr_SetString(PyExc_OverflowError,
2433 "too many digits in integer");
2434 return NULL;
2435 }
2436 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 /* Uncomment next line to test exceedingly rare copy code */
2438 /* size_z = 1; */
2439 assert(size_z > 0);
2440 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002441 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002443 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 /* `convwidth` consecutive input digits are treated as a single
2447 * digit in base `convmultmax`.
2448 */
2449 convwidth = convwidth_base[base];
2450 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 /* Work ;-) */
2453 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002454 if (*str == '_') {
2455 str++;
2456 continue;
2457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* grab up to convwidth digits from the input string */
2459 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002460 for (i = 1; i < convwidth && str != scan; ++str) {
2461 if (*str == '_') {
2462 continue;
2463 }
2464 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002466 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 assert(c < PyLong_BASE);
2468 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 convmult = convmultmax;
2471 /* Calculate the shift only if we couldn't get
2472 * convwidth digits.
2473 */
2474 if (i != convwidth) {
2475 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002476 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002478 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 /* Multiply z by convmult, and add c. */
2482 pz = z->ob_digit;
2483 pzstop = pz + Py_SIZE(z);
2484 for (; pz < pzstop; ++pz) {
2485 c += (twodigits)*pz * convmult;
2486 *pz = (digit)(c & PyLong_MASK);
2487 c >>= PyLong_SHIFT;
2488 }
2489 /* carry off the current end? */
2490 if (c) {
2491 assert(c < PyLong_BASE);
2492 if (Py_SIZE(z) < size_z) {
2493 *pz = (digit)c;
2494 ++Py_SIZE(z);
2495 }
2496 else {
2497 PyLongObject *tmp;
2498 /* Extremely rare. Get more space. */
2499 assert(Py_SIZE(z) == size_z);
2500 tmp = _PyLong_New(size_z + 1);
2501 if (tmp == NULL) {
2502 Py_DECREF(z);
2503 return NULL;
2504 }
2505 memcpy(tmp->ob_digit,
2506 z->ob_digit,
2507 sizeof(digit) * size_z);
2508 Py_DECREF(z);
2509 z = tmp;
2510 z->ob_digit[size_z] = (digit)c;
2511 ++size_z;
2512 }
2513 }
2514 }
2515 }
Brett Cannona721aba2016-09-09 14:57:09 -07002516 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002518 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 if (error_if_nonzero) {
2520 /* reset the base to 0, else the exception message
2521 doesn't make too much sense */
2522 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002523 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002525 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 /* there might still be other problems, therefore base
2527 remains zero here for the same reason */
2528 }
Brett Cannona721aba2016-09-09 14:57:09 -07002529 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002531 }
2532 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002534 }
2535 while (*str && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002537 }
2538 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002540 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002542 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002543 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002544 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002545 }
2546 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002547 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002548 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002549 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002550
Mark Dickinson22b20182010-05-10 21:27:53 +00002551 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002552 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002553 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002554 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 Py_XDECREF(z);
2556 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2557 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002558 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002562 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 base, strobj);
2564 Py_DECREF(strobj);
2565 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002566}
2567
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002568/* Since PyLong_FromString doesn't have a length parameter,
2569 * check here for possible NULs in the string.
2570 *
2571 * Reports an invalid literal as a bytes object.
2572 */
2573PyObject *
2574_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2575{
2576 PyObject *result, *strobj;
2577 char *end = NULL;
2578
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002579 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002580 if (end == NULL || (result != NULL && end == s + len))
2581 return result;
2582 Py_XDECREF(result);
2583 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2584 if (strobj != NULL) {
2585 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002586 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002587 base, strobj);
2588 Py_DECREF(strobj);
2589 }
2590 return NULL;
2591}
2592
Guido van Rossum9e896b32000-04-05 20:11:21 +00002593PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002594PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002595{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002596 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002597 if (unicode == NULL)
2598 return NULL;
2599 v = PyLong_FromUnicodeObject(unicode, base);
2600 Py_DECREF(unicode);
2601 return v;
2602}
2603
2604PyObject *
2605PyLong_FromUnicodeObject(PyObject *u, int base)
2606{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002607 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002608 const char *buffer;
2609 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002610 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002611
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002612 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002613 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002615 assert(PyUnicode_IS_ASCII(asciidig));
2616 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002617 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002618 assert(buffer != NULL);
2619
2620 result = PyLong_FromString(buffer, &end, base);
2621 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002622 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002623 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002625 Py_DECREF(asciidig);
2626 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002627 PyErr_Format(PyExc_ValueError,
2628 "invalid literal for int() with base %d: %.200R",
2629 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002630 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002631}
2632
Tim Peters9f688bf2000-07-07 15:53:28 +00002633/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002634static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002636static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002637
Serhiy Storchaka95949422013-08-27 19:40:23 +03002638/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002639
Guido van Rossume32e0141992-01-19 16:31:05 +00002640static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002641long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002643{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002644 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 if (size_b == 0) {
2648 PyErr_SetString(PyExc_ZeroDivisionError,
2649 "integer division or modulo by zero");
2650 return -1;
2651 }
2652 if (size_a < size_b ||
2653 (size_a == size_b &&
2654 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2655 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002656 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002657 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002658 return -1;
2659 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002660 Py_INCREF(_PyLong_Zero);
2661 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 return 0;
2663 }
2664 if (size_b == 1) {
2665 digit rem = 0;
2666 z = divrem1(a, b->ob_digit[0], &rem);
2667 if (z == NULL)
2668 return -1;
2669 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2670 if (*prem == NULL) {
2671 Py_DECREF(z);
2672 return -1;
2673 }
2674 }
2675 else {
2676 z = x_divrem(a, b, prem);
2677 if (z == NULL)
2678 return -1;
2679 }
2680 /* Set the signs.
2681 The quotient z has the sign of a*b;
2682 the remainder r has the sign of a,
2683 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002684 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2685 _PyLong_Negate(&z);
2686 if (z == NULL) {
2687 Py_CLEAR(*prem);
2688 return -1;
2689 }
2690 }
2691 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2692 _PyLong_Negate(prem);
2693 if (*prem == NULL) {
2694 Py_DECREF(z);
2695 Py_CLEAR(*prem);
2696 return -1;
2697 }
2698 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 *pdiv = maybe_small_long(z);
2700 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002701}
2702
Serhiy Storchaka95949422013-08-27 19:40:23 +03002703/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002704 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002705
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002706static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002707x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 PyLongObject *v, *w, *a;
2710 Py_ssize_t i, k, size_v, size_w;
2711 int d;
2712 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2713 twodigits vv;
2714 sdigit zhi;
2715 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2718 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2719 handle the special case when the initial estimate q for a quotient
2720 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2721 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002724 size_v = Py_ABS(Py_SIZE(v1));
2725 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2727 v = _PyLong_New(size_v+1);
2728 if (v == NULL) {
2729 *prem = NULL;
2730 return NULL;
2731 }
2732 w = _PyLong_New(size_w);
2733 if (w == NULL) {
2734 Py_DECREF(v);
2735 *prem = NULL;
2736 return NULL;
2737 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2740 shift v1 left by the same amount. Results go into w and v. */
2741 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2742 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2743 assert(carry == 0);
2744 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2745 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2746 v->ob_digit[size_v] = carry;
2747 size_v++;
2748 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2751 at most (and usually exactly) k = size_v - size_w digits. */
2752 k = size_v - size_w;
2753 assert(k >= 0);
2754 a = _PyLong_New(k);
2755 if (a == NULL) {
2756 Py_DECREF(w);
2757 Py_DECREF(v);
2758 *prem = NULL;
2759 return NULL;
2760 }
2761 v0 = v->ob_digit;
2762 w0 = w->ob_digit;
2763 wm1 = w0[size_w-1];
2764 wm2 = w0[size_w-2];
2765 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2766 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2767 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002770 Py_DECREF(a);
2771 Py_DECREF(w);
2772 Py_DECREF(v);
2773 *prem = NULL;
2774 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002775 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 /* estimate quotient digit q; may overestimate by 1 (rare) */
2778 vtop = vk[size_w];
2779 assert(vtop <= wm1);
2780 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2781 q = (digit)(vv / wm1);
2782 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2783 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2784 | vk[size_w-2])) {
2785 --q;
2786 r += wm1;
2787 if (r >= PyLong_BASE)
2788 break;
2789 }
2790 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2793 zhi = 0;
2794 for (i = 0; i < size_w; ++i) {
2795 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2796 -PyLong_BASE * q <= z < PyLong_BASE */
2797 z = (sdigit)vk[i] + zhi -
2798 (stwodigits)q * (stwodigits)w0[i];
2799 vk[i] = (digit)z & PyLong_MASK;
2800 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002801 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 /* add w back if q was too large (this branch taken rarely) */
2805 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2806 if ((sdigit)vtop + zhi < 0) {
2807 carry = 0;
2808 for (i = 0; i < size_w; ++i) {
2809 carry += vk[i] + w0[i];
2810 vk[i] = carry & PyLong_MASK;
2811 carry >>= PyLong_SHIFT;
2812 }
2813 --q;
2814 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 /* store quotient digit */
2817 assert(q < PyLong_BASE);
2818 *--ak = q;
2819 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 /* unshift remainder; we reuse w to store the result */
2822 carry = v_rshift(w0, v0, size_w, d);
2823 assert(carry==0);
2824 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 *prem = long_normalize(w);
2827 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002828}
2829
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002830/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2831 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2832 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2833 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2834 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2835 -1.0. */
2836
2837/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2838#if DBL_MANT_DIG == 53
2839#define EXP2_DBL_MANT_DIG 9007199254740992.0
2840#else
2841#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2842#endif
2843
2844double
2845_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2848 /* See below for why x_digits is always large enough. */
2849 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2850 double dx;
2851 /* Correction term for round-half-to-even rounding. For a digit x,
2852 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2853 multiple of 4, rounding ties to a multiple of 8. */
2854 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002855
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002856 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 if (a_size == 0) {
2858 /* Special case for 0: significand 0.0, exponent 0. */
2859 *e = 0;
2860 return 0.0;
2861 }
2862 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2863 /* The following is an overflow-free version of the check
2864 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2865 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2866 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2867 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002868 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2872 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 Number of digits needed for result: write // for floor division.
2875 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2884 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2887 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2888 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 in both cases.
2895 */
2896 if (a_bits <= DBL_MANT_DIG + 2) {
2897 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2898 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2899 x_size = 0;
2900 while (x_size < shift_digits)
2901 x_digits[x_size++] = 0;
2902 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2903 (int)shift_bits);
2904 x_size += a_size;
2905 x_digits[x_size++] = rem;
2906 }
2907 else {
2908 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2909 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2910 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2911 a_size - shift_digits, (int)shift_bits);
2912 x_size = a_size - shift_digits;
2913 /* For correct rounding below, we need the least significant
2914 bit of x to be 'sticky' for this shift: if any of the bits
2915 shifted out was nonzero, we set the least significant bit
2916 of x. */
2917 if (rem)
2918 x_digits[0] |= 1;
2919 else
2920 while (shift_digits > 0)
2921 if (a->ob_digit[--shift_digits]) {
2922 x_digits[0] |= 1;
2923 break;
2924 }
2925 }
Victor Stinner63941882011-09-29 00:42:28 +02002926 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 /* Round, and convert to double. */
2929 x_digits[0] += half_even_correction[x_digits[0] & 7];
2930 dx = x_digits[--x_size];
2931 while (x_size > 0)
2932 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 /* Rescale; make correction if result is 1.0. */
2935 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2936 if (dx == 1.0) {
2937 if (a_bits == PY_SSIZE_T_MAX)
2938 goto overflow;
2939 dx = 0.5;
2940 a_bits += 1;
2941 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 *e = a_bits;
2944 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002945
2946 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 /* exponent > PY_SSIZE_T_MAX */
2948 PyErr_SetString(PyExc_OverflowError,
2949 "huge integer: number of bits overflows a Py_ssize_t");
2950 *e = 0;
2951 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002952}
2953
Serhiy Storchaka95949422013-08-27 19:40:23 +03002954/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002955 using the round-half-to-even rule in the case of a tie. */
2956
2957double
2958PyLong_AsDouble(PyObject *v)
2959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 Py_ssize_t exponent;
2961 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002962
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002963 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 PyErr_BadInternalCall();
2965 return -1.0;
2966 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002967 if (!PyLong_Check(v)) {
2968 PyErr_SetString(PyExc_TypeError, "an integer is required");
2969 return -1.0;
2970 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002971 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002972 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002973 to double. This improves performance of FP/long operations
2974 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002975 */
2976 return (double)MEDIUM_VALUE((PyLongObject *)v);
2977 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2979 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2980 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002981 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 return -1.0;
2983 }
2984 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002985}
2986
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002987/* Methods */
2988
2989static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002990long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002993}
2994
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002995static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002996long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 if (Py_SIZE(a) != Py_SIZE(b)) {
3001 sign = Py_SIZE(a) - Py_SIZE(b);
3002 }
3003 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003004 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3006 ;
3007 if (i < 0)
3008 sign = 0;
3009 else {
3010 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
3011 if (Py_SIZE(a) < 0)
3012 sign = -sign;
3013 }
3014 }
3015 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003016}
3017
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003018static PyObject *
3019long_richcompare(PyObject *self, PyObject *other, int op)
3020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 CHECK_BINOP(self, other);
3023 if (self == other)
3024 result = 0;
3025 else
3026 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003027 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003028}
3029
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003030static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003031long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003032{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003033 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 Py_ssize_t i;
3035 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 i = Py_SIZE(v);
3038 switch(i) {
3039 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3040 case 0: return 0;
3041 case 1: return v->ob_digit[0];
3042 }
3043 sign = 1;
3044 x = 0;
3045 if (i < 0) {
3046 sign = -1;
3047 i = -(i);
3048 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003050 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3051 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3052 _PyHASH_MODULUS.
3053
3054 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3055 amounts to a rotation of the bits of x. To see this, write
3056
3057 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3058
3059 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3060 PyLong_SHIFT bits of x (those that are shifted out of the
3061 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3062 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3063 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3064 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3065 congruent to y modulo _PyHASH_MODULUS. So
3066
3067 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3068
3069 The right-hand side is just the result of rotating the
3070 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3071 not all _PyHASH_BITS bits of x are 1s, the same is true
3072 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3073 the reduction of x*2**PyLong_SHIFT modulo
3074 _PyHASH_MODULUS. */
3075 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3076 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003078 if (x >= _PyHASH_MODULUS)
3079 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 }
3081 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003082 if (x == (Py_uhash_t)-1)
3083 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003084 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003085}
3086
3087
Serhiy Storchaka95949422013-08-27 19:40:23 +03003088/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003089
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003090static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003091x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003092{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003093 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 PyLongObject *z;
3095 Py_ssize_t i;
3096 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 /* Ensure a is the larger of the two: */
3099 if (size_a < size_b) {
3100 { PyLongObject *temp = a; a = b; b = temp; }
3101 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003102 size_a = size_b;
3103 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 }
3105 z = _PyLong_New(size_a+1);
3106 if (z == NULL)
3107 return NULL;
3108 for (i = 0; i < size_b; ++i) {
3109 carry += a->ob_digit[i] + b->ob_digit[i];
3110 z->ob_digit[i] = carry & PyLong_MASK;
3111 carry >>= PyLong_SHIFT;
3112 }
3113 for (; i < size_a; ++i) {
3114 carry += a->ob_digit[i];
3115 z->ob_digit[i] = carry & PyLong_MASK;
3116 carry >>= PyLong_SHIFT;
3117 }
3118 z->ob_digit[i] = carry;
3119 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003120}
3121
3122/* Subtract the absolute values of two integers. */
3123
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003124static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003125x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003126{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003127 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 PyLongObject *z;
3129 Py_ssize_t i;
3130 int sign = 1;
3131 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 /* Ensure a is the larger of the two: */
3134 if (size_a < size_b) {
3135 sign = -1;
3136 { PyLongObject *temp = a; a = b; b = temp; }
3137 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003138 size_a = size_b;
3139 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 }
3141 else if (size_a == size_b) {
3142 /* Find highest digit where a and b differ: */
3143 i = size_a;
3144 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3145 ;
3146 if (i < 0)
3147 return (PyLongObject *)PyLong_FromLong(0);
3148 if (a->ob_digit[i] < b->ob_digit[i]) {
3149 sign = -1;
3150 { PyLongObject *temp = a; a = b; b = temp; }
3151 }
3152 size_a = size_b = i+1;
3153 }
3154 z = _PyLong_New(size_a);
3155 if (z == NULL)
3156 return NULL;
3157 for (i = 0; i < size_b; ++i) {
3158 /* The following assumes unsigned arithmetic
3159 works module 2**N for some N>PyLong_SHIFT. */
3160 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3161 z->ob_digit[i] = borrow & PyLong_MASK;
3162 borrow >>= PyLong_SHIFT;
3163 borrow &= 1; /* Keep only one sign bit */
3164 }
3165 for (; i < size_a; ++i) {
3166 borrow = a->ob_digit[i] - borrow;
3167 z->ob_digit[i] = borrow & PyLong_MASK;
3168 borrow >>= PyLong_SHIFT;
3169 borrow &= 1; /* Keep only one sign bit */
3170 }
3171 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003172 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003173 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003176}
3177
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003178static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003179long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003184
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003185 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003186 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 }
3188 if (Py_SIZE(a) < 0) {
3189 if (Py_SIZE(b) < 0) {
3190 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003191 if (z != NULL) {
3192 /* x_add received at least one multiple-digit int,
3193 and thus z must be a multiple-digit int.
3194 That also means z is not an element of
3195 small_ints, so negating it in-place is safe. */
3196 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003198 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 }
3200 else
3201 z = x_sub(b, a);
3202 }
3203 else {
3204 if (Py_SIZE(b) < 0)
3205 z = x_sub(a, b);
3206 else
3207 z = x_add(a, b);
3208 }
3209 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003210}
3211
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003212static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003213long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003218
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003219 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003220 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 }
3222 if (Py_SIZE(a) < 0) {
3223 if (Py_SIZE(b) < 0)
3224 z = x_sub(a, b);
3225 else
3226 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003227 if (z != NULL) {
3228 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003230 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 }
3232 else {
3233 if (Py_SIZE(b) < 0)
3234 z = x_add(a, b);
3235 else
3236 z = x_sub(a, b);
3237 }
3238 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003239}
3240
Tim Peters5af4e6c2002-08-12 02:31:19 +00003241/* Grade school multiplication, ignoring the signs.
3242 * Returns the absolute value of the product, or NULL if error.
3243 */
3244static PyLongObject *
3245x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003248 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3249 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 z = _PyLong_New(size_a + size_b);
3253 if (z == NULL)
3254 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3257 if (a == b) {
3258 /* Efficient squaring per HAC, Algorithm 14.16:
3259 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3260 * Gives slightly less than a 2x speedup when a == b,
3261 * via exploiting that each entry in the multiplication
3262 * pyramid appears twice (except for the size_a squares).
3263 */
3264 for (i = 0; i < size_a; ++i) {
3265 twodigits carry;
3266 twodigits f = a->ob_digit[i];
3267 digit *pz = z->ob_digit + (i << 1);
3268 digit *pa = a->ob_digit + i + 1;
3269 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003272 Py_DECREF(z);
3273 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003274 });
Tim Peters0973b992004-08-29 22:16:50 +00003275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 carry = *pz + f * f;
3277 *pz++ = (digit)(carry & PyLong_MASK);
3278 carry >>= PyLong_SHIFT;
3279 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 /* Now f is added in twice in each column of the
3282 * pyramid it appears. Same as adding f<<1 once.
3283 */
3284 f <<= 1;
3285 while (pa < paend) {
3286 carry += *pz + *pa++ * f;
3287 *pz++ = (digit)(carry & PyLong_MASK);
3288 carry >>= PyLong_SHIFT;
3289 assert(carry <= (PyLong_MASK << 1));
3290 }
3291 if (carry) {
3292 carry += *pz;
3293 *pz++ = (digit)(carry & PyLong_MASK);
3294 carry >>= PyLong_SHIFT;
3295 }
3296 if (carry)
3297 *pz += (digit)(carry & PyLong_MASK);
3298 assert((carry >> PyLong_SHIFT) == 0);
3299 }
3300 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003301 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 for (i = 0; i < size_a; ++i) {
3303 twodigits carry = 0;
3304 twodigits f = a->ob_digit[i];
3305 digit *pz = z->ob_digit + i;
3306 digit *pb = b->ob_digit;
3307 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003310 Py_DECREF(z);
3311 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003312 });
Tim Peters0973b992004-08-29 22:16:50 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 while (pb < pbend) {
3315 carry += *pz + *pb++ * f;
3316 *pz++ = (digit)(carry & PyLong_MASK);
3317 carry >>= PyLong_SHIFT;
3318 assert(carry <= PyLong_MASK);
3319 }
3320 if (carry)
3321 *pz += (digit)(carry & PyLong_MASK);
3322 assert((carry >> PyLong_SHIFT) == 0);
3323 }
3324 }
3325 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003326}
3327
3328/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003329 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003330 split, and sets low and high such that abs(n) == (high << size) + low,
3331 viewing the shift as being by digits. The sign bit is ignored, and
3332 the return values are >= 0.
3333 Returns 0 on success, -1 on failure.
3334*/
3335static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003336kmul_split(PyLongObject *n,
3337 Py_ssize_t size,
3338 PyLongObject **high,
3339 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 PyLongObject *hi, *lo;
3342 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003343 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003344
Victor Stinner640c35c2013-06-04 23:14:37 +02003345 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 if ((hi = _PyLong_New(size_hi)) == NULL)
3349 return -1;
3350 if ((lo = _PyLong_New(size_lo)) == NULL) {
3351 Py_DECREF(hi);
3352 return -1;
3353 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3356 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 *high = long_normalize(hi);
3359 *low = long_normalize(lo);
3360 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003361}
3362
Tim Peters60004642002-08-12 22:01:34 +00003363static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3364
Tim Peters5af4e6c2002-08-12 02:31:19 +00003365/* Karatsuba multiplication. Ignores the input signs, and returns the
3366 * absolute value of the product (or NULL if error).
3367 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3368 */
3369static PyLongObject *
3370k_mul(PyLongObject *a, PyLongObject *b)
3371{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003372 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3373 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 PyLongObject *ah = NULL;
3375 PyLongObject *al = NULL;
3376 PyLongObject *bh = NULL;
3377 PyLongObject *bl = NULL;
3378 PyLongObject *ret = NULL;
3379 PyLongObject *t1, *t2, *t3;
3380 Py_ssize_t shift; /* the number of digits we split off */
3381 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3384 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3385 * Then the original product is
3386 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3387 * By picking X to be a power of 2, "*X" is just shifting, and it's
3388 * been reduced to 3 multiplies on numbers half the size.
3389 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 /* We want to split based on the larger number; fiddle so that b
3392 * is largest.
3393 */
3394 if (asize > bsize) {
3395 t1 = a;
3396 a = b;
3397 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 i = asize;
3400 asize = bsize;
3401 bsize = i;
3402 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 /* Use gradeschool math when either number is too small. */
3405 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3406 if (asize <= i) {
3407 if (asize == 0)
3408 return (PyLongObject *)PyLong_FromLong(0);
3409 else
3410 return x_mul(a, b);
3411 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 /* If a is small compared to b, splitting on b gives a degenerate
3414 * case with ah==0, and Karatsuba may be (even much) less efficient
3415 * than "grade school" then. However, we can still win, by viewing
3416 * b as a string of "big digits", each of width a->ob_size. That
3417 * leads to a sequence of balanced calls to k_mul.
3418 */
3419 if (2 * asize <= bsize)
3420 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 /* Split a & b into hi & lo pieces. */
3423 shift = bsize >> 1;
3424 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3425 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 if (a == b) {
3428 bh = ah;
3429 bl = al;
3430 Py_INCREF(bh);
3431 Py_INCREF(bl);
3432 }
3433 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 /* The plan:
3436 * 1. Allocate result space (asize + bsize digits: that's always
3437 * enough).
3438 * 2. Compute ah*bh, and copy into result at 2*shift.
3439 * 3. Compute al*bl, and copy into result at 0. Note that this
3440 * can't overlap with #2.
3441 * 4. Subtract al*bl from the result, starting at shift. This may
3442 * underflow (borrow out of the high digit), but we don't care:
3443 * we're effectively doing unsigned arithmetic mod
3444 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3445 * borrows and carries out of the high digit can be ignored.
3446 * 5. Subtract ah*bh from the result, starting at shift.
3447 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3448 * at shift.
3449 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 /* 1. Allocate result space. */
3452 ret = _PyLong_New(asize + bsize);
3453 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003454#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 /* Fill with trash, to catch reference to uninitialized digits. */
3456 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003457#endif
Tim Peters44121a62002-08-12 06:17:58 +00003458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3460 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3461 assert(Py_SIZE(t1) >= 0);
3462 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3463 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3464 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 /* Zero-out the digits higher than the ah*bh copy. */
3467 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3468 if (i)
3469 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3470 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 /* 3. t2 <- al*bl, and copy into the low digits. */
3473 if ((t2 = k_mul(al, bl)) == NULL) {
3474 Py_DECREF(t1);
3475 goto fail;
3476 }
3477 assert(Py_SIZE(t2) >= 0);
3478 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3479 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 /* Zero out remaining digits. */
3482 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3483 if (i)
3484 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3487 * because it's fresher in cache.
3488 */
3489 i = Py_SIZE(ret) - shift; /* # digits after shift */
3490 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3491 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3494 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3497 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3498 Py_DECREF(ah);
3499 Py_DECREF(al);
3500 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 if (a == b) {
3503 t2 = t1;
3504 Py_INCREF(t2);
3505 }
3506 else if ((t2 = x_add(bh, bl)) == NULL) {
3507 Py_DECREF(t1);
3508 goto fail;
3509 }
3510 Py_DECREF(bh);
3511 Py_DECREF(bl);
3512 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 t3 = k_mul(t1, t2);
3515 Py_DECREF(t1);
3516 Py_DECREF(t2);
3517 if (t3 == NULL) goto fail;
3518 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 /* Add t3. It's not obvious why we can't run out of room here.
3521 * See the (*) comment after this function.
3522 */
3523 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3524 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003527
Mark Dickinson22b20182010-05-10 21:27:53 +00003528 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 Py_XDECREF(ret);
3530 Py_XDECREF(ah);
3531 Py_XDECREF(al);
3532 Py_XDECREF(bh);
3533 Py_XDECREF(bl);
3534 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003535}
3536
Tim Petersd6974a52002-08-13 20:37:51 +00003537/* (*) Why adding t3 can't "run out of room" above.
3538
Tim Petersab86c2b2002-08-15 20:06:00 +00003539Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3540to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003541
Tim Petersab86c2b2002-08-15 20:06:00 +000035421. For any integer i, i = c(i/2) + f(i/2). In particular,
3543 bsize = c(bsize/2) + f(bsize/2).
35442. shift = f(bsize/2)
35453. asize <= bsize
35464. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3547 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003548
Tim Petersab86c2b2002-08-15 20:06:00 +00003549We allocated asize + bsize result digits, and add t3 into them at an offset
3550of shift. This leaves asize+bsize-shift allocated digit positions for t3
3551to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3552asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003553
Tim Petersab86c2b2002-08-15 20:06:00 +00003554bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3555at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003556
Tim Petersab86c2b2002-08-15 20:06:00 +00003557If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3558digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3559most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003560
Tim Petersab86c2b2002-08-15 20:06:00 +00003561The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003562
Tim Petersab86c2b2002-08-15 20:06:00 +00003563 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003564
Tim Petersab86c2b2002-08-15 20:06:00 +00003565and we have asize + c(bsize/2) available digit positions. We need to show
3566this is always enough. An instance of c(bsize/2) cancels out in both, so
3567the question reduces to whether asize digits is enough to hold
3568(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3569then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3570asize 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 +00003571digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003572asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003573c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3574is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3575bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003576
Tim Peters48d52c02002-08-14 17:07:32 +00003577Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3578clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3579ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003580*/
3581
Tim Peters60004642002-08-12 22:01:34 +00003582/* b has at least twice the digits of a, and a is big enough that Karatsuba
3583 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3584 * of slices, each with a->ob_size digits, and multiply the slices by a,
3585 * one at a time. This gives k_mul balanced inputs to work with, and is
3586 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003587 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003588 * single-width slice overlap between successive partial sums).
3589 */
3590static PyLongObject *
3591k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3592{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003593 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3594 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 Py_ssize_t nbdone; /* # of b digits already multiplied */
3596 PyLongObject *ret;
3597 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 assert(asize > KARATSUBA_CUTOFF);
3600 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 /* Allocate result space, and zero it out. */
3603 ret = _PyLong_New(asize + bsize);
3604 if (ret == NULL)
3605 return NULL;
3606 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 /* Successive slices of b are copied into bslice. */
3609 bslice = _PyLong_New(asize);
3610 if (bslice == NULL)
3611 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 nbdone = 0;
3614 while (bsize > 0) {
3615 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003616 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 /* Multiply the next slice of b by a. */
3619 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3620 nbtouse * sizeof(digit));
3621 Py_SIZE(bslice) = nbtouse;
3622 product = k_mul(a, bslice);
3623 if (product == NULL)
3624 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 /* Add into result. */
3627 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3628 product->ob_digit, Py_SIZE(product));
3629 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 bsize -= nbtouse;
3632 nbdone += nbtouse;
3633 }
Tim Peters60004642002-08-12 22:01:34 +00003634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 Py_DECREF(bslice);
3636 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003637
Mark Dickinson22b20182010-05-10 21:27:53 +00003638 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 Py_DECREF(ret);
3640 Py_XDECREF(bslice);
3641 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003642}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003643
3644static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003645long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003652 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003654 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 z = k_mul(a, b);
3658 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003659 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3660 _PyLong_Negate(&z);
3661 if (z == NULL)
3662 return NULL;
3663 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003665}
3666
Yury Selivanove0b23092016-02-11 10:26:27 -05003667/* Fast modulo division for single-digit longs. */
3668static PyObject *
3669fast_mod(PyLongObject *a, PyLongObject *b)
3670{
3671 sdigit left = a->ob_digit[0];
3672 sdigit right = b->ob_digit[0];
3673 sdigit mod;
3674
3675 assert(Py_ABS(Py_SIZE(a)) == 1);
3676 assert(Py_ABS(Py_SIZE(b)) == 1);
3677
3678 if (Py_SIZE(a) == Py_SIZE(b)) {
3679 /* 'a' and 'b' have the same sign. */
3680 mod = left % right;
3681 }
3682 else {
3683 /* Either 'a' or 'b' is negative. */
3684 mod = right - 1 - (left - 1) % right;
3685 }
3686
Victor Stinnerf963c132016-03-23 18:36:54 +01003687 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003688}
3689
3690/* Fast floor division for single-digit longs. */
3691static PyObject *
3692fast_floor_div(PyLongObject *a, PyLongObject *b)
3693{
3694 sdigit left = a->ob_digit[0];
3695 sdigit right = b->ob_digit[0];
3696 sdigit div;
3697
3698 assert(Py_ABS(Py_SIZE(a)) == 1);
3699 assert(Py_ABS(Py_SIZE(b)) == 1);
3700
3701 if (Py_SIZE(a) == Py_SIZE(b)) {
3702 /* 'a' and 'b' have the same sign. */
3703 div = left / right;
3704 }
3705 else {
3706 /* Either 'a' or 'b' is negative. */
3707 div = -1 - (left - 1) / right;
3708 }
3709
3710 return PyLong_FromLong(div);
3711}
3712
Guido van Rossume32e0141992-01-19 16:31:05 +00003713/* The / and % operators are now defined in terms of divmod().
3714 The expression a mod b has the value a - b*floor(a/b).
3715 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003716 |a| by |b|, with the sign of a. This is also expressed
3717 as a - b*trunc(a/b), if trunc truncates towards zero.
3718 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 a b a rem b a mod b
3720 13 10 3 3
3721 -13 10 -3 7
3722 13 -10 3 -7
3723 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003724 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003725 have different signs. We then subtract one from the 'div'
3726 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003727
Tim Peters47e52ee2004-08-30 02:44:38 +00003728/* Compute
3729 * *pdiv, *pmod = divmod(v, w)
3730 * NULL can be passed for pdiv or pmod, in which case that part of
3731 * the result is simply thrown away. The caller owns a reference to
3732 * each of these it requests (does not pass NULL for).
3733 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003734static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003735l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003739
Yury Selivanove0b23092016-02-11 10:26:27 -05003740 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3741 /* Fast path for single-digit longs */
3742 div = NULL;
3743 if (pdiv != NULL) {
3744 div = (PyLongObject *)fast_floor_div(v, w);
3745 if (div == NULL) {
3746 return -1;
3747 }
3748 }
3749 if (pmod != NULL) {
3750 mod = (PyLongObject *)fast_mod(v, w);
3751 if (mod == NULL) {
3752 Py_XDECREF(div);
3753 return -1;
3754 }
3755 *pmod = mod;
3756 }
3757 if (pdiv != NULL) {
3758 /* We only want to set `*pdiv` when `*pmod` is
3759 set successfully. */
3760 *pdiv = div;
3761 }
3762 return 0;
3763 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 if (long_divrem(v, w, &div, &mod) < 0)
3765 return -1;
3766 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3767 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3768 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 temp = (PyLongObject *) long_add(mod, w);
3770 Py_DECREF(mod);
3771 mod = temp;
3772 if (mod == NULL) {
3773 Py_DECREF(div);
3774 return -1;
3775 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003776 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3777 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 Py_DECREF(mod);
3779 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 return -1;
3781 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 Py_DECREF(div);
3783 div = temp;
3784 }
3785 if (pdiv != NULL)
3786 *pdiv = div;
3787 else
3788 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 if (pmod != NULL)
3791 *pmod = mod;
3792 else
3793 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003796}
3797
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003798static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003799long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003804
3805 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3806 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3807 }
3808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3810 div = NULL;
3811 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003812}
3813
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003814/* PyLong/PyLong -> float, with correctly rounded result. */
3815
3816#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3817#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3818
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003819static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003820long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 PyLongObject *a, *b, *x;
3823 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3824 digit mask, low;
3825 int inexact, negate, a_is_small, b_is_small;
3826 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 CHECK_BINOP(v, w);
3829 a = (PyLongObject *)v;
3830 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 /*
3833 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3836 1. choose a suitable integer 'shift'
3837 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3838 3. adjust x for correct rounding
3839 4. convert x to a double dx with the same value
3840 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3845 returns either 0.0 or -0.0, depending on the sign of b. For a and
3846 b both nonzero, ignore signs of a and b, and add the sign back in
3847 at the end. Now write a_bits and b_bits for the bit lengths of a
3848 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3849 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3854 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3855 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3856 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 1. The integer 'shift' is chosen so that x has the right number of
3861 bits for a double, plus two or three extra bits that will be used
3862 in the rounding decisions. Writing a_bits and b_bits for the
3863 number of significant bits in a and b respectively, a
3864 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 This is fine in the usual case, but if a/b is smaller than the
3869 smallest normal float then it can lead to double rounding on an
3870 IEEE 754 platform, giving incorrectly rounded results. So we
3871 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 2. The quantity x is computed by first shifting a (left -shift bits
3876 if shift <= 0, right shift bits if shift > 0) and then dividing by
3877 b. For both the shift and the division, we keep track of whether
3878 the result is inexact, in a flag 'inexact'; this information is
3879 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 With the choice of shift above, together with our assumption that
3882 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3883 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3886 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 For float representability, we need x/2**extra_bits <
3891 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3892 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 To round, we just modify the bottom digit of x in-place; this can
3897 end up giving a digit with value > PyLONG_MASK, but that's not a
3898 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 With the original choices for shift above, extra_bits will always
3901 be 2 or 3. Then rounding under the round-half-to-even rule, we
3902 round up iff the most significant of the extra bits is 1, and
3903 either: (a) the computation of x in step 2 had an inexact result,
3904 or (b) at least one other of the extra bits is 1, or (c) the least
3905 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 4. Conversion to a double is straightforward; all floating-point
3908 operations involved in the conversion are exact, so there's no
3909 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3912 The result will always be exactly representable as a double, except
3913 in the case that it overflows. To avoid dependence on the exact
3914 behaviour of ldexp on overflow, we check for overflow before
3915 applying ldexp. The result of ldexp is adjusted for sign before
3916 returning.
3917 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003920 a_size = Py_ABS(Py_SIZE(a));
3921 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3923 if (b_size == 0) {
3924 PyErr_SetString(PyExc_ZeroDivisionError,
3925 "division by zero");
3926 goto error;
3927 }
3928 if (a_size == 0)
3929 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 /* Fast path for a and b small (exactly representable in a double).
3932 Relies on floating-point division being correctly rounded; results
3933 may be subject to double rounding on x86 machines that operate with
3934 the x87 FPU set to 64-bit precision. */
3935 a_is_small = a_size <= MANT_DIG_DIGITS ||
3936 (a_size == MANT_DIG_DIGITS+1 &&
3937 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3938 b_is_small = b_size <= MANT_DIG_DIGITS ||
3939 (b_size == MANT_DIG_DIGITS+1 &&
3940 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3941 if (a_is_small && b_is_small) {
3942 double da, db;
3943 da = a->ob_digit[--a_size];
3944 while (a_size > 0)
3945 da = da * PyLong_BASE + a->ob_digit[--a_size];
3946 db = b->ob_digit[--b_size];
3947 while (b_size > 0)
3948 db = db * PyLong_BASE + b->ob_digit[--b_size];
3949 result = da / db;
3950 goto success;
3951 }
Tim Peterse2a60002001-09-04 06:17:36 +00003952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 /* Catch obvious cases of underflow and overflow */
3954 diff = a_size - b_size;
3955 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3956 /* Extreme overflow */
3957 goto overflow;
3958 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3959 /* Extreme underflow */
3960 goto underflow_or_zero;
3961 /* Next line is now safe from overflowing a Py_ssize_t */
3962 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3963 bits_in_digit(b->ob_digit[b_size - 1]);
3964 /* Now diff = a_bits - b_bits. */
3965 if (diff > DBL_MAX_EXP)
3966 goto overflow;
3967 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3968 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003971 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 /* x = abs(a * 2**-shift) */
3976 if (shift <= 0) {
3977 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3978 digit rem;
3979 /* x = a << -shift */
3980 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3981 /* In practice, it's probably impossible to end up
3982 here. Both a and b would have to be enormous,
3983 using close to SIZE_T_MAX bytes of memory each. */
3984 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003985 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 goto error;
3987 }
3988 x = _PyLong_New(a_size + shift_digits + 1);
3989 if (x == NULL)
3990 goto error;
3991 for (i = 0; i < shift_digits; i++)
3992 x->ob_digit[i] = 0;
3993 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3994 a_size, -shift % PyLong_SHIFT);
3995 x->ob_digit[a_size + shift_digits] = rem;
3996 }
3997 else {
3998 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3999 digit rem;
4000 /* x = a >> shift */
4001 assert(a_size >= shift_digits);
4002 x = _PyLong_New(a_size - shift_digits);
4003 if (x == NULL)
4004 goto error;
4005 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4006 a_size - shift_digits, shift % PyLong_SHIFT);
4007 /* set inexact if any of the bits shifted out is nonzero */
4008 if (rem)
4009 inexact = 1;
4010 while (!inexact && shift_digits > 0)
4011 if (a->ob_digit[--shift_digits])
4012 inexact = 1;
4013 }
4014 long_normalize(x);
4015 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4018 reference to x, so it's safe to modify it in-place. */
4019 if (b_size == 1) {
4020 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4021 b->ob_digit[0]);
4022 long_normalize(x);
4023 if (rem)
4024 inexact = 1;
4025 }
4026 else {
4027 PyLongObject *div, *rem;
4028 div = x_divrem(x, b, &rem);
4029 Py_DECREF(x);
4030 x = div;
4031 if (x == NULL)
4032 goto error;
4033 if (Py_SIZE(rem))
4034 inexact = 1;
4035 Py_DECREF(rem);
4036 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004037 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 assert(x_size > 0); /* result of division is never zero */
4039 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004042 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 /* Round by directly modifying the low digit of x. */
4046 mask = (digit)1 << (extra_bits - 1);
4047 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004048 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004050 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 /* Convert x to a double dx; the conversion is exact. */
4053 dx = x->ob_digit[--x_size];
4054 while (x_size > 0)
4055 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4056 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 /* Check whether ldexp result will overflow a double. */
4059 if (shift + x_bits >= DBL_MAX_EXP &&
4060 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4061 goto overflow;
4062 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004063
4064 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004066
4067 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004069
4070 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 PyErr_SetString(PyExc_OverflowError,
4072 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004073 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004075}
4076
4077static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004078long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 CHECK_BINOP(a, b);
4083
Yury Selivanove0b23092016-02-11 10:26:27 -05004084 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4085 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4086 }
4087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4089 mod = NULL;
4090 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004091}
4092
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004093static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004094long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 PyLongObject *div, *mod;
4097 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4102 return NULL;
4103 }
4104 z = PyTuple_New(2);
4105 if (z != NULL) {
4106 PyTuple_SetItem(z, 0, (PyObject *) div);
4107 PyTuple_SetItem(z, 1, (PyObject *) mod);
4108 }
4109 else {
4110 Py_DECREF(div);
4111 Py_DECREF(mod);
4112 }
4113 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004114}
4115
Tim Peters47e52ee2004-08-30 02:44:38 +00004116/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004117static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004118long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4121 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 PyLongObject *z = NULL; /* accumulated result */
4124 Py_ssize_t i, j, k; /* counters */
4125 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 /* 5-ary values. If the exponent is large enough, table is
4128 * precomputed so that table[i] == a**i % c for i in range(32).
4129 */
4130 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4131 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 /* a, b, c = v, w, x */
4134 CHECK_BINOP(v, w);
4135 a = (PyLongObject*)v; Py_INCREF(a);
4136 b = (PyLongObject*)w; Py_INCREF(b);
4137 if (PyLong_Check(x)) {
4138 c = (PyLongObject *)x;
4139 Py_INCREF(x);
4140 }
4141 else if (x == Py_None)
4142 c = NULL;
4143 else {
4144 Py_DECREF(a);
4145 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004146 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 }
Tim Peters4c483c42001-09-05 06:24:58 +00004148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 if (Py_SIZE(b) < 0) { /* if exponent is negative */
4150 if (c) {
Mark Dickinson0c346d82014-04-11 14:34:40 -04004151 PyErr_SetString(PyExc_ValueError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00004152 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 goto Error;
4154 }
4155 else {
4156 /* else return a float. This works because we know
4157 that this calls float_pow() which converts its
4158 arguments to double. */
4159 Py_DECREF(a);
4160 Py_DECREF(b);
4161 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
4162 }
4163 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 if (c) {
4166 /* if modulus == 0:
4167 raise ValueError() */
4168 if (Py_SIZE(c) == 0) {
4169 PyErr_SetString(PyExc_ValueError,
4170 "pow() 3rd argument cannot be 0");
4171 goto Error;
4172 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 /* if modulus < 0:
4175 negativeOutput = True
4176 modulus = -modulus */
4177 if (Py_SIZE(c) < 0) {
4178 negativeOutput = 1;
4179 temp = (PyLongObject *)_PyLong_Copy(c);
4180 if (temp == NULL)
4181 goto Error;
4182 Py_DECREF(c);
4183 c = temp;
4184 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004185 _PyLong_Negate(&c);
4186 if (c == NULL)
4187 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 /* if modulus == 1:
4191 return 0 */
4192 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4193 z = (PyLongObject *)PyLong_FromLong(0L);
4194 goto Done;
4195 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004196
Tim Peters81a93152013-10-05 16:53:52 -05004197 /* Reduce base by modulus in some cases:
4198 1. If base < 0. Forcing the base non-negative makes things easier.
4199 2. If base is obviously larger than the modulus. The "small
4200 exponent" case later can multiply directly by base repeatedly,
4201 while the "large exponent" case multiplies directly by base 31
4202 times. It can be unboundedly faster to multiply by
4203 base % modulus instead.
4204 We could _always_ do this reduction, but l_divmod() isn't cheap,
4205 so we only do it when it buys something. */
4206 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 if (l_divmod(a, c, NULL, &temp) < 0)
4208 goto Error;
4209 Py_DECREF(a);
4210 a = temp;
4211 temp = NULL;
4212 }
4213 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 /* At this point a, b, and c are guaranteed non-negative UNLESS
4216 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 z = (PyLongObject *)PyLong_FromLong(1L);
4219 if (z == NULL)
4220 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 /* Perform a modular reduction, X = X % c, but leave X alone if c
4223 * is NULL.
4224 */
4225#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004226 do { \
4227 if (c != NULL) { \
4228 if (l_divmod(X, c, NULL, &temp) < 0) \
4229 goto Error; \
4230 Py_XDECREF(X); \
4231 X = temp; \
4232 temp = NULL; \
4233 } \
4234 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 /* Multiply two values, then reduce the result:
4237 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004238#define MULT(X, Y, result) \
4239 do { \
4240 temp = (PyLongObject *)long_mul(X, Y); \
4241 if (temp == NULL) \
4242 goto Error; \
4243 Py_XDECREF(result); \
4244 result = temp; \
4245 temp = NULL; \
4246 REDUCE(result); \
4247 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4250 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4251 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4252 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4253 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004256 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004258 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 }
4260 }
4261 }
4262 else {
4263 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4264 Py_INCREF(z); /* still holds 1L */
4265 table[0] = z;
4266 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004267 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4270 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4273 const int index = (bi >> j) & 0x1f;
4274 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004275 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004277 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 }
4279 }
4280 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 if (negativeOutput && (Py_SIZE(z) != 0)) {
4283 temp = (PyLongObject *)long_sub(z, c);
4284 if (temp == NULL)
4285 goto Error;
4286 Py_DECREF(z);
4287 z = temp;
4288 temp = NULL;
4289 }
4290 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004291
Mark Dickinson22b20182010-05-10 21:27:53 +00004292 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004293 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004295 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4297 for (i = 0; i < 32; ++i)
4298 Py_XDECREF(table[i]);
4299 }
4300 Py_DECREF(a);
4301 Py_DECREF(b);
4302 Py_XDECREF(c);
4303 Py_XDECREF(temp);
4304 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004305}
4306
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004307static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004308long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 /* Implement ~x as -(x+1) */
4311 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004312 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004314 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 if (x == NULL)
4316 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004317 _PyLong_Negate(&x);
4318 /* No need for maybe_small_long here, since any small
4319 longs will have been caught in the Py_SIZE <= 1 fast path. */
4320 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004321}
4322
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004323static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004324long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004327 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 return PyLong_FromLong(-MEDIUM_VALUE(v));
4329 z = (PyLongObject *)_PyLong_Copy(v);
4330 if (z != NULL)
4331 Py_SIZE(z) = -(Py_SIZE(v));
4332 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004333}
4334
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004335static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004336long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 if (Py_SIZE(v) < 0)
4339 return long_neg(v);
4340 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004341 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004342}
4343
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004344static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004345long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004348}
4349
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004350/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4351static int
4352divmod_shift(PyLongObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
4353{
4354 assert(PyLong_Check((PyObject *)shiftby));
4355 assert(Py_SIZE(shiftby) >= 0);
4356 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4357 if (lshiftby >= 0) {
4358 *wordshift = lshiftby / PyLong_SHIFT;
4359 *remshift = lshiftby % PyLong_SHIFT;
4360 return 0;
4361 }
4362 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4363 be that PyLong_AsSsize_t raised an OverflowError. */
4364 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4365 PyErr_Clear();
4366 PyLongObject *wordshift_obj = divrem1(shiftby, PyLong_SHIFT, remshift);
4367 if (wordshift_obj == NULL) {
4368 return -1;
4369 }
4370 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4371 Py_DECREF(wordshift_obj);
4372 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4373 return 0;
4374 }
4375 PyErr_Clear();
4376 /* Clip the value. With such large wordshift the right shift
4377 returns 0 and the left shift raises an error in _PyLong_New(). */
4378 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4379 *remshift = 0;
4380 return 0;
4381}
4382
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004383static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004384long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 PyLongObject *z = NULL;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004387 Py_ssize_t newsize, wordshift, hishift, i, j;
4388 digit loshift, lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004391
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004392 if (Py_SIZE(b) < 0) {
4393 PyErr_SetString(PyExc_ValueError,
4394 "negative shift count");
4395 return NULL;
4396 }
4397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 if (Py_SIZE(a) < 0) {
4399 /* Right shifting negative numbers is harder */
4400 PyLongObject *a1, *a2;
4401 a1 = (PyLongObject *) long_invert(a);
4402 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004403 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 a2 = (PyLongObject *) long_rshift(a1, b);
4405 Py_DECREF(a1);
4406 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004407 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 z = (PyLongObject *) long_invert(a2);
4409 Py_DECREF(a2);
4410 }
4411 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004412 if (divmod_shift(b, &wordshift, &loshift) < 0)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004413 return NULL;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004414 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 if (newsize <= 0)
4416 return PyLong_FromLong(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 hishift = PyLong_SHIFT - loshift;
4418 lomask = ((digit)1 << hishift) - 1;
4419 himask = PyLong_MASK ^ lomask;
4420 z = _PyLong_New(newsize);
4421 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004422 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4424 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4425 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004426 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004428 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004430 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004431}
4432
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004433static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004434long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 /* This version due to Tim Peters */
4437 PyLongObject *a = (PyLongObject*)v;
4438 PyLongObject *b = (PyLongObject*)w;
4439 PyLongObject *z = NULL;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004440 Py_ssize_t oldsize, newsize, wordshift, i, j;
4441 digit remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004445
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004446 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004448 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004450 if (Py_SIZE(a) == 0) {
4451 return PyLong_FromLong(0);
4452 }
4453
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004454 if (divmod_shift(b, &wordshift, &remshift) < 0)
4455 return NULL;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004456 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 newsize = oldsize + wordshift;
4458 if (remshift)
4459 ++newsize;
4460 z = _PyLong_New(newsize);
4461 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004462 return NULL;
4463 if (Py_SIZE(a) < 0) {
4464 assert(Py_REFCNT(z) == 1);
4465 Py_SIZE(z) = -Py_SIZE(z);
4466 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 for (i = 0; i < wordshift; i++)
4468 z->ob_digit[i] = 0;
4469 accum = 0;
4470 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4471 accum |= (twodigits)a->ob_digit[j] << remshift;
4472 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4473 accum >>= PyLong_SHIFT;
4474 }
4475 if (remshift)
4476 z->ob_digit[newsize-1] = (digit)accum;
4477 else
4478 assert(!accum);
4479 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004481}
4482
Mark Dickinson27a87a22009-10-25 20:43:34 +00004483/* Compute two's complement of digit vector a[0:m], writing result to
4484 z[0:m]. The digit vector a need not be normalized, but should not
4485 be entirely zero. a and z may point to the same digit vector. */
4486
4487static void
4488v_complement(digit *z, digit *a, Py_ssize_t m)
4489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 Py_ssize_t i;
4491 digit carry = 1;
4492 for (i = 0; i < m; ++i) {
4493 carry += a[i] ^ PyLong_MASK;
4494 z[i] = carry & PyLong_MASK;
4495 carry >>= PyLong_SHIFT;
4496 }
4497 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004498}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004499
4500/* Bitwise and/xor/or operations */
4501
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004502static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004503long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004504 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004505 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 int nega, negb, negz;
4508 Py_ssize_t size_a, size_b, size_z, i;
4509 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 /* Bitwise operations for negative numbers operate as though
4512 on a two's complement representation. So convert arguments
4513 from sign-magnitude to two's complement, and convert the
4514 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004517 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 nega = Py_SIZE(a) < 0;
4519 if (nega) {
4520 z = _PyLong_New(size_a);
4521 if (z == NULL)
4522 return NULL;
4523 v_complement(z->ob_digit, a->ob_digit, size_a);
4524 a = z;
4525 }
4526 else
4527 /* Keep reference count consistent. */
4528 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004531 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 negb = Py_SIZE(b) < 0;
4533 if (negb) {
4534 z = _PyLong_New(size_b);
4535 if (z == NULL) {
4536 Py_DECREF(a);
4537 return NULL;
4538 }
4539 v_complement(z->ob_digit, b->ob_digit, size_b);
4540 b = z;
4541 }
4542 else
4543 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 /* Swap a and b if necessary to ensure size_a >= size_b. */
4546 if (size_a < size_b) {
4547 z = a; a = b; b = z;
4548 size_z = size_a; size_a = size_b; size_b = size_z;
4549 negz = nega; nega = negb; negb = negz;
4550 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 /* JRH: The original logic here was to allocate the result value (z)
4553 as the longer of the two operands. However, there are some cases
4554 where the result is guaranteed to be shorter than that: AND of two
4555 positives, OR of two negatives: use the shorter number. AND with
4556 mixed signs: use the positive number. OR with mixed signs: use the
4557 negative number.
4558 */
4559 switch (op) {
4560 case '^':
4561 negz = nega ^ negb;
4562 size_z = size_a;
4563 break;
4564 case '&':
4565 negz = nega & negb;
4566 size_z = negb ? size_a : size_b;
4567 break;
4568 case '|':
4569 negz = nega | negb;
4570 size_z = negb ? size_b : size_a;
4571 break;
4572 default:
4573 PyErr_BadArgument();
4574 return NULL;
4575 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 /* We allow an extra digit if z is negative, to make sure that
4578 the final two's complement of z doesn't overflow. */
4579 z = _PyLong_New(size_z + negz);
4580 if (z == NULL) {
4581 Py_DECREF(a);
4582 Py_DECREF(b);
4583 return NULL;
4584 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 /* Compute digits for overlap of a and b. */
4587 switch(op) {
4588 case '&':
4589 for (i = 0; i < size_b; ++i)
4590 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4591 break;
4592 case '|':
4593 for (i = 0; i < size_b; ++i)
4594 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4595 break;
4596 case '^':
4597 for (i = 0; i < size_b; ++i)
4598 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4599 break;
4600 default:
4601 PyErr_BadArgument();
4602 return NULL;
4603 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 /* Copy any remaining digits of a, inverting if necessary. */
4606 if (op == '^' && negb)
4607 for (; i < size_z; ++i)
4608 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4609 else if (i < size_z)
4610 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4611 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 /* Complement result if negative. */
4614 if (negz) {
4615 Py_SIZE(z) = -(Py_SIZE(z));
4616 z->ob_digit[size_z] = PyLong_MASK;
4617 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4618 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 Py_DECREF(a);
4621 Py_DECREF(b);
4622 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004623}
4624
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004625static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004626long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 PyObject *c;
4629 CHECK_BINOP(a, b);
4630 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4631 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004632}
4633
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004634static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004635long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 PyObject *c;
4638 CHECK_BINOP(a, b);
4639 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4640 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004641}
4642
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004643static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004644long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 PyObject *c;
4647 CHECK_BINOP(a, b);
4648 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4649 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004650}
4651
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004652static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004653long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 if (PyLong_CheckExact(v))
4656 Py_INCREF(v);
4657 else
4658 v = _PyLong_Copy((PyLongObject *)v);
4659 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004660}
4661
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004662PyObject *
4663_PyLong_GCD(PyObject *aarg, PyObject *barg)
4664{
4665 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4666 stwodigits x, y, q, s, t, c_carry, d_carry;
4667 stwodigits A, B, C, D, T;
4668 int nbits, k;
4669 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4670 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4671
4672 a = (PyLongObject *)aarg;
4673 b = (PyLongObject *)barg;
4674 size_a = Py_SIZE(a);
4675 size_b = Py_SIZE(b);
4676 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4677 Py_INCREF(a);
4678 Py_INCREF(b);
4679 goto simple;
4680 }
4681
4682 /* Initial reduction: make sure that 0 <= b <= a. */
4683 a = (PyLongObject *)long_abs(a);
4684 if (a == NULL)
4685 return NULL;
4686 b = (PyLongObject *)long_abs(b);
4687 if (b == NULL) {
4688 Py_DECREF(a);
4689 return NULL;
4690 }
4691 if (long_compare(a, b) < 0) {
4692 r = a;
4693 a = b;
4694 b = r;
4695 }
4696 /* We now own references to a and b */
4697
4698 alloc_a = Py_SIZE(a);
4699 alloc_b = Py_SIZE(b);
4700 /* reduce until a fits into 2 digits */
4701 while ((size_a = Py_SIZE(a)) > 2) {
4702 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4703 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4704 corresponding bits of b into y */
4705 size_b = Py_SIZE(b);
4706 assert(size_b <= size_a);
4707 if (size_b == 0) {
4708 if (size_a < alloc_a) {
4709 r = (PyLongObject *)_PyLong_Copy(a);
4710 Py_DECREF(a);
4711 }
4712 else
4713 r = a;
4714 Py_DECREF(b);
4715 Py_XDECREF(c);
4716 Py_XDECREF(d);
4717 return (PyObject *)r;
4718 }
4719 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4720 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4721 (a->ob_digit[size_a-3] >> nbits));
4722
4723 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4724 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4725 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4726
4727 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4728 larger than PyLong_MASK during the algorithm. */
4729 A = 1; B = 0; C = 0; D = 1;
4730 for (k=0;; k++) {
4731 if (y-C == 0)
4732 break;
4733 q = (x+(A-1))/(y-C);
4734 s = B+q*D;
4735 t = x-q*y;
4736 if (s > t)
4737 break;
4738 x = y; y = t;
4739 t = A+q*C; A = D; B = C; C = s; D = t;
4740 }
4741
4742 if (k == 0) {
4743 /* no progress; do a Euclidean step */
4744 if (l_divmod(a, b, NULL, &r) < 0)
4745 goto error;
4746 Py_DECREF(a);
4747 a = b;
4748 b = r;
4749 alloc_a = alloc_b;
4750 alloc_b = Py_SIZE(b);
4751 continue;
4752 }
4753
4754 /*
4755 a, b = A*b-B*a, D*a-C*b if k is odd
4756 a, b = A*a-B*b, D*b-C*a if k is even
4757 */
4758 if (k&1) {
4759 T = -A; A = -B; B = T;
4760 T = -C; C = -D; D = T;
4761 }
4762 if (c != NULL)
4763 Py_SIZE(c) = size_a;
4764 else if (Py_REFCNT(a) == 1) {
4765 Py_INCREF(a);
4766 c = a;
4767 }
4768 else {
4769 alloc_a = size_a;
4770 c = _PyLong_New(size_a);
4771 if (c == NULL)
4772 goto error;
4773 }
4774
4775 if (d != NULL)
4776 Py_SIZE(d) = size_a;
4777 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4778 Py_INCREF(b);
4779 d = b;
4780 Py_SIZE(d) = size_a;
4781 }
4782 else {
4783 alloc_b = size_a;
4784 d = _PyLong_New(size_a);
4785 if (d == NULL)
4786 goto error;
4787 }
4788 a_end = a->ob_digit + size_a;
4789 b_end = b->ob_digit + size_b;
4790
4791 /* compute new a and new b in parallel */
4792 a_digit = a->ob_digit;
4793 b_digit = b->ob_digit;
4794 c_digit = c->ob_digit;
4795 d_digit = d->ob_digit;
4796 c_carry = 0;
4797 d_carry = 0;
4798 while (b_digit < b_end) {
4799 c_carry += (A * *a_digit) - (B * *b_digit);
4800 d_carry += (D * *b_digit++) - (C * *a_digit++);
4801 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4802 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4803 c_carry >>= PyLong_SHIFT;
4804 d_carry >>= PyLong_SHIFT;
4805 }
4806 while (a_digit < a_end) {
4807 c_carry += A * *a_digit;
4808 d_carry -= C * *a_digit++;
4809 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4810 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4811 c_carry >>= PyLong_SHIFT;
4812 d_carry >>= PyLong_SHIFT;
4813 }
4814 assert(c_carry == 0);
4815 assert(d_carry == 0);
4816
4817 Py_INCREF(c);
4818 Py_INCREF(d);
4819 Py_DECREF(a);
4820 Py_DECREF(b);
4821 a = long_normalize(c);
4822 b = long_normalize(d);
4823 }
4824 Py_XDECREF(c);
4825 Py_XDECREF(d);
4826
4827simple:
4828 assert(Py_REFCNT(a) > 0);
4829 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004830/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4831 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4832#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004833 /* a fits into a long, so b must too */
4834 x = PyLong_AsLong((PyObject *)a);
4835 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004836#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004837 x = PyLong_AsLongLong((PyObject *)a);
4838 y = PyLong_AsLongLong((PyObject *)b);
4839#else
4840# error "_PyLong_GCD"
4841#endif
4842 x = Py_ABS(x);
4843 y = Py_ABS(y);
4844 Py_DECREF(a);
4845 Py_DECREF(b);
4846
4847 /* usual Euclidean algorithm for longs */
4848 while (y != 0) {
4849 t = y;
4850 y = x % y;
4851 x = t;
4852 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004853#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004854 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004855#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004856 return PyLong_FromLongLong(x);
4857#else
4858# error "_PyLong_GCD"
4859#endif
4860
4861error:
4862 Py_DECREF(a);
4863 Py_DECREF(b);
4864 Py_XDECREF(c);
4865 Py_XDECREF(d);
4866 return NULL;
4867}
4868
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004869static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004870long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004872 double result;
4873 result = PyLong_AsDouble(v);
4874 if (result == -1.0 && PyErr_Occurred())
4875 return NULL;
4876 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004877}
4878
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004879static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004880long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
4881
4882/*[clinic input]
4883@classmethod
4884int.__new__ as long_new
4885 x: object(c_default="NULL") = 0
4886 /
4887 base as obase: object(c_default="NULL") = 10
4888[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004889
Tim Peters6d6c1a32001-08-02 04:15:00 +00004890static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004891long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
4892/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00004893{
Gregory P. Smitha689e522012-12-25 22:38:32 -08004894 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004897 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004898 if (x == NULL) {
4899 if (obase != NULL) {
4900 PyErr_SetString(PyExc_TypeError,
4901 "int() missing string argument");
4902 return NULL;
4903 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004904 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004905 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004906 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004908
Gregory P. Smitha689e522012-12-25 22:38:32 -08004909 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004910 if (base == -1 && PyErr_Occurred())
4911 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004912 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004913 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05304914 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004915 return NULL;
4916 }
4917
4918 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004919 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004920 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 if (PyByteArray_Check(x))
4923 string = PyByteArray_AS_STRING(x);
4924 else
4925 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004926 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004927 }
4928 else {
4929 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004930 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 return NULL;
4932 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004933}
4934
Serhiy Storchaka95949422013-08-27 19:40:23 +03004935/* Wimpy, slow approach to tp_new calls for subtypes of int:
4936 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004937 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004938 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004939*/
4940static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004941long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00004942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 PyLongObject *tmp, *newobj;
4944 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004947 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 if (tmp == NULL)
4949 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004950 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 n = Py_SIZE(tmp);
4952 if (n < 0)
4953 n = -n;
4954 newobj = (PyLongObject *)type->tp_alloc(type, n);
4955 if (newobj == NULL) {
4956 Py_DECREF(tmp);
4957 return NULL;
4958 }
4959 assert(PyLong_Check(newobj));
4960 Py_SIZE(newobj) = Py_SIZE(tmp);
4961 for (i = 0; i < n; i++)
4962 newobj->ob_digit[i] = tmp->ob_digit[i];
4963 Py_DECREF(tmp);
4964 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004965}
4966
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004967/*[clinic input]
4968int.__getnewargs__
4969[clinic start generated code]*/
4970
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004971static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004972int___getnewargs___impl(PyObject *self)
4973/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004974{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004975 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004976}
4977
Guido van Rossumb43daf72007-08-01 18:08:08 +00004978static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004979long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
4980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004982}
4983
4984static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004985long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
4986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004988}
4989
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004990/*[clinic input]
4991int.__format__
4992
4993 format_spec: unicode
4994 /
4995[clinic start generated code]*/
4996
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004997static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004998int___format___impl(PyObject *self, PyObject *format_spec)
4999/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005000{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005001 _PyUnicodeWriter writer;
5002 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005003
Victor Stinner8f674cc2013-04-17 23:02:17 +02005004 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005005 ret = _PyLong_FormatAdvancedWriter(
5006 &writer,
5007 self,
5008 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5009 if (ret == -1) {
5010 _PyUnicodeWriter_Dealloc(&writer);
5011 return NULL;
5012 }
5013 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005014}
5015
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005016/* Return a pair (q, r) such that a = b * q + r, and
5017 abs(r) <= abs(b)/2, with equality possible only if q is even.
5018 In other words, q == a / b, rounded to the nearest integer using
5019 round-half-to-even. */
5020
5021PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005022_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005023{
5024 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005025 PyObject *twice_rem, *result, *temp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005026 int cmp, quo_is_odd, quo_is_neg;
5027
5028 /* Equivalent Python code:
5029
5030 def divmod_near(a, b):
5031 q, r = divmod(a, b)
5032 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5033 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5034 # positive, 2 * r < b if b negative.
5035 greater_than_half = 2*r > b if b > 0 else 2*r < b
5036 exactly_half = 2*r == b
5037 if greater_than_half or exactly_half and q % 2 == 1:
5038 q += 1
5039 r -= b
5040 return q, r
5041
5042 */
5043 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5044 PyErr_SetString(PyExc_TypeError,
5045 "non-integer arguments in division");
5046 return NULL;
5047 }
5048
5049 /* Do a and b have different signs? If so, quotient is negative. */
5050 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5051
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005052 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5053 goto error;
5054
5055 /* compare twice the remainder with the divisor, to see
5056 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005057 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005058 if (twice_rem == NULL)
5059 goto error;
5060 if (quo_is_neg) {
5061 temp = long_neg((PyLongObject*)twice_rem);
5062 Py_DECREF(twice_rem);
5063 twice_rem = temp;
5064 if (twice_rem == NULL)
5065 goto error;
5066 }
5067 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5068 Py_DECREF(twice_rem);
5069
5070 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5071 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5072 /* fix up quotient */
5073 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005074 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005075 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005076 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005077 Py_DECREF(quo);
5078 quo = (PyLongObject *)temp;
5079 if (quo == NULL)
5080 goto error;
5081 /* and remainder */
5082 if (quo_is_neg)
5083 temp = long_add(rem, (PyLongObject *)b);
5084 else
5085 temp = long_sub(rem, (PyLongObject *)b);
5086 Py_DECREF(rem);
5087 rem = (PyLongObject *)temp;
5088 if (rem == NULL)
5089 goto error;
5090 }
5091
5092 result = PyTuple_New(2);
5093 if (result == NULL)
5094 goto error;
5095
5096 /* PyTuple_SET_ITEM steals references */
5097 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5098 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005099 return result;
5100
5101 error:
5102 Py_XDECREF(quo);
5103 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005104 return NULL;
5105}
5106
Eric Smith8c663262007-08-25 02:26:07 +00005107static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005108long_round(PyObject *self, PyObject *args)
5109{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005110 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005111
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005112 /* To round an integer m to the nearest 10**n (n positive), we make use of
5113 * the divmod_near operation, defined by:
5114 *
5115 * divmod_near(a, b) = (q, r)
5116 *
5117 * where q is the nearest integer to the quotient a / b (the
5118 * nearest even integer in the case of a tie) and r == a - q * b.
5119 * Hence q * b = a - r is the nearest multiple of b to a,
5120 * preferring even multiples in the case of a tie.
5121 *
5122 * So the nearest multiple of 10**n to m is:
5123 *
5124 * m - divmod_near(m, 10**n)[1].
5125 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5127 return NULL;
5128 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005129 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005130
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005131 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005132 if (ndigits == NULL)
5133 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005134
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005135 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 if (Py_SIZE(ndigits) >= 0) {
5137 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005138 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005139 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005140
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005141 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5142 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005143 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005144 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005146 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005147
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005148 result = PyLong_FromLong(10L);
5149 if (result == NULL) {
5150 Py_DECREF(ndigits);
5151 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005152 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005153
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005154 temp = long_pow(result, ndigits, Py_None);
5155 Py_DECREF(ndigits);
5156 Py_DECREF(result);
5157 result = temp;
5158 if (result == NULL)
5159 return NULL;
5160
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005161 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005162 Py_DECREF(result);
5163 result = temp;
5164 if (result == NULL)
5165 return NULL;
5166
5167 temp = long_sub((PyLongObject *)self,
5168 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5169 Py_DECREF(result);
5170 result = temp;
5171
5172 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005173}
5174
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005175/*[clinic input]
5176int.__sizeof__ -> Py_ssize_t
5177
5178Returns size in memory, in bytes.
5179[clinic start generated code]*/
5180
5181static Py_ssize_t
5182int___sizeof___impl(PyObject *self)
5183/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005186
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005187 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5188 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005189}
5190
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005191/*[clinic input]
5192int.bit_length
5193
5194Number of bits necessary to represent self in binary.
5195
5196>>> bin(37)
5197'0b100101'
5198>>> (37).bit_length()
51996
5200[clinic start generated code]*/
5201
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005202static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005203int_bit_length_impl(PyObject *self)
5204/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005206 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005207 Py_ssize_t ndigits;
5208 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005210
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005211 assert(self != NULL);
5212 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005213
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005214 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005215 if (ndigits == 0)
5216 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005217
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005218 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005219 msd_bits = bits_in_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5222 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005224 /* expression above may overflow; use Python integers instead */
5225 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5226 if (result == NULL)
5227 return NULL;
5228 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5229 if (x == NULL)
5230 goto error;
5231 y = (PyLongObject *)long_mul(result, x);
5232 Py_DECREF(x);
5233 if (y == NULL)
5234 goto error;
5235 Py_DECREF(result);
5236 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5239 if (x == NULL)
5240 goto error;
5241 y = (PyLongObject *)long_add(result, x);
5242 Py_DECREF(x);
5243 if (y == NULL)
5244 goto error;
5245 Py_DECREF(result);
5246 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005249
Mark Dickinson22b20182010-05-10 21:27:53 +00005250 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 Py_DECREF(result);
5252 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005253}
5254
Christian Heimes53876d92008-04-19 00:31:39 +00005255#if 0
5256static PyObject *
5257long_is_finite(PyObject *v)
5258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005260}
5261#endif
5262
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005263/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005264int.as_integer_ratio
5265
5266Return integer ratio.
5267
5268Return a pair of integers, whose ratio is exactly equal to the original int
5269and with a positive denominator.
5270
5271>>> (10).as_integer_ratio()
5272(10, 1)
5273>>> (-10).as_integer_ratio()
5274(-10, 1)
5275>>> (0).as_integer_ratio()
5276(0, 1)
5277[clinic start generated code]*/
5278
5279static PyObject *
5280int_as_integer_ratio_impl(PyObject *self)
5281/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5282{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005283 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005284 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005285 if (numerator == NULL) {
5286 return NULL;
5287 }
5288 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5289 Py_DECREF(numerator);
5290 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005291}
5292
5293/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005294int.to_bytes
5295
5296 length: Py_ssize_t
5297 Length of bytes object to use. An OverflowError is raised if the
5298 integer is not representable with the given number of bytes.
5299 byteorder: unicode
5300 The byte order used to represent the integer. If byteorder is 'big',
5301 the most significant byte is at the beginning of the byte array. If
5302 byteorder is 'little', the most significant byte is at the end of the
5303 byte array. To request the native byte order of the host system, use
5304 `sys.byteorder' as the byte order value.
5305 *
5306 signed as is_signed: bool = False
5307 Determines whether two's complement is used to represent the integer.
5308 If signed is False and a negative integer is given, an OverflowError
5309 is raised.
5310
5311Return an array of bytes representing an integer.
5312[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005313
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005314static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005315int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5316 int is_signed)
5317/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005320 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005321
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005322 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005324 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005325 little_endian = 0;
5326 else {
5327 PyErr_SetString(PyExc_ValueError,
5328 "byteorder must be either 'little' or 'big'");
5329 return NULL;
5330 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 if (length < 0) {
5333 PyErr_SetString(PyExc_ValueError,
5334 "length argument must be non-negative");
5335 return NULL;
5336 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 bytes = PyBytes_FromStringAndSize(NULL, length);
5339 if (bytes == NULL)
5340 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005341
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005342 if (_PyLong_AsByteArray((PyLongObject *)self,
5343 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 length, little_endian, is_signed) < 0) {
5345 Py_DECREF(bytes);
5346 return NULL;
5347 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005350}
5351
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005352/*[clinic input]
5353@classmethod
5354int.from_bytes
5355
5356 bytes as bytes_obj: object
5357 Holds the array of bytes to convert. The argument must either
5358 support the buffer protocol or be an iterable object producing bytes.
5359 Bytes and bytearray are examples of built-in objects that support the
5360 buffer protocol.
5361 byteorder: unicode
5362 The byte order used to represent the integer. If byteorder is 'big',
5363 the most significant byte is at the beginning of the byte array. If
5364 byteorder is 'little', the most significant byte is at the end of the
5365 byte array. To request the native byte order of the host system, use
5366 `sys.byteorder' as the byte order value.
5367 *
5368 signed as is_signed: bool = False
5369 Indicates whether two's complement is used to represent the integer.
5370
5371Return the integer represented by the given array of bytes.
5372[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005373
5374static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005375int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5376 PyObject *byteorder, int is_signed)
5377/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005380 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005381
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005382 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005384 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 little_endian = 0;
5386 else {
5387 PyErr_SetString(PyExc_ValueError,
5388 "byteorder must be either 'little' or 'big'");
5389 return NULL;
5390 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005391
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005392 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 if (bytes == NULL)
5394 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 long_obj = _PyLong_FromByteArray(
5397 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5398 little_endian, is_signed);
5399 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005400
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005401 if (long_obj != NULL && type != &PyLong_Type) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01005402 Py_SETREF(long_obj, PyObject_CallFunctionObjArgs((PyObject *)type,
5403 long_obj, NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005407}
5408
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005409static PyObject *
5410long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5411{
5412 return long_long(self);
5413}
5414
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005415static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005416 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005418 INT_BIT_LENGTH_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00005419#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5421 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005422#endif
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005423 INT_TO_BYTES_METHODDEF
5424 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005425 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005426 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005427 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005428 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005430 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 "Ceiling of an Integral returns itself."},
5432 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5433 "Rounding an Integral returns itself.\n"
5434 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005435 INT___GETNEWARGS___METHODDEF
5436 INT___FORMAT___METHODDEF
5437 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005439};
5440
Guido van Rossumb43daf72007-08-01 18:08:08 +00005441static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005442 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005443 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005444 "the real part of a complex number",
5445 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005446 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005447 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005448 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005449 NULL},
5450 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005451 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005452 "the numerator of a rational number in lowest terms",
5453 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005454 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005455 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005456 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005457 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005458 {NULL} /* Sentinel */
5459};
5460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005461PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005462"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005463int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005464\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005465Convert a number or string to an integer, or return 0 if no arguments\n\
5466are given. If x is a number, return x.__int__(). For floating point\n\
5467numbers, this truncates towards zero.\n\
5468\n\
5469If x is not a number or if base is given, then x must be a string,\n\
5470bytes, or bytearray instance representing an integer literal in the\n\
5471given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5472by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5473Base 0 means to interpret the base from the string as an integer literal.\n\
5474>>> int('0b100', base=0)\n\
54754");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005476
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005477static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005478 (binaryfunc)long_add, /*nb_add*/
5479 (binaryfunc)long_sub, /*nb_subtract*/
5480 (binaryfunc)long_mul, /*nb_multiply*/
5481 long_mod, /*nb_remainder*/
5482 long_divmod, /*nb_divmod*/
5483 long_pow, /*nb_power*/
5484 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005485 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005486 (unaryfunc)long_abs, /*tp_absolute*/
5487 (inquiry)long_bool, /*tp_bool*/
5488 (unaryfunc)long_invert, /*nb_invert*/
5489 long_lshift, /*nb_lshift*/
5490 (binaryfunc)long_rshift, /*nb_rshift*/
5491 long_and, /*nb_and*/
5492 long_xor, /*nb_xor*/
5493 long_or, /*nb_or*/
5494 long_long, /*nb_int*/
5495 0, /*nb_reserved*/
5496 long_float, /*nb_float*/
5497 0, /* nb_inplace_add */
5498 0, /* nb_inplace_subtract */
5499 0, /* nb_inplace_multiply */
5500 0, /* nb_inplace_remainder */
5501 0, /* nb_inplace_power */
5502 0, /* nb_inplace_lshift */
5503 0, /* nb_inplace_rshift */
5504 0, /* nb_inplace_and */
5505 0, /* nb_inplace_xor */
5506 0, /* nb_inplace_or */
5507 long_div, /* nb_floor_divide */
5508 long_true_divide, /* nb_true_divide */
5509 0, /* nb_inplace_floor_divide */
5510 0, /* nb_inplace_true_divide */
5511 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005512};
5513
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005514PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5516 "int", /* tp_name */
5517 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5518 sizeof(digit), /* tp_itemsize */
5519 long_dealloc, /* tp_dealloc */
5520 0, /* tp_print */
5521 0, /* tp_getattr */
5522 0, /* tp_setattr */
5523 0, /* tp_reserved */
5524 long_to_decimal_string, /* tp_repr */
5525 &long_as_number, /* tp_as_number */
5526 0, /* tp_as_sequence */
5527 0, /* tp_as_mapping */
5528 (hashfunc)long_hash, /* tp_hash */
5529 0, /* tp_call */
5530 long_to_decimal_string, /* tp_str */
5531 PyObject_GenericGetAttr, /* tp_getattro */
5532 0, /* tp_setattro */
5533 0, /* tp_as_buffer */
5534 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5535 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5536 long_doc, /* tp_doc */
5537 0, /* tp_traverse */
5538 0, /* tp_clear */
5539 long_richcompare, /* tp_richcompare */
5540 0, /* tp_weaklistoffset */
5541 0, /* tp_iter */
5542 0, /* tp_iternext */
5543 long_methods, /* tp_methods */
5544 0, /* tp_members */
5545 long_getset, /* tp_getset */
5546 0, /* tp_base */
5547 0, /* tp_dict */
5548 0, /* tp_descr_get */
5549 0, /* tp_descr_set */
5550 0, /* tp_dictoffset */
5551 0, /* tp_init */
5552 0, /* tp_alloc */
5553 long_new, /* tp_new */
5554 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005555};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005556
Mark Dickinsonbd792642009-03-18 20:06:12 +00005557static PyTypeObject Int_InfoType;
5558
5559PyDoc_STRVAR(int_info__doc__,
5560"sys.int_info\n\
5561\n\
5562A struct sequence that holds information about Python's\n\
5563internal representation of integers. The attributes are read only.");
5564
5565static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005567 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005569};
5570
5571static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 "sys.int_info", /* name */
5573 int_info__doc__, /* doc */
5574 int_info_fields, /* fields */
5575 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005576};
5577
5578PyObject *
5579PyLong_GetInfo(void)
5580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005581 PyObject* int_info;
5582 int field = 0;
5583 int_info = PyStructSequence_New(&Int_InfoType);
5584 if (int_info == NULL)
5585 return NULL;
5586 PyStructSequence_SET_ITEM(int_info, field++,
5587 PyLong_FromLong(PyLong_SHIFT));
5588 PyStructSequence_SET_ITEM(int_info, field++,
5589 PyLong_FromLong(sizeof(digit)));
5590 if (PyErr_Occurred()) {
5591 Py_CLEAR(int_info);
5592 return NULL;
5593 }
5594 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005595}
5596
Guido van Rossumddefaf32007-01-14 03:31:43 +00005597int
5598_PyLong_Init(void)
5599{
5600#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 int ival, size;
5602 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005604 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5605 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5606 if (Py_TYPE(v) == &PyLong_Type) {
5607 /* The element is already initialized, most likely
5608 * the Python interpreter was initialized before.
5609 */
5610 Py_ssize_t refcnt;
5611 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005613 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5614 _Py_NewReference(op);
5615 /* _Py_NewReference sets the ref count to 1 but
5616 * the ref count might be larger. Set the refcnt
5617 * to the original refcnt + 1 */
5618 Py_REFCNT(op) = refcnt + 1;
5619 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005620 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005621 }
5622 else {
Victor Stinnerb509d522018-11-23 14:27:38 +01005623 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005624 }
5625 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005626 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005628#endif
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005629 _PyLong_Zero = PyLong_FromLong(0);
5630 if (_PyLong_Zero == NULL)
5631 return 0;
5632 _PyLong_One = PyLong_FromLong(1);
5633 if (_PyLong_One == NULL)
5634 return 0;
5635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005637 if (Int_InfoType.tp_name == NULL) {
5638 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5639 return 0;
5640 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005642 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005643}
5644
5645void
5646PyLong_Fini(void)
5647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005648 /* Integers are currently statically allocated. Py_DECREF is not
5649 needed, but Python must forget about the reference or multiple
5650 reinitializations will fail. */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005651 Py_CLEAR(_PyLong_One);
5652 Py_CLEAR(_PyLong_Zero);
Guido van Rossumddefaf32007-01-14 03:31:43 +00005653#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 int i;
5655 PyLongObject *v = small_ints;
5656 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5657 _Py_DEC_REFTOTAL;
5658 _Py_ForgetReference((PyObject*)v);
5659 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005660#endif
5661}