blob: f0567970468a82815b734426a9f39165c2c3439e [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*/
Victor Stinner5dcc06f2019-11-21 08:51:59 +010043static PyLongObject* small_ints[NSMALLNEGINTS + NSMALLPOSINTS] = {0};
Greg Price5e63ab02019-08-24 10:19:37 -070044
animalize6b519982019-09-06 14:00:56 +080045#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050046#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070047
Guido van Rossumddefaf32007-01-14 03:31:43 +000048#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +000049Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000050#endif
51
Guido van Rossum7eaf8222007-06-18 17:58:50 +000052static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000053get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000054{
animalize6b519982019-09-06 14:00:56 +080055 assert(IS_SMALL_INT(ival));
Victor Stinner5dcc06f2019-11-21 08:51:59 +010056 PyObject *v = (PyObject*)small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000058#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 if (ival >= 0)
Pablo Galindo49c75a82018-10-28 15:02:17 +000060 _Py_quick_int_allocs++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 else
Pablo Galindo49c75a82018-10-28 15:02:17 +000062 _Py_quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000063#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068maybe_small_long(PyLongObject *v)
69{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020070 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080072 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 Py_DECREF(v);
74 return (PyLongObject *)get_small_int(ival);
75 }
76 }
77 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000078}
Guido van Rossumddefaf32007-01-14 03:31:43 +000079#else
animalize6b519982019-09-06 14:00:56 +080080#define IS_SMALL_INT(ival) 0
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050081#define IS_SMALL_UINT(ival) 0
animalize6b519982019-09-06 14:00:56 +080082#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000083#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000084#endif
85
Serhiy Storchaka95949422013-08-27 19:40:23 +030086/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000087 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020088Py_LOCAL_INLINE(void)
89_PyLong_Negate(PyLongObject **x_p)
90{
91 PyLongObject *x;
92
93 x = (PyLongObject *)*x_p;
94 if (Py_REFCNT(x) == 1) {
95 Py_SIZE(x) = -Py_SIZE(x);
96 return;
97 }
98
99 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
100 Py_DECREF(x);
101}
102
Serhiy Storchaka95949422013-08-27 19:40:23 +0300103/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +0000104 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +0300105 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +0000106 */
Tim Peters0973b992004-08-29 22:16:50 +0000107#define KARATSUBA_CUTOFF 70
108#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +0000109
Tim Peters47e52ee2004-08-30 02:44:38 +0000110/* For exponentiation, use the binary left-to-right algorithm
111 * unless the exponent contains more than FIVEARY_CUTOFF digits.
112 * In that case, do 5 bits at a time. The potential drawback is that
113 * a table of 2**5 intermediate results is computed.
114 */
115#define FIVEARY_CUTOFF 8
116
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000117#define SIGCHECK(PyTryBlock) \
118 do { \
119 if (PyErr_CheckSignals()) PyTryBlock \
120 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000121
Serhiy Storchaka95949422013-08-27 19:40:23 +0300122/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000123 Doesn't attempt to free the storage--in most cases, due to the nature
124 of the algorithms used, this could save at most be one word anyway. */
125
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200127long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200129 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 while (i > 0 && v->ob_digit[i-1] == 0)
133 --i;
134 if (i != j)
135 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
136 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000137}
138
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200139/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
140 using the nb_int slot, if available. Raise TypeError if either the
141 nb_int slot is not available or the result of the call to nb_int
142 returns something not of type int.
143*/
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200144PyObject *
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200145_PyLong_FromNbInt(PyObject *integral)
146{
147 PyNumberMethods *nb;
148 PyObject *result;
149
150 /* Fast path for the case that we already have an int. */
151 if (PyLong_CheckExact(integral)) {
152 Py_INCREF(integral);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200153 return integral;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200154 }
155
156 nb = Py_TYPE(integral)->tp_as_number;
157 if (nb == NULL || nb->nb_int == NULL) {
158 PyErr_Format(PyExc_TypeError,
159 "an integer is required (got type %.200s)",
160 Py_TYPE(integral)->tp_name);
161 return NULL;
162 }
163
164 /* Convert using the nb_int slot, which should return something
165 of exact type int. */
166 result = nb->nb_int(integral);
167 if (!result || PyLong_CheckExact(result))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200168 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200169 if (!PyLong_Check(result)) {
170 PyErr_Format(PyExc_TypeError,
171 "__int__ returned non-int (type %.200s)",
172 result->ob_type->tp_name);
173 Py_DECREF(result);
174 return NULL;
175 }
176 /* Issue #17576: warn if 'result' not of exact type int. */
177 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
178 "__int__ returned non-int (type %.200s). "
179 "The ability to return an instance of a strict subclass of int "
180 "is deprecated, and may be removed in a future version of Python.",
181 result->ob_type->tp_name)) {
182 Py_DECREF(result);
183 return NULL;
184 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200185 return result;
186}
187
188/* Convert the given object to a PyLongObject using the nb_index or
189 nb_int slots, if available (the latter is deprecated).
190 Raise TypeError if either nb_index and nb_int slots are not
191 available or the result of the call to nb_index or nb_int
192 returns something not of type int.
193 Should be replaced with PyNumber_Index after the end of the
194 deprecation period.
195*/
196PyObject *
197_PyLong_FromNbIndexOrNbInt(PyObject *integral)
198{
199 PyNumberMethods *nb;
200 PyObject *result;
201
202 /* Fast path for the case that we already have an int. */
203 if (PyLong_CheckExact(integral)) {
204 Py_INCREF(integral);
205 return integral;
206 }
207
208 nb = Py_TYPE(integral)->tp_as_number;
209 if (nb == NULL || (nb->nb_index == NULL && nb->nb_int == NULL)) {
210 PyErr_Format(PyExc_TypeError,
211 "an integer is required (got type %.200s)",
212 Py_TYPE(integral)->tp_name);
213 return NULL;
214 }
215
216 if (nb->nb_index) {
217 /* Convert using the nb_index slot, which should return something
218 of exact type int. */
219 result = nb->nb_index(integral);
220 if (!result || PyLong_CheckExact(result))
221 return result;
222 if (!PyLong_Check(result)) {
223 PyErr_Format(PyExc_TypeError,
224 "__index__ returned non-int (type %.200s)",
225 result->ob_type->tp_name);
226 Py_DECREF(result);
227 return NULL;
228 }
229 /* Issue #17576: warn if 'result' not of exact type int. */
230 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
231 "__index__ returned non-int (type %.200s). "
232 "The ability to return an instance of a strict subclass of int "
233 "is deprecated, and may be removed in a future version of Python.",
234 result->ob_type->tp_name))
235 {
236 Py_DECREF(result);
237 return NULL;
238 }
239 return result;
240 }
241
242 result = _PyLong_FromNbInt(integral);
243 if (result && PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
244 "an integer is required (got type %.200s). "
245 "Implicit conversion to integers using __int__ is deprecated, "
246 "and may be removed in a future version of Python.",
247 Py_TYPE(integral)->tp_name))
248 {
249 Py_DECREF(result);
250 return NULL;
251 }
252 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200253}
254
255
Serhiy Storchaka95949422013-08-27 19:40:23 +0300256/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000257 Return NULL and set exception if we run out of memory. */
258
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000259#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000261
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000262PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000263_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 PyLongObject *result;
266 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
267 sizeof(digit)*size. Previous incarnations of this code used
268 sizeof(PyVarObject) instead of the offsetof, but this risks being
269 incorrect in the presence of padding between the PyVarObject header
270 and the digits. */
271 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
272 PyErr_SetString(PyExc_OverflowError,
273 "too many digits in integer");
274 return NULL;
275 }
276 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
277 size*sizeof(digit));
278 if (!result) {
279 PyErr_NoMemory();
280 return NULL;
281 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100282 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000283}
284
Tim Peters64b5ce32001-09-10 20:52:51 +0000285PyObject *
286_PyLong_Copy(PyLongObject *src)
287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 PyLongObject *result;
289 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 assert(src != NULL);
292 i = Py_SIZE(src);
293 if (i < 0)
294 i = -(i);
295 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100296 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800297 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700298 return get_small_int(ival);
299 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 }
301 result = _PyLong_New(i);
302 if (result != NULL) {
303 Py_SIZE(result) = Py_SIZE(src);
304 while (--i >= 0)
305 result->ob_digit[i] = src->ob_digit[i];
306 }
307 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000308}
309
Serhiy Storchaka95949422013-08-27 19:40:23 +0300310/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000311
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000313PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyLongObject *v;
316 unsigned long abs_ival;
317 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
318 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100319 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000320
animalize6b519982019-09-06 14:00:56 +0800321 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700322 return get_small_int((sdigit)ival);
323 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (ival < 0) {
326 /* negate: can't write this as abs_ival = -ival since that
327 invokes undefined behaviour when ival is LONG_MIN */
328 abs_ival = 0U-(unsigned long)ival;
329 sign = -1;
330 }
331 else {
332 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100333 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* Fast path for single-digit ints */
337 if (!(abs_ival >> PyLong_SHIFT)) {
338 v = _PyLong_New(1);
339 if (v) {
340 Py_SIZE(v) = sign;
341 v->ob_digit[0] = Py_SAFE_DOWNCAST(
342 abs_ival, unsigned long, digit);
343 }
344 return (PyObject*)v;
345 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000346
Mark Dickinson249b8982009-04-27 19:41:00 +0000347#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 /* 2 digits */
349 if (!(abs_ival >> 2*PyLong_SHIFT)) {
350 v = _PyLong_New(2);
351 if (v) {
352 Py_SIZE(v) = 2*sign;
353 v->ob_digit[0] = Py_SAFE_DOWNCAST(
354 abs_ival & PyLong_MASK, unsigned long, digit);
355 v->ob_digit[1] = Py_SAFE_DOWNCAST(
356 abs_ival >> PyLong_SHIFT, unsigned long, digit);
357 }
358 return (PyObject*)v;
359 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000360#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 /* Larger numbers: loop to determine number of digits */
363 t = abs_ival;
364 while (t) {
365 ++ndigits;
366 t >>= PyLong_SHIFT;
367 }
368 v = _PyLong_New(ndigits);
369 if (v != NULL) {
370 digit *p = v->ob_digit;
371 Py_SIZE(v) = ndigits*sign;
372 t = abs_ival;
373 while (t) {
374 *p++ = Py_SAFE_DOWNCAST(
375 t & PyLong_MASK, unsigned long, digit);
376 t >>= PyLong_SHIFT;
377 }
378 }
379 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000380}
381
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500382#define PYLONG_FROM_UINT(INT_TYPE, ival) \
383 do { \
384 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200385 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500386 } \
387 /* Count the number of Python digits. */ \
388 Py_ssize_t ndigits = 0; \
389 INT_TYPE t = (ival); \
390 while (t) { \
391 ++ndigits; \
392 t >>= PyLong_SHIFT; \
393 } \
394 PyLongObject *v = _PyLong_New(ndigits); \
395 if (v == NULL) { \
396 return NULL; \
397 } \
398 digit *p = v->ob_digit; \
399 while ((ival)) { \
400 *p++ = (digit)((ival) & PyLong_MASK); \
401 (ival) >>= PyLong_SHIFT; \
402 } \
403 return (PyObject *)v; \
404 } while(0)
405
Serhiy Storchaka95949422013-08-27 19:40:23 +0300406/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000407
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000408PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000409PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000410{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500411 PYLONG_FROM_UINT(unsigned long, ival);
412}
Tim Petersce9de2f2001-06-14 04:56:19 +0000413
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500414/* Create a new int object from a C unsigned long long int. */
415
416PyObject *
417PyLong_FromUnsignedLongLong(unsigned long long ival)
418{
419 PYLONG_FROM_UINT(unsigned long long, ival);
420}
421
422/* Create a new int object from a C size_t. */
423
424PyObject *
425PyLong_FromSize_t(size_t ival)
426{
427 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000428}
429
Serhiy Storchaka95949422013-08-27 19:40:23 +0300430/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000431
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000432PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 PyLongObject *v;
436 double frac;
437 int i, ndig, expo, neg;
438 neg = 0;
439 if (Py_IS_INFINITY(dval)) {
440 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000441 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 return NULL;
443 }
444 if (Py_IS_NAN(dval)) {
445 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000446 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 return NULL;
448 }
449 if (dval < 0.0) {
450 neg = 1;
451 dval = -dval;
452 }
453 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
454 if (expo <= 0)
455 return PyLong_FromLong(0L);
456 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
457 v = _PyLong_New(ndig);
458 if (v == NULL)
459 return NULL;
460 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
461 for (i = ndig; --i >= 0; ) {
462 digit bits = (digit)frac;
463 v->ob_digit[i] = bits;
464 frac = frac - (double)bits;
465 frac = ldexp(frac, PyLong_SHIFT);
466 }
467 if (neg)
468 Py_SIZE(v) = -(Py_SIZE(v));
469 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000470}
471
Thomas Wouters89f507f2006-12-13 04:49:30 +0000472/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
473 * anything about what happens when a signed integer operation overflows,
474 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700475 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000476 * (unsigned long)LONG_MAX, and for the smallest negative signed long
477 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
478 * However, some other compilers warn about applying unary minus to an
479 * unsigned operand. Hence the weird "0-".
480 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
482#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000483
Serhiy Storchaka95949422013-08-27 19:40:23 +0300484/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100485 method.
486
487 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
488 the result. Otherwise *overflow is 0.
489
490 For other errors (e.g., TypeError), return -1 and set an error condition.
491 In this case *overflow will be 0.
492*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000493
494long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000495PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200498 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 unsigned long x, prev;
500 long res;
501 Py_ssize_t i;
502 int sign;
503 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 *overflow = 0;
506 if (vv == NULL) {
507 PyErr_BadInternalCall();
508 return -1;
509 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000510
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200511 if (PyLong_Check(vv)) {
512 v = (PyLongObject *)vv;
513 }
514 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200515 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200516 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 return -1;
518 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 switch (i) {
525 case -1:
526 res = -(sdigit)v->ob_digit[0];
527 break;
528 case 0:
529 res = 0;
530 break;
531 case 1:
532 res = v->ob_digit[0];
533 break;
534 default:
535 sign = 1;
536 x = 0;
537 if (i < 0) {
538 sign = -1;
539 i = -(i);
540 }
541 while (--i >= 0) {
542 prev = x;
543 x = (x << PyLong_SHIFT) | v->ob_digit[i];
544 if ((x >> PyLong_SHIFT) != prev) {
545 *overflow = sign;
546 goto exit;
547 }
548 }
549 /* Haven't lost any bits, but casting to long requires extra
550 * care (see comment above).
551 */
552 if (x <= (unsigned long)LONG_MAX) {
553 res = (long)x * sign;
554 }
555 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
556 res = LONG_MIN;
557 }
558 else {
559 *overflow = sign;
560 /* res is already set to -1 */
561 }
562 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000563 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200565 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 }
567 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000568}
569
Serhiy Storchaka95949422013-08-27 19:40:23 +0300570/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100571 method. Return -1 and set an error if overflow occurs. */
572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000574PyLong_AsLong(PyObject *obj)
575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 int overflow;
577 long result = PyLong_AsLongAndOverflow(obj, &overflow);
578 if (overflow) {
579 /* XXX: could be cute and give a different
580 message for overflow == -1 */
581 PyErr_SetString(PyExc_OverflowError,
582 "Python int too large to convert to C long");
583 }
584 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000585}
586
Serhiy Storchaka95949422013-08-27 19:40:23 +0300587/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200588 method. Return -1 and set an error if overflow occurs. */
589
590int
591_PyLong_AsInt(PyObject *obj)
592{
593 int overflow;
594 long result = PyLong_AsLongAndOverflow(obj, &overflow);
595 if (overflow || result > INT_MAX || result < INT_MIN) {
596 /* XXX: could be cute and give a different
597 message for overflow == -1 */
598 PyErr_SetString(PyExc_OverflowError,
599 "Python int too large to convert to C int");
600 return -1;
601 }
602 return (int)result;
603}
604
Serhiy Storchaka95949422013-08-27 19:40:23 +0300605/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000606 Returns -1 and sets an error condition if overflow occurs. */
607
608Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000609PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200610 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 size_t x, prev;
612 Py_ssize_t i;
613 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (vv == NULL) {
616 PyErr_BadInternalCall();
617 return -1;
618 }
619 if (!PyLong_Check(vv)) {
620 PyErr_SetString(PyExc_TypeError, "an integer is required");
621 return -1;
622 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 v = (PyLongObject *)vv;
625 i = Py_SIZE(v);
626 switch (i) {
627 case -1: return -(sdigit)v->ob_digit[0];
628 case 0: return 0;
629 case 1: return v->ob_digit[0];
630 }
631 sign = 1;
632 x = 0;
633 if (i < 0) {
634 sign = -1;
635 i = -(i);
636 }
637 while (--i >= 0) {
638 prev = x;
639 x = (x << PyLong_SHIFT) | v->ob_digit[i];
640 if ((x >> PyLong_SHIFT) != prev)
641 goto overflow;
642 }
643 /* Haven't lost any bits, but casting to a signed type requires
644 * extra care (see comment above).
645 */
646 if (x <= (size_t)PY_SSIZE_T_MAX) {
647 return (Py_ssize_t)x * sign;
648 }
649 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
650 return PY_SSIZE_T_MIN;
651 }
652 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000653
Mark Dickinson22b20182010-05-10 21:27:53 +0000654 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 PyErr_SetString(PyExc_OverflowError,
656 "Python int too large to convert to C ssize_t");
657 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000658}
659
Serhiy Storchaka95949422013-08-27 19:40:23 +0300660/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000661 Returns -1 and sets an error condition if overflow occurs. */
662
663unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000664PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000665{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200666 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 unsigned long x, prev;
668 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (vv == NULL) {
671 PyErr_BadInternalCall();
672 return (unsigned long)-1;
673 }
674 if (!PyLong_Check(vv)) {
675 PyErr_SetString(PyExc_TypeError, "an integer is required");
676 return (unsigned long)-1;
677 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 v = (PyLongObject *)vv;
680 i = Py_SIZE(v);
681 x = 0;
682 if (i < 0) {
683 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000684 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return (unsigned long) -1;
686 }
687 switch (i) {
688 case 0: return 0;
689 case 1: return v->ob_digit[0];
690 }
691 while (--i >= 0) {
692 prev = x;
693 x = (x << PyLong_SHIFT) | v->ob_digit[i];
694 if ((x >> PyLong_SHIFT) != prev) {
695 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100696 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000697 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 return (unsigned long) -1;
699 }
700 }
701 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000702}
703
Serhiy Storchaka95949422013-08-27 19:40:23 +0300704/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200705 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000706
707size_t
708PyLong_AsSize_t(PyObject *vv)
709{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200710 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 size_t x, prev;
712 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (vv == NULL) {
715 PyErr_BadInternalCall();
716 return (size_t) -1;
717 }
718 if (!PyLong_Check(vv)) {
719 PyErr_SetString(PyExc_TypeError, "an integer is required");
720 return (size_t)-1;
721 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 v = (PyLongObject *)vv;
724 i = Py_SIZE(v);
725 x = 0;
726 if (i < 0) {
727 PyErr_SetString(PyExc_OverflowError,
728 "can't convert negative value to size_t");
729 return (size_t) -1;
730 }
731 switch (i) {
732 case 0: return 0;
733 case 1: return v->ob_digit[0];
734 }
735 while (--i >= 0) {
736 prev = x;
737 x = (x << PyLong_SHIFT) | v->ob_digit[i];
738 if ((x >> PyLong_SHIFT) != prev) {
739 PyErr_SetString(PyExc_OverflowError,
740 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200741 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 }
743 }
744 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000745}
746
Serhiy Storchaka95949422013-08-27 19:40:23 +0300747/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000748 Returns -1 and sets an error condition if an error occurs. */
749
Guido van Rossumddefaf32007-01-14 03:31:43 +0000750static unsigned long
751_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000752{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200753 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 unsigned long x;
755 Py_ssize_t i;
756 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (vv == NULL || !PyLong_Check(vv)) {
759 PyErr_BadInternalCall();
760 return (unsigned long) -1;
761 }
762 v = (PyLongObject *)vv;
763 i = Py_SIZE(v);
764 switch (i) {
765 case 0: return 0;
766 case 1: return v->ob_digit[0];
767 }
768 sign = 1;
769 x = 0;
770 if (i < 0) {
771 sign = -1;
772 i = -i;
773 }
774 while (--i >= 0) {
775 x = (x << PyLong_SHIFT) | v->ob_digit[i];
776 }
777 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000778}
779
Guido van Rossumddefaf32007-01-14 03:31:43 +0000780unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200781PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 PyLongObject *lo;
784 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000785
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200786 if (op == NULL) {
787 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 return (unsigned long)-1;
789 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000790
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200791 if (PyLong_Check(op)) {
792 return _PyLong_AsUnsignedLongMask(op);
793 }
794
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200795 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (lo == NULL)
797 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200798
799 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
800 Py_DECREF(lo);
801 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000802}
803
Tim Peters5b8132f2003-01-31 15:52:05 +0000804int
805_PyLong_Sign(PyObject *vv)
806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 assert(v != NULL);
810 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000813}
814
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200815/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
816 2**k if d is nonzero, else 0. */
817
818static const unsigned char BitLengthTable[32] = {
819 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
820 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
821};
822
823static int
824bits_in_digit(digit d)
825{
826 int d_bits = 0;
827 while (d >= 32) {
828 d_bits += 6;
829 d >>= 6;
830 }
831 d_bits += (int)BitLengthTable[d];
832 return d_bits;
833}
834
Tim Petersbaefd9e2003-01-28 20:37:45 +0000835size_t
836_PyLong_NumBits(PyObject *vv)
837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyLongObject *v = (PyLongObject *)vv;
839 size_t result = 0;
840 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200841 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 assert(v != NULL);
844 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200845 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
847 if (ndigits > 0) {
848 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700849 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100851 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200852 msd_bits = bits_in_digit(msd);
853 if (SIZE_MAX - msd_bits < result)
854 goto Overflow;
855 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 }
857 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000858
Mark Dickinson22b20182010-05-10 21:27:53 +0000859 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
861 "to express in a platform size_t");
862 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000863}
864
Tim Peters2a9b3672001-06-11 21:23:58 +0000865PyObject *
866_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000868{
Mark Dickinson22b20182010-05-10 21:27:53 +0000869 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 int incr; /* direction to move pstartbyte */
871 const unsigned char* pendbyte; /* MSB of bytes */
872 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300873 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyLongObject* v; /* result */
875 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (n == 0)
878 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 if (little_endian) {
881 pstartbyte = bytes;
882 pendbyte = bytes + n - 1;
883 incr = 1;
884 }
885 else {
886 pstartbyte = bytes + n - 1;
887 pendbyte = bytes;
888 incr = -1;
889 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (is_signed)
892 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200895 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 is positive, and leading 0xff bytes if negative. */
897 {
898 size_t i;
899 const unsigned char* p = pendbyte;
900 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000901 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000904 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 break;
906 }
907 numsignificantbytes = n - i;
908 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
909 actually has 2 significant bytes. OTOH, 0xff0001 ==
910 -0x00ffff, so we wouldn't *need* to bump it there; but we
911 do for 0xffff = -0x0001. To be safe without bothering to
912 check every case, bump it regardless. */
913 if (is_signed && numsignificantbytes < n)
914 ++numsignificantbytes;
915 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000916
Serhiy Storchaka95949422013-08-27 19:40:23 +0300917 /* How many Python int digits do we need? We have
918 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
920 /* catch overflow before it happens */
921 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
922 PyErr_SetString(PyExc_OverflowError,
923 "byte array too long to convert to int");
924 return NULL;
925 }
926 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
927 v = _PyLong_New(ndigits);
928 if (v == NULL)
929 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Copy the bits over. The tricky parts are computing 2's-comp on
932 the fly for signed numbers, and dealing with the mismatch between
933 8-bit bytes and (probably) 15-bit Python digits.*/
934 {
935 size_t i;
936 twodigits carry = 1; /* for 2's-comp calculation */
937 twodigits accum = 0; /* sliding register */
938 unsigned int accumbits = 0; /* number of bits in accum */
939 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
942 twodigits thisbyte = *p;
943 /* Compute correction for 2's comp, if needed. */
944 if (is_signed) {
945 thisbyte = (0xff ^ thisbyte) + carry;
946 carry = thisbyte >> 8;
947 thisbyte &= 0xff;
948 }
949 /* Because we're going LSB to MSB, thisbyte is
950 more significant than what's already in accum,
951 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200952 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 accumbits += 8;
954 if (accumbits >= PyLong_SHIFT) {
955 /* There's enough to fill a Python digit. */
956 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000957 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 ++idigit;
959 accum >>= PyLong_SHIFT;
960 accumbits -= PyLong_SHIFT;
961 assert(accumbits < PyLong_SHIFT);
962 }
963 }
964 assert(accumbits < PyLong_SHIFT);
965 if (accumbits) {
966 assert(idigit < ndigits);
967 v->ob_digit[idigit] = (digit)accum;
968 ++idigit;
969 }
970 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 Py_SIZE(v) = is_signed ? -idigit : idigit;
973 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000974}
975
976int
977_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 unsigned char* bytes, size_t n,
979 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000982 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000984 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
986 digit carry; /* for computing 2's-comp */
987 size_t j; /* # bytes filled */
988 unsigned char* p; /* pointer to next byte in bytes */
989 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (Py_SIZE(v) < 0) {
994 ndigits = -(Py_SIZE(v));
995 if (!is_signed) {
996 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000997 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 return -1;
999 }
1000 do_twos_comp = 1;
1001 }
1002 else {
1003 ndigits = Py_SIZE(v);
1004 do_twos_comp = 0;
1005 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (little_endian) {
1008 p = bytes;
1009 pincr = 1;
1010 }
1011 else {
1012 p = bytes + n - 1;
1013 pincr = -1;
1014 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 /* Copy over all the Python digits.
1017 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +03001018 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 normalized. */
1020 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
1021 j = 0;
1022 accum = 0;
1023 accumbits = 0;
1024 carry = do_twos_comp ? 1 : 0;
1025 for (i = 0; i < ndigits; ++i) {
1026 digit thisdigit = v->ob_digit[i];
1027 if (do_twos_comp) {
1028 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
1029 carry = thisdigit >> PyLong_SHIFT;
1030 thisdigit &= PyLong_MASK;
1031 }
1032 /* Because we're going LSB to MSB, thisdigit is more
1033 significant than what's already in accum, so needs to be
1034 prepended to accum. */
1035 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 /* The most-significant digit may be (probably is) at least
1038 partly empty. */
1039 if (i == ndigits - 1) {
1040 /* Count # of sign bits -- they needn't be stored,
1041 * although for signed conversion we need later to
1042 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +00001043 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 while (s != 0) {
1045 s >>= 1;
1046 accumbits++;
1047 }
1048 }
1049 else
1050 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 /* Store as many bytes as possible. */
1053 while (accumbits >= 8) {
1054 if (j >= n)
1055 goto Overflow;
1056 ++j;
1057 *p = (unsigned char)(accum & 0xff);
1058 p += pincr;
1059 accumbits -= 8;
1060 accum >>= 8;
1061 }
1062 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 /* Store the straggler (if any). */
1065 assert(accumbits < 8);
1066 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1067 if (accumbits > 0) {
1068 if (j >= n)
1069 goto Overflow;
1070 ++j;
1071 if (do_twos_comp) {
1072 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +03001073 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 infinite supply of sign bits). */
1075 accum |= (~(twodigits)0) << accumbits;
1076 }
1077 *p = (unsigned char)(accum & 0xff);
1078 p += pincr;
1079 }
1080 else if (j == n && n > 0 && is_signed) {
1081 /* The main loop filled the byte array exactly, so the code
1082 just above didn't get to ensure there's a sign bit, and the
1083 loop below wouldn't add one either. Make sure a sign bit
1084 exists. */
1085 unsigned char msb = *(p - pincr);
1086 int sign_bit_set = msb >= 0x80;
1087 assert(accumbits == 0);
1088 if (sign_bit_set == do_twos_comp)
1089 return 0;
1090 else
1091 goto Overflow;
1092 }
Tim Peters05607ad2001-06-13 21:01:27 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 /* Fill remaining bytes with copies of the sign bit. */
1095 {
1096 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1097 for ( ; j < n; ++j, p += pincr)
1098 *p = signbyte;
1099 }
Tim Peters05607ad2001-06-13 21:01:27 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001102
Mark Dickinson22b20182010-05-10 21:27:53 +00001103 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1105 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001106
Tim Peters2a9b3672001-06-11 21:23:58 +00001107}
1108
Serhiy Storchaka95949422013-08-27 19:40:23 +03001109/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001110
1111PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001112PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001113{
Mark Dickinson91044792012-10-18 19:21:43 +01001114#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001115 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001116#else
1117
Tim Peters70128a12001-06-16 08:48:40 +00001118#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001119# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001120#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001121 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001122#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001123
Guido van Rossum78694d91998-09-18 14:14:13 +00001124}
1125
Serhiy Storchaka95949422013-08-27 19:40:23 +03001126/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001127
1128void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001129PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001130{
Tim Peters70128a12001-06-16 08:48:40 +00001131#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1135 x = PyLong_AsLong(vv);
1136 else
1137 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001138#else
Tim Peters70128a12001-06-16 08:48:40 +00001139
Tim Peters70128a12001-06-16 08:48:40 +00001140#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001141# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001142#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001143 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1146 x = PyLong_AsLongLong(vv);
1147 else
1148 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001149
1150#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (x == -1 && PyErr_Occurred())
1153 return NULL;
1154 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001155}
1156
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001157/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001158 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001159 */
1160
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001161#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001162
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001163/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001164
1165PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001166PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001169 unsigned long long abs_ival;
1170 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 int ndigits = 0;
1172 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001173
animalize6b519982019-09-06 14:00:56 +08001174 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001175 return get_small_int((sdigit)ival);
1176 }
1177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (ival < 0) {
1179 /* avoid signed overflow on negation; see comments
1180 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001181 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 negative = 1;
1183 }
1184 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001185 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 /* Count the number of Python digits.
1189 We used to pick 5 ("big enough for anything"), but that's a
1190 waste of time and space given that 5*15 = 75 bits are rarely
1191 needed. */
1192 t = abs_ival;
1193 while (t) {
1194 ++ndigits;
1195 t >>= PyLong_SHIFT;
1196 }
1197 v = _PyLong_New(ndigits);
1198 if (v != NULL) {
1199 digit *p = v->ob_digit;
1200 Py_SIZE(v) = negative ? -ndigits : ndigits;
1201 t = abs_ival;
1202 while (t) {
1203 *p++ = (digit)(t & PyLong_MASK);
1204 t >>= PyLong_SHIFT;
1205 }
1206 }
1207 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001208}
1209
Serhiy Storchaka95949422013-08-27 19:40:23 +03001210/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001211
1212PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001213PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyLongObject *v;
1216 size_t abs_ival;
1217 size_t t; /* unsigned so >> doesn't propagate sign bit */
1218 int ndigits = 0;
1219 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001220
animalize6b519982019-09-06 14:00:56 +08001221 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001222 return get_small_int((sdigit)ival);
1223 }
1224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 if (ival < 0) {
1226 /* avoid signed overflow when ival = SIZE_T_MIN */
1227 abs_ival = (size_t)(-1-ival)+1;
1228 negative = 1;
1229 }
1230 else {
1231 abs_ival = (size_t)ival;
1232 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 /* Count the number of Python digits. */
1235 t = abs_ival;
1236 while (t) {
1237 ++ndigits;
1238 t >>= PyLong_SHIFT;
1239 }
1240 v = _PyLong_New(ndigits);
1241 if (v != NULL) {
1242 digit *p = v->ob_digit;
1243 Py_SIZE(v) = negative ? -ndigits : ndigits;
1244 t = abs_ival;
1245 while (t) {
1246 *p++ = (digit)(t & PyLong_MASK);
1247 t >>= PyLong_SHIFT;
1248 }
1249 }
1250 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001251}
1252
Serhiy Storchaka95949422013-08-27 19:40:23 +03001253/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001254 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001255
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001256long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001257PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001260 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001262 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (vv == NULL) {
1265 PyErr_BadInternalCall();
1266 return -1;
1267 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001268
1269 if (PyLong_Check(vv)) {
1270 v = (PyLongObject *)vv;
1271 }
1272 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001273 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001274 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001276 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001278
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001279 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001281 case -1:
1282 bytes = -(sdigit)v->ob_digit[0];
1283 break;
1284 case 0:
1285 bytes = 0;
1286 break;
1287 case 1:
1288 bytes = v->ob_digit[0];
1289 break;
1290 default:
1291 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001292 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001294 if (do_decref) {
1295 Py_DECREF(v);
1296 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001297
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001298 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001300 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 else
1302 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001303}
1304
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001305/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001306 Return -1 and set an error if overflow occurs. */
1307
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001308unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001309PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001312 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001314
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001315 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001317 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001319 if (!PyLong_Check(vv)) {
1320 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001321 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001322 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 v = (PyLongObject*)vv;
1325 switch(Py_SIZE(v)) {
1326 case 0: return 0;
1327 case 1: return v->ob_digit[0];
1328 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001329
Mark Dickinson22b20182010-05-10 21:27:53 +00001330 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001331 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001332
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001333 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001335 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 else
1337 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001338}
Tim Petersd1a7da62001-06-13 00:35:57 +00001339
Serhiy Storchaka95949422013-08-27 19:40:23 +03001340/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001341 Returns -1 and sets an error condition if an error occurs. */
1342
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001343static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001344_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001345{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001346 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001347 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 Py_ssize_t i;
1349 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 if (vv == NULL || !PyLong_Check(vv)) {
1352 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001353 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 }
1355 v = (PyLongObject *)vv;
1356 switch(Py_SIZE(v)) {
1357 case 0: return 0;
1358 case 1: return v->ob_digit[0];
1359 }
1360 i = Py_SIZE(v);
1361 sign = 1;
1362 x = 0;
1363 if (i < 0) {
1364 sign = -1;
1365 i = -i;
1366 }
1367 while (--i >= 0) {
1368 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1369 }
1370 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001371}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001372
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001373unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001374PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001377 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001378
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001379 if (op == NULL) {
1380 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001381 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001383
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001384 if (PyLong_Check(op)) {
1385 return _PyLong_AsUnsignedLongLongMask(op);
1386 }
1387
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001388 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001390 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001391
1392 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1393 Py_DECREF(lo);
1394 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001395}
Tim Petersd1a7da62001-06-13 00:35:57 +00001396
Serhiy Storchaka95949422013-08-27 19:40:23 +03001397/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001398 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001399
Mark Dickinson8d48b432011-10-23 20:47:14 +01001400 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1401 the result. Otherwise *overflow is 0.
1402
1403 For other errors (e.g., TypeError), return -1 and set an error condition.
1404 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001405*/
1406
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001407long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001408PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001411 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001412 unsigned long long x, prev;
1413 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 Py_ssize_t i;
1415 int sign;
1416 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 *overflow = 0;
1419 if (vv == NULL) {
1420 PyErr_BadInternalCall();
1421 return -1;
1422 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001423
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001424 if (PyLong_Check(vv)) {
1425 v = (PyLongObject *)vv;
1426 }
1427 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001428 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001429 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 return -1;
1431 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 switch (i) {
1438 case -1:
1439 res = -(sdigit)v->ob_digit[0];
1440 break;
1441 case 0:
1442 res = 0;
1443 break;
1444 case 1:
1445 res = v->ob_digit[0];
1446 break;
1447 default:
1448 sign = 1;
1449 x = 0;
1450 if (i < 0) {
1451 sign = -1;
1452 i = -(i);
1453 }
1454 while (--i >= 0) {
1455 prev = x;
1456 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1457 if ((x >> PyLong_SHIFT) != prev) {
1458 *overflow = sign;
1459 goto exit;
1460 }
1461 }
1462 /* Haven't lost any bits, but casting to long requires extra
1463 * care (see comment above).
1464 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001465 if (x <= (unsigned long long)PY_LLONG_MAX) {
1466 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 }
1468 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1469 res = PY_LLONG_MIN;
1470 }
1471 else {
1472 *overflow = sign;
1473 /* res is already set to -1 */
1474 }
1475 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001476 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001478 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 }
1480 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001481}
1482
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001483int
1484_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1485{
1486 unsigned long uval;
1487
1488 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1489 PyErr_SetString(PyExc_ValueError, "value must be positive");
1490 return 0;
1491 }
1492 uval = PyLong_AsUnsignedLong(obj);
1493 if (uval == (unsigned long)-1 && PyErr_Occurred())
1494 return 0;
1495 if (uval > USHRT_MAX) {
1496 PyErr_SetString(PyExc_OverflowError,
1497 "Python int too large for C unsigned short");
1498 return 0;
1499 }
1500
1501 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1502 return 1;
1503}
1504
1505int
1506_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1507{
1508 unsigned long uval;
1509
1510 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1511 PyErr_SetString(PyExc_ValueError, "value must be positive");
1512 return 0;
1513 }
1514 uval = PyLong_AsUnsignedLong(obj);
1515 if (uval == (unsigned long)-1 && PyErr_Occurred())
1516 return 0;
1517 if (uval > UINT_MAX) {
1518 PyErr_SetString(PyExc_OverflowError,
1519 "Python int too large for C unsigned int");
1520 return 0;
1521 }
1522
1523 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1524 return 1;
1525}
1526
1527int
1528_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1529{
1530 unsigned long uval;
1531
1532 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1533 PyErr_SetString(PyExc_ValueError, "value must be positive");
1534 return 0;
1535 }
1536 uval = PyLong_AsUnsignedLong(obj);
1537 if (uval == (unsigned long)-1 && PyErr_Occurred())
1538 return 0;
1539
1540 *(unsigned long *)ptr = uval;
1541 return 1;
1542}
1543
1544int
1545_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1546{
1547 unsigned long long uval;
1548
1549 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1550 PyErr_SetString(PyExc_ValueError, "value must be positive");
1551 return 0;
1552 }
1553 uval = PyLong_AsUnsignedLongLong(obj);
1554 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1555 return 0;
1556
1557 *(unsigned long long *)ptr = uval;
1558 return 1;
1559}
1560
1561int
1562_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1563{
1564 size_t uval;
1565
1566 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1567 PyErr_SetString(PyExc_ValueError, "value must be positive");
1568 return 0;
1569 }
1570 uval = PyLong_AsSize_t(obj);
1571 if (uval == (size_t)-1 && PyErr_Occurred())
1572 return 0;
1573
1574 *(size_t *)ptr = uval;
1575 return 1;
1576}
1577
1578
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001579#define CHECK_BINOP(v,w) \
1580 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001581 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1582 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001583 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001584
Tim Peters877a2122002-08-12 05:09:36 +00001585/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1586 * is modified in place, by adding y to it. Carries are propagated as far as
1587 * x[m-1], and the remaining carry (0 or 1) is returned.
1588 */
1589static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001590v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 Py_ssize_t i;
1593 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 assert(m >= n);
1596 for (i = 0; i < n; ++i) {
1597 carry += x[i] + y[i];
1598 x[i] = carry & PyLong_MASK;
1599 carry >>= PyLong_SHIFT;
1600 assert((carry & 1) == carry);
1601 }
1602 for (; carry && i < m; ++i) {
1603 carry += x[i];
1604 x[i] = carry & PyLong_MASK;
1605 carry >>= PyLong_SHIFT;
1606 assert((carry & 1) == carry);
1607 }
1608 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001609}
1610
1611/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1612 * is modified in place, by subtracting y from it. Borrows are propagated as
1613 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1614 */
1615static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001616v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 Py_ssize_t i;
1619 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 assert(m >= n);
1622 for (i = 0; i < n; ++i) {
1623 borrow = x[i] - y[i] - borrow;
1624 x[i] = borrow & PyLong_MASK;
1625 borrow >>= PyLong_SHIFT;
1626 borrow &= 1; /* keep only 1 sign bit */
1627 }
1628 for (; borrow && i < m; ++i) {
1629 borrow = x[i] - borrow;
1630 x[i] = borrow & PyLong_MASK;
1631 borrow >>= PyLong_SHIFT;
1632 borrow &= 1;
1633 }
1634 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001635}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001636
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001637/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1638 * result in z[0:m], and return the d bits shifted out of the top.
1639 */
1640static digit
1641v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 Py_ssize_t i;
1644 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 assert(0 <= d && d < PyLong_SHIFT);
1647 for (i=0; i < m; i++) {
1648 twodigits acc = (twodigits)a[i] << d | carry;
1649 z[i] = (digit)acc & PyLong_MASK;
1650 carry = (digit)(acc >> PyLong_SHIFT);
1651 }
1652 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001653}
1654
1655/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1656 * result in z[0:m], and return the d bits shifted out of the bottom.
1657 */
1658static digit
1659v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 Py_ssize_t i;
1662 digit carry = 0;
1663 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 assert(0 <= d && d < PyLong_SHIFT);
1666 for (i=m; i-- > 0;) {
1667 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1668 carry = (digit)acc & mask;
1669 z[i] = (digit)(acc >> d);
1670 }
1671 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001672}
1673
Tim Peters212e6142001-07-14 12:23:19 +00001674/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1675 in pout, and returning the remainder. pin and pout point at the LSD.
1676 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001677 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001678 immutable. */
1679
1680static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001681inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 assert(n > 0 && n <= PyLong_MASK);
1686 pin += size;
1687 pout += size;
1688 while (--size >= 0) {
1689 digit hi;
1690 rem = (rem << PyLong_SHIFT) | *--pin;
1691 *--pout = hi = (digit)(rem / n);
1692 rem -= (twodigits)hi * n;
1693 }
1694 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001695}
1696
Serhiy Storchaka95949422013-08-27 19:40:23 +03001697/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001698 (as function result) and the remainder (through *prem).
1699 The sign of a is ignored; n should not be zero. */
1700
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001701static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001702divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001703{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001704 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 assert(n > 0 && n <= PyLong_MASK);
1708 z = _PyLong_New(size);
1709 if (z == NULL)
1710 return NULL;
1711 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1712 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001713}
1714
Serhiy Storchaka95949422013-08-27 19:40:23 +03001715/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001716 string. (Return value is non-shared so that callers can modify the
1717 returned value if necessary.) */
1718
Victor Stinnerd3f08822012-05-29 12:57:52 +02001719static int
1720long_to_decimal_string_internal(PyObject *aa,
1721 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001722 _PyUnicodeWriter *writer,
1723 _PyBytesWriter *bytes_writer,
1724 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001727 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 Py_ssize_t size, strlen, size_a, i, j;
1729 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001731 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001732 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 a = (PyLongObject *)aa;
1735 if (a == NULL || !PyLong_Check(a)) {
1736 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001737 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001739 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 /* quick and dirty upper bound for the number of digits
1743 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 But log2(a) < size_a * PyLong_SHIFT, and
1748 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001749 > 3.3 * _PyLong_DECIMAL_SHIFT
1750
1751 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1752 size_a + size_a / d < size_a + size_a / floor(d),
1753 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1754 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001756 d = (33 * _PyLong_DECIMAL_SHIFT) /
1757 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1758 assert(size_a < PY_SSIZE_T_MAX/2);
1759 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 scratch = _PyLong_New(size);
1761 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001762 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 /* convert array of base _PyLong_BASE digits in pin to an array of
1765 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1766 Volume 2 (3rd edn), section 4.4, Method 1b). */
1767 pin = a->ob_digit;
1768 pout = scratch->ob_digit;
1769 size = 0;
1770 for (i = size_a; --i >= 0; ) {
1771 digit hi = pin[i];
1772 for (j = 0; j < size; j++) {
1773 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1774 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1775 pout[j] = (digit)(z - (twodigits)hi *
1776 _PyLong_DECIMAL_BASE);
1777 }
1778 while (hi) {
1779 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1780 hi /= _PyLong_DECIMAL_BASE;
1781 }
1782 /* check for keyboard interrupt */
1783 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001784 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001785 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001786 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 }
1788 /* pout should have at least one digit, so that the case when a = 0
1789 works correctly */
1790 if (size == 0)
1791 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 /* calculate exact length of output string, and allocate */
1794 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1795 tenpow = 10;
1796 rem = pout[size-1];
1797 while (rem >= tenpow) {
1798 tenpow *= 10;
1799 strlen++;
1800 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001801 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001802 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1803 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001804 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001805 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001806 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001808 else if (bytes_writer) {
1809 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1810 if (*bytes_str == NULL) {
1811 Py_DECREF(scratch);
1812 return -1;
1813 }
1814 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001815 else {
1816 str = PyUnicode_New(strlen, '9');
1817 if (str == NULL) {
1818 Py_DECREF(scratch);
1819 return -1;
1820 }
1821 kind = PyUnicode_KIND(str);
1822 }
1823
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001824#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001825 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001826 /* pout[0] through pout[size-2] contribute exactly \
1827 _PyLong_DECIMAL_SHIFT digits each */ \
1828 for (i=0; i < size - 1; i++) { \
1829 rem = pout[i]; \
1830 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1831 *--p = '0' + rem % 10; \
1832 rem /= 10; \
1833 } \
1834 } \
1835 /* pout[size-1]: always produce at least one decimal digit */ \
1836 rem = pout[i]; \
1837 do { \
1838 *--p = '0' + rem % 10; \
1839 rem /= 10; \
1840 } while (rem != 0); \
1841 \
1842 /* and sign */ \
1843 if (negative) \
1844 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001845 } while (0)
1846
1847#define WRITE_UNICODE_DIGITS(TYPE) \
1848 do { \
1849 if (writer) \
1850 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1851 else \
1852 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1853 \
1854 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001855 \
1856 /* check we've counted correctly */ \
1857 if (writer) \
1858 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1859 else \
1860 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1861 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001864 if (bytes_writer) {
1865 char *p = *bytes_str + strlen;
1866 WRITE_DIGITS(p);
1867 assert(p == *bytes_str);
1868 }
1869 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001870 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001871 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001873 else if (kind == PyUnicode_2BYTE_KIND) {
1874 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001875 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001876 }
1877 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001878 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001879 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001880 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001881 }
1882#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001883#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001886 if (writer) {
1887 writer->pos += strlen;
1888 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001889 else if (bytes_writer) {
1890 (*bytes_str) += strlen;
1891 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001892 else {
1893 assert(_PyUnicode_CheckConsistency(str, 1));
1894 *p_output = (PyObject *)str;
1895 }
1896 return 0;
1897}
1898
1899static PyObject *
1900long_to_decimal_string(PyObject *aa)
1901{
1902 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001903 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001904 return NULL;
1905 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001906}
1907
Serhiy Storchaka95949422013-08-27 19:40:23 +03001908/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001909 which should be one of 2, 8 or 16. Return a string object.
1910 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1911 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001912
Victor Stinnerd3f08822012-05-29 12:57:52 +02001913static int
1914long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001915 PyObject **p_output, _PyUnicodeWriter *writer,
1916 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001917{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001918 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001919 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001920 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001922 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001923 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001925
Victor Stinnerd3f08822012-05-29 12:57:52 +02001926 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 if (a == NULL || !PyLong_Check(a)) {
1928 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001929 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001931 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001932 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 /* Compute a rough upper bound for the length of the string */
1935 switch (base) {
1936 case 16:
1937 bits = 4;
1938 break;
1939 case 8:
1940 bits = 3;
1941 break;
1942 case 2:
1943 bits = 1;
1944 break;
1945 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001946 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001948
Mark Dickinsone2846542012-04-20 21:21:24 +01001949 /* Compute exact length 'sz' of output string. */
1950 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001951 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001952 }
1953 else {
1954 Py_ssize_t size_a_in_bits;
1955 /* Ensure overflow doesn't occur during computation of sz. */
1956 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1957 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001958 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001959 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001960 }
1961 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1962 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001963 /* Allow 1 character for a '-' sign. */
1964 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1965 }
1966 if (alternate) {
1967 /* 2 characters for prefix */
1968 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001969 }
1970
Victor Stinnerd3f08822012-05-29 12:57:52 +02001971 if (writer) {
1972 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1973 return -1;
1974 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001976 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001977 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1978 if (*bytes_str == NULL)
1979 return -1;
1980 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001982 v = PyUnicode_New(sz, 'x');
1983 if (v == NULL)
1984 return -1;
1985 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001987
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001988#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001989 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001990 if (size_a == 0) { \
1991 *--p = '0'; \
1992 } \
1993 else { \
1994 /* JRH: special case for power-of-2 bases */ \
1995 twodigits accum = 0; \
1996 int accumbits = 0; /* # of bits in accum */ \
1997 Py_ssize_t i; \
1998 for (i = 0; i < size_a; ++i) { \
1999 accum |= (twodigits)a->ob_digit[i] << accumbits; \
2000 accumbits += PyLong_SHIFT; \
2001 assert(accumbits >= bits); \
2002 do { \
2003 char cdigit; \
2004 cdigit = (char)(accum & (base - 1)); \
2005 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
2006 *--p = cdigit; \
2007 accumbits -= bits; \
2008 accum >>= bits; \
2009 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
2010 } \
2011 } \
2012 \
2013 if (alternate) { \
2014 if (base == 16) \
2015 *--p = 'x'; \
2016 else if (base == 8) \
2017 *--p = 'o'; \
2018 else /* (base == 2) */ \
2019 *--p = 'b'; \
2020 *--p = '0'; \
2021 } \
2022 if (negative) \
2023 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002024 } while (0)
2025
2026#define WRITE_UNICODE_DIGITS(TYPE) \
2027 do { \
2028 if (writer) \
2029 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
2030 else \
2031 p = (TYPE*)PyUnicode_DATA(v) + sz; \
2032 \
2033 WRITE_DIGITS(p); \
2034 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002035 if (writer) \
2036 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2037 else \
2038 assert(p == (TYPE*)PyUnicode_DATA(v)); \
2039 } while (0)
2040
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002041 if (bytes_writer) {
2042 char *p = *bytes_str + sz;
2043 WRITE_DIGITS(p);
2044 assert(p == *bytes_str);
2045 }
2046 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002047 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002048 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002049 }
2050 else if (kind == PyUnicode_2BYTE_KIND) {
2051 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002052 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002053 }
2054 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002055 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002056 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002057 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002058 }
2059#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002060#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002061
2062 if (writer) {
2063 writer->pos += sz;
2064 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002065 else if (bytes_writer) {
2066 (*bytes_str) += sz;
2067 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002068 else {
2069 assert(_PyUnicode_CheckConsistency(v, 1));
2070 *p_output = v;
2071 }
2072 return 0;
2073}
2074
2075PyObject *
2076_PyLong_Format(PyObject *obj, int base)
2077{
2078 PyObject *str;
2079 int err;
2080 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002081 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002082 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002083 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002084 if (err == -1)
2085 return NULL;
2086 return str;
2087}
2088
2089int
2090_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2091 PyObject *obj,
2092 int base, int alternate)
2093{
2094 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002095 return long_to_decimal_string_internal(obj, NULL, writer,
2096 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002097 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002098 return long_format_binary(obj, base, alternate, NULL, writer,
2099 NULL, NULL);
2100}
2101
2102char*
2103_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2104 PyObject *obj,
2105 int base, int alternate)
2106{
2107 char *str2;
2108 int res;
2109 str2 = str;
2110 if (base == 10)
2111 res = long_to_decimal_string_internal(obj, NULL, NULL,
2112 writer, &str2);
2113 else
2114 res = long_format_binary(obj, base, alternate, NULL, NULL,
2115 writer, &str2);
2116 if (res < 0)
2117 return NULL;
2118 assert(str2 != NULL);
2119 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002120}
2121
Thomas Wouters477c8d52006-05-27 19:21:47 +00002122/* Table of digit values for 8-bit string -> integer conversion.
2123 * '0' maps to 0, ..., '9' maps to 9.
2124 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2125 * All other indices map to 37.
2126 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002127 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002128 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002129unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2131 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2132 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2133 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2134 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2135 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2136 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2137 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2138 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2139 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2140 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2141 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2142 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2143 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2144 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2145 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002146};
2147
2148/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002149 * 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 +03002150 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002151 * The point to this routine is that it takes time linear in the number of
2152 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002153 *
2154 * Return values:
2155 * -1 on syntax error (exception needs to be set, *res is untouched)
2156 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002157 */
Brett Cannona721aba2016-09-09 14:57:09 -07002158static int
2159long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002160{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002161 const char *p = *str;
2162 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002163 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002164 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 int bits_per_char;
2166 Py_ssize_t n;
2167 PyLongObject *z;
2168 twodigits accum;
2169 int bits_in_accum;
2170 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2173 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002174 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002176 }
2177 /* count digits and set p to end-of-string */
2178 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2179 if (*p == '_') {
2180 if (prev == '_') {
2181 *str = p - 1;
2182 return -1;
2183 }
2184 } else {
2185 ++digits;
2186 }
2187 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002189 }
2190 if (prev == '_') {
2191 /* Trailing underscore not allowed. */
2192 *str = p - 1;
2193 return -1;
2194 }
2195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002197 /* n <- the number of Python digits needed,
2198 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2199 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyErr_SetString(PyExc_ValueError,
2201 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002202 *res = NULL;
2203 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002205 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002207 if (z == NULL) {
2208 *res = NULL;
2209 return 0;
2210 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002211 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 * from least to most significant in both.
2213 */
2214 accum = 0;
2215 bits_in_accum = 0;
2216 pdigit = z->ob_digit;
2217 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002218 int k;
2219 if (*p == '_') {
2220 continue;
2221 }
2222 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 assert(k >= 0 && k < base);
2224 accum |= (twodigits)k << bits_in_accum;
2225 bits_in_accum += bits_per_char;
2226 if (bits_in_accum >= PyLong_SHIFT) {
2227 *pdigit++ = (digit)(accum & PyLong_MASK);
2228 assert(pdigit - z->ob_digit <= n);
2229 accum >>= PyLong_SHIFT;
2230 bits_in_accum -= PyLong_SHIFT;
2231 assert(bits_in_accum < PyLong_SHIFT);
2232 }
2233 }
2234 if (bits_in_accum) {
2235 assert(bits_in_accum <= PyLong_SHIFT);
2236 *pdigit++ = (digit)accum;
2237 assert(pdigit - z->ob_digit <= n);
2238 }
2239 while (pdigit - z->ob_digit < n)
2240 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002241 *res = long_normalize(z);
2242 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002243}
2244
Serhiy Storchaka95949422013-08-27 19:40:23 +03002245/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002246 * ignored.
2247 *
2248 * If successful, a PyLong object will be returned and 'pend' will be pointing
2249 * to the first unused byte unless it's NULL.
2250 *
2251 * If unsuccessful, NULL will be returned.
2252 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002253PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002254PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002257 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 PyLongObject *z = NULL;
2259 PyObject *strobj;
2260 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 if ((base != 0 && base < 2) || base > 36) {
2263 PyErr_SetString(PyExc_ValueError,
2264 "int() arg 2 must be >= 2 and <= 36");
2265 return NULL;
2266 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002267 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002269 }
2270 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002272 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 else if (*str == '-') {
2274 ++str;
2275 sign = -1;
2276 }
2277 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002278 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002280 }
2281 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002283 }
2284 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002286 }
2287 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 else {
2291 /* "old" (C-style) octal literal, now invalid.
2292 it might still be zero though */
2293 error_if_nonzero = 1;
2294 base = 10;
2295 }
2296 }
2297 if (str[0] == '0' &&
2298 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2299 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002300 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002302 /* One underscore allowed here. */
2303 if (*str == '_') {
2304 ++str;
2305 }
2306 }
2307 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002308 /* May not start with underscores. */
2309 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002310 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002313 if ((base & (base - 1)) == 0) {
2314 int res = long_from_binary_base(&str, base, &z);
2315 if (res < 0) {
2316 /* Syntax error. */
2317 goto onError;
2318 }
2319 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002321/***
2322Binary bases can be converted in time linear in the number of digits, because
2323Python's representation base is binary. Other bases (including decimal!) use
2324the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002325
Thomas Wouters477c8d52006-05-27 19:21:47 +00002326First some math: the largest integer that can be expressed in N base-B digits
2327is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2328case number of Python digits needed to hold it is the smallest integer n s.t.
2329
2330 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2331 BASE**n >= B**N [taking logs to base BASE]
2332 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2333
2334The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002335this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002336and the result is computed into it.
2337
2338The input string is actually treated as being in base base**i (i.e., i digits
2339are processed at a time), where two more static arrays hold:
2340
2341 convwidth_base[base] = the largest integer i such that base**i <= BASE
2342 convmultmax_base[base] = base ** convwidth_base[base]
2343
2344The first of these is the largest i such that i consecutive input digits
2345must fit in a single Python digit. The second is effectively the input
2346base we're really using.
2347
2348Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2349convmultmax_base[base], the result is "simply"
2350
2351 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2352
2353where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002354
2355Error analysis: as above, the number of Python digits `n` needed is worst-
2356case
2357
2358 n >= N * log(B)/log(BASE)
2359
2360where `N` is the number of input digits in base `B`. This is computed via
2361
2362 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2363
2364below. Two numeric concerns are how much space this can waste, and whether
2365the computed result can be too small. To be concrete, assume BASE = 2**15,
2366which is the default (and it's unlikely anyone changes that).
2367
2368Waste isn't a problem: provided the first input digit isn't 0, the difference
2369between the worst-case input with N digits and the smallest input with N
2370digits is about a factor of B, but B is small compared to BASE so at most
2371one allocated Python digit can remain unused on that count. If
2372N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2373and adding 1 returns a result 1 larger than necessary. However, that can't
2374happen: whenever B is a power of 2, long_from_binary_base() is called
2375instead, and it's impossible for B**i to be an integer power of 2**15 when
2376B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2377an exact integer when B is not a power of 2, since B**i has a prime factor
2378other than 2 in that case, but (2**15)**j's only prime factor is 2).
2379
2380The computed result can be too small if the true value of N*log(B)/log(BASE)
2381is a little bit larger than an exact integer, but due to roundoff errors (in
2382computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2383yields a numeric result a little less than that integer. Unfortunately, "how
2384close can a transcendental function get to an integer over some range?"
2385questions are generally theoretically intractable. Computer analysis via
2386continued fractions is practical: expand log(B)/log(BASE) via continued
2387fractions, giving a sequence i/j of "the best" rational approximations. Then
2388j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2389we can get very close to being in trouble, but very rarely. For example,
239076573 is a denominator in one of the continued-fraction approximations to
2391log(10)/log(2**15), and indeed:
2392
2393 >>> log(10)/log(2**15)*76573
2394 16958.000000654003
2395
2396is very close to an integer. If we were working with IEEE single-precision,
2397rounding errors could kill us. Finding worst cases in IEEE double-precision
2398requires better-than-double-precision log() functions, and Tim didn't bother.
2399Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002400new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002401This should happen extremely rarely, and in fact I don't have a test case
2402that triggers it(!). Instead the code was tested by artificially allocating
2403just 1 digit at the start, so that the copying code was exercised for every
2404digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002405***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002406 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002408 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 int i;
2410 int convwidth;
2411 twodigits convmultmax, convmult;
2412 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002413 const char *scan, *lastdigit;
2414 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 static double log_base_BASE[37] = {0.0e0,};
2417 static int convwidth_base[37] = {0,};
2418 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 if (log_base_BASE[base] == 0.0) {
2421 twodigits convmax = base;
2422 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002423
Mark Dickinson22b20182010-05-10 21:27:53 +00002424 log_base_BASE[base] = (log((double)base) /
2425 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 for (;;) {
2427 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002428 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002430 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 convmax = next;
2432 ++i;
2433 }
2434 convmultmax_base[base] = convmax;
2435 assert(i > 0);
2436 convwidth_base[base] = i;
2437 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 /* Find length of the string of numeric characters. */
2440 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002441 lastdigit = str;
2442
2443 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2444 if (*scan == '_') {
2445 if (prev == '_') {
2446 /* Only one underscore allowed. */
2447 str = lastdigit + 1;
2448 goto onError;
2449 }
2450 }
2451 else {
2452 ++digits;
2453 lastdigit = scan;
2454 }
2455 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002457 }
2458 if (prev == '_') {
2459 /* Trailing underscore not allowed. */
2460 /* Set error pointer to first underscore. */
2461 str = lastdigit + 1;
2462 goto onError;
2463 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002464
Serhiy Storchaka95949422013-08-27 19:40:23 +03002465 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 * integer with this base and length. Note that there's no
2467 * need to initialize z->ob_digit -- no slot is read up before
2468 * being stored into.
2469 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002470 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2471 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002472 /* The same exception as in _PyLong_New(). */
2473 PyErr_SetString(PyExc_OverflowError,
2474 "too many digits in integer");
2475 return NULL;
2476 }
2477 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 /* Uncomment next line to test exceedingly rare copy code */
2479 /* size_z = 1; */
2480 assert(size_z > 0);
2481 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002482 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002484 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 /* `convwidth` consecutive input digits are treated as a single
2488 * digit in base `convmultmax`.
2489 */
2490 convwidth = convwidth_base[base];
2491 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 /* Work ;-) */
2494 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002495 if (*str == '_') {
2496 str++;
2497 continue;
2498 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 /* grab up to convwidth digits from the input string */
2500 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002501 for (i = 1; i < convwidth && str != scan; ++str) {
2502 if (*str == '_') {
2503 continue;
2504 }
2505 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002507 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 assert(c < PyLong_BASE);
2509 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 convmult = convmultmax;
2512 /* Calculate the shift only if we couldn't get
2513 * convwidth digits.
2514 */
2515 if (i != convwidth) {
2516 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002517 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002519 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 /* Multiply z by convmult, and add c. */
2523 pz = z->ob_digit;
2524 pzstop = pz + Py_SIZE(z);
2525 for (; pz < pzstop; ++pz) {
2526 c += (twodigits)*pz * convmult;
2527 *pz = (digit)(c & PyLong_MASK);
2528 c >>= PyLong_SHIFT;
2529 }
2530 /* carry off the current end? */
2531 if (c) {
2532 assert(c < PyLong_BASE);
2533 if (Py_SIZE(z) < size_z) {
2534 *pz = (digit)c;
2535 ++Py_SIZE(z);
2536 }
2537 else {
2538 PyLongObject *tmp;
2539 /* Extremely rare. Get more space. */
2540 assert(Py_SIZE(z) == size_z);
2541 tmp = _PyLong_New(size_z + 1);
2542 if (tmp == NULL) {
2543 Py_DECREF(z);
2544 return NULL;
2545 }
2546 memcpy(tmp->ob_digit,
2547 z->ob_digit,
2548 sizeof(digit) * size_z);
2549 Py_DECREF(z);
2550 z = tmp;
2551 z->ob_digit[size_z] = (digit)c;
2552 ++size_z;
2553 }
2554 }
2555 }
2556 }
Brett Cannona721aba2016-09-09 14:57:09 -07002557 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002559 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 if (error_if_nonzero) {
2561 /* reset the base to 0, else the exception message
2562 doesn't make too much sense */
2563 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002564 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002566 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 /* there might still be other problems, therefore base
2568 remains zero here for the same reason */
2569 }
Brett Cannona721aba2016-09-09 14:57:09 -07002570 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002572 }
2573 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002575 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002576 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002578 }
2579 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002581 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002583 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002584 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002585 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002586 }
2587 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002588 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002589 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002590 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002591
Mark Dickinson22b20182010-05-10 21:27:53 +00002592 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002593 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002594 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002595 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 Py_XDECREF(z);
2597 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2598 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002599 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002603 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 base, strobj);
2605 Py_DECREF(strobj);
2606 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002607}
2608
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002609/* Since PyLong_FromString doesn't have a length parameter,
2610 * check here for possible NULs in the string.
2611 *
2612 * Reports an invalid literal as a bytes object.
2613 */
2614PyObject *
2615_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2616{
2617 PyObject *result, *strobj;
2618 char *end = NULL;
2619
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002620 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002621 if (end == NULL || (result != NULL && end == s + len))
2622 return result;
2623 Py_XDECREF(result);
2624 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2625 if (strobj != NULL) {
2626 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002627 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002628 base, strobj);
2629 Py_DECREF(strobj);
2630 }
2631 return NULL;
2632}
2633
Guido van Rossum9e896b32000-04-05 20:11:21 +00002634PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002635PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002636{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002637 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 if (unicode == NULL)
2639 return NULL;
2640 v = PyLong_FromUnicodeObject(unicode, base);
2641 Py_DECREF(unicode);
2642 return v;
2643}
2644
2645PyObject *
2646PyLong_FromUnicodeObject(PyObject *u, int base)
2647{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002648 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002649 const char *buffer;
2650 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002651 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002653 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002654 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002656 assert(PyUnicode_IS_ASCII(asciidig));
2657 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002658 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002659 assert(buffer != NULL);
2660
2661 result = PyLong_FromString(buffer, &end, base);
2662 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002663 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002664 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002666 Py_DECREF(asciidig);
2667 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002668 PyErr_Format(PyExc_ValueError,
2669 "invalid literal for int() with base %d: %.200R",
2670 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002671 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002672}
2673
Tim Peters9f688bf2000-07-07 15:53:28 +00002674/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002675static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002677static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002678
Serhiy Storchaka95949422013-08-27 19:40:23 +03002679/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002680
Guido van Rossume32e0141992-01-19 16:31:05 +00002681static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002682long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002684{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002685 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 if (size_b == 0) {
2689 PyErr_SetString(PyExc_ZeroDivisionError,
2690 "integer division or modulo by zero");
2691 return -1;
2692 }
2693 if (size_a < size_b ||
2694 (size_a == size_b &&
2695 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2696 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002697 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002698 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002699 return -1;
2700 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002701 Py_INCREF(_PyLong_Zero);
2702 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 return 0;
2704 }
2705 if (size_b == 1) {
2706 digit rem = 0;
2707 z = divrem1(a, b->ob_digit[0], &rem);
2708 if (z == NULL)
2709 return -1;
2710 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2711 if (*prem == NULL) {
2712 Py_DECREF(z);
2713 return -1;
2714 }
2715 }
2716 else {
2717 z = x_divrem(a, b, prem);
2718 if (z == NULL)
2719 return -1;
2720 }
2721 /* Set the signs.
2722 The quotient z has the sign of a*b;
2723 the remainder r has the sign of a,
2724 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002725 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2726 _PyLong_Negate(&z);
2727 if (z == NULL) {
2728 Py_CLEAR(*prem);
2729 return -1;
2730 }
2731 }
2732 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2733 _PyLong_Negate(prem);
2734 if (*prem == NULL) {
2735 Py_DECREF(z);
2736 Py_CLEAR(*prem);
2737 return -1;
2738 }
2739 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 *pdiv = maybe_small_long(z);
2741 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002742}
2743
Serhiy Storchaka95949422013-08-27 19:40:23 +03002744/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002745 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002746
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002747static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002748x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 PyLongObject *v, *w, *a;
2751 Py_ssize_t i, k, size_v, size_w;
2752 int d;
2753 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2754 twodigits vv;
2755 sdigit zhi;
2756 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2759 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2760 handle the special case when the initial estimate q for a quotient
2761 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2762 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002765 size_v = Py_ABS(Py_SIZE(v1));
2766 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2768 v = _PyLong_New(size_v+1);
2769 if (v == NULL) {
2770 *prem = NULL;
2771 return NULL;
2772 }
2773 w = _PyLong_New(size_w);
2774 if (w == NULL) {
2775 Py_DECREF(v);
2776 *prem = NULL;
2777 return NULL;
2778 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2781 shift v1 left by the same amount. Results go into w and v. */
2782 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2783 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2784 assert(carry == 0);
2785 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2786 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2787 v->ob_digit[size_v] = carry;
2788 size_v++;
2789 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2792 at most (and usually exactly) k = size_v - size_w digits. */
2793 k = size_v - size_w;
2794 assert(k >= 0);
2795 a = _PyLong_New(k);
2796 if (a == NULL) {
2797 Py_DECREF(w);
2798 Py_DECREF(v);
2799 *prem = NULL;
2800 return NULL;
2801 }
2802 v0 = v->ob_digit;
2803 w0 = w->ob_digit;
2804 wm1 = w0[size_w-1];
2805 wm2 = w0[size_w-2];
2806 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2807 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2808 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002811 Py_DECREF(a);
2812 Py_DECREF(w);
2813 Py_DECREF(v);
2814 *prem = NULL;
2815 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002816 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 /* estimate quotient digit q; may overestimate by 1 (rare) */
2819 vtop = vk[size_w];
2820 assert(vtop <= wm1);
2821 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2822 q = (digit)(vv / wm1);
2823 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2824 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2825 | vk[size_w-2])) {
2826 --q;
2827 r += wm1;
2828 if (r >= PyLong_BASE)
2829 break;
2830 }
2831 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2834 zhi = 0;
2835 for (i = 0; i < size_w; ++i) {
2836 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2837 -PyLong_BASE * q <= z < PyLong_BASE */
2838 z = (sdigit)vk[i] + zhi -
2839 (stwodigits)q * (stwodigits)w0[i];
2840 vk[i] = (digit)z & PyLong_MASK;
2841 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002842 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 /* add w back if q was too large (this branch taken rarely) */
2846 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2847 if ((sdigit)vtop + zhi < 0) {
2848 carry = 0;
2849 for (i = 0; i < size_w; ++i) {
2850 carry += vk[i] + w0[i];
2851 vk[i] = carry & PyLong_MASK;
2852 carry >>= PyLong_SHIFT;
2853 }
2854 --q;
2855 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 /* store quotient digit */
2858 assert(q < PyLong_BASE);
2859 *--ak = q;
2860 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 /* unshift remainder; we reuse w to store the result */
2863 carry = v_rshift(w0, v0, size_w, d);
2864 assert(carry==0);
2865 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 *prem = long_normalize(w);
2868 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002869}
2870
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002871/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2872 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2873 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2874 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2875 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2876 -1.0. */
2877
2878/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2879#if DBL_MANT_DIG == 53
2880#define EXP2_DBL_MANT_DIG 9007199254740992.0
2881#else
2882#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2883#endif
2884
2885double
2886_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2889 /* See below for why x_digits is always large enough. */
2890 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2891 double dx;
2892 /* Correction term for round-half-to-even rounding. For a digit x,
2893 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2894 multiple of 4, rounding ties to a multiple of 8. */
2895 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002896
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002897 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 if (a_size == 0) {
2899 /* Special case for 0: significand 0.0, exponent 0. */
2900 *e = 0;
2901 return 0.0;
2902 }
2903 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2904 /* The following is an overflow-free version of the check
2905 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2906 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2907 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2908 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002909 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2913 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 Number of digits needed for result: write // for floor division.
2916 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2925 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2928 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2929 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 in both cases.
2936 */
2937 if (a_bits <= DBL_MANT_DIG + 2) {
2938 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2939 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2940 x_size = 0;
2941 while (x_size < shift_digits)
2942 x_digits[x_size++] = 0;
2943 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2944 (int)shift_bits);
2945 x_size += a_size;
2946 x_digits[x_size++] = rem;
2947 }
2948 else {
2949 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2950 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2951 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2952 a_size - shift_digits, (int)shift_bits);
2953 x_size = a_size - shift_digits;
2954 /* For correct rounding below, we need the least significant
2955 bit of x to be 'sticky' for this shift: if any of the bits
2956 shifted out was nonzero, we set the least significant bit
2957 of x. */
2958 if (rem)
2959 x_digits[0] |= 1;
2960 else
2961 while (shift_digits > 0)
2962 if (a->ob_digit[--shift_digits]) {
2963 x_digits[0] |= 1;
2964 break;
2965 }
2966 }
Victor Stinner63941882011-09-29 00:42:28 +02002967 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 /* Round, and convert to double. */
2970 x_digits[0] += half_even_correction[x_digits[0] & 7];
2971 dx = x_digits[--x_size];
2972 while (x_size > 0)
2973 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 /* Rescale; make correction if result is 1.0. */
2976 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2977 if (dx == 1.0) {
2978 if (a_bits == PY_SSIZE_T_MAX)
2979 goto overflow;
2980 dx = 0.5;
2981 a_bits += 1;
2982 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 *e = a_bits;
2985 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002986
2987 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 /* exponent > PY_SSIZE_T_MAX */
2989 PyErr_SetString(PyExc_OverflowError,
2990 "huge integer: number of bits overflows a Py_ssize_t");
2991 *e = 0;
2992 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002993}
2994
Serhiy Storchaka95949422013-08-27 19:40:23 +03002995/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002996 using the round-half-to-even rule in the case of a tie. */
2997
2998double
2999PyLong_AsDouble(PyObject *v)
3000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 Py_ssize_t exponent;
3002 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003003
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02003004 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 PyErr_BadInternalCall();
3006 return -1.0;
3007 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02003008 if (!PyLong_Check(v)) {
3009 PyErr_SetString(PyExc_TypeError, "an integer is required");
3010 return -1.0;
3011 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05003012 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05003013 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01003014 to double. This improves performance of FP/long operations
3015 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05003016 */
3017 return (double)MEDIUM_VALUE((PyLongObject *)v);
3018 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
3020 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
3021 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01003022 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 return -1.0;
3024 }
3025 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003026}
3027
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003028/* Methods */
3029
HongWeipeng42acb7b2019-09-18 23:10:15 +08003030/* if a < b, return a negative number
3031 if a == b, return 0
3032 if a > b, return a positive number */
3033
3034static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003035long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003036{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003037 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
3038 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003039 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08003040 sdigit diff = 0;
3041 while (--i >= 0) {
3042 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
3043 if (diff) {
3044 break;
3045 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003047 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003049 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003050}
3051
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003052static PyObject *
3053long_richcompare(PyObject *self, PyObject *other, int op)
3054{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003055 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 CHECK_BINOP(self, other);
3057 if (self == other)
3058 result = 0;
3059 else
3060 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003061 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003062}
3063
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003064static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003065long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003066{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003067 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 Py_ssize_t i;
3069 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 i = Py_SIZE(v);
3072 switch(i) {
3073 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3074 case 0: return 0;
3075 case 1: return v->ob_digit[0];
3076 }
3077 sign = 1;
3078 x = 0;
3079 if (i < 0) {
3080 sign = -1;
3081 i = -(i);
3082 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003084 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3085 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3086 _PyHASH_MODULUS.
3087
3088 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3089 amounts to a rotation of the bits of x. To see this, write
3090
3091 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3092
3093 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3094 PyLong_SHIFT bits of x (those that are shifted out of the
3095 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3096 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3097 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3098 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3099 congruent to y modulo _PyHASH_MODULUS. So
3100
3101 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3102
3103 The right-hand side is just the result of rotating the
3104 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3105 not all _PyHASH_BITS bits of x are 1s, the same is true
3106 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3107 the reduction of x*2**PyLong_SHIFT modulo
3108 _PyHASH_MODULUS. */
3109 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3110 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003112 if (x >= _PyHASH_MODULUS)
3113 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 }
3115 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003116 if (x == (Py_uhash_t)-1)
3117 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003118 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003119}
3120
3121
Serhiy Storchaka95949422013-08-27 19:40:23 +03003122/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003123
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003124static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003125x_add(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 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 /* Ensure a is the larger of the two: */
3133 if (size_a < size_b) {
3134 { PyLongObject *temp = a; a = b; b = temp; }
3135 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003136 size_a = size_b;
3137 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 }
3139 z = _PyLong_New(size_a+1);
3140 if (z == NULL)
3141 return NULL;
3142 for (i = 0; i < size_b; ++i) {
3143 carry += a->ob_digit[i] + b->ob_digit[i];
3144 z->ob_digit[i] = carry & PyLong_MASK;
3145 carry >>= PyLong_SHIFT;
3146 }
3147 for (; i < size_a; ++i) {
3148 carry += a->ob_digit[i];
3149 z->ob_digit[i] = carry & PyLong_MASK;
3150 carry >>= PyLong_SHIFT;
3151 }
3152 z->ob_digit[i] = carry;
3153 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003154}
3155
3156/* Subtract the absolute values of two integers. */
3157
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003158static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003159x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003160{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003161 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 PyLongObject *z;
3163 Py_ssize_t i;
3164 int sign = 1;
3165 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 /* Ensure a is the larger of the two: */
3168 if (size_a < size_b) {
3169 sign = -1;
3170 { PyLongObject *temp = a; a = b; b = temp; }
3171 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003172 size_a = size_b;
3173 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 }
3175 else if (size_a == size_b) {
3176 /* Find highest digit where a and b differ: */
3177 i = size_a;
3178 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3179 ;
3180 if (i < 0)
3181 return (PyLongObject *)PyLong_FromLong(0);
3182 if (a->ob_digit[i] < b->ob_digit[i]) {
3183 sign = -1;
3184 { PyLongObject *temp = a; a = b; b = temp; }
3185 }
3186 size_a = size_b = i+1;
3187 }
3188 z = _PyLong_New(size_a);
3189 if (z == NULL)
3190 return NULL;
3191 for (i = 0; i < size_b; ++i) {
3192 /* The following assumes unsigned arithmetic
3193 works module 2**N for some N>PyLong_SHIFT. */
3194 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3195 z->ob_digit[i] = borrow & PyLong_MASK;
3196 borrow >>= PyLong_SHIFT;
3197 borrow &= 1; /* Keep only one sign bit */
3198 }
3199 for (; i < size_a; ++i) {
3200 borrow = a->ob_digit[i] - borrow;
3201 z->ob_digit[i] = borrow & PyLong_MASK;
3202 borrow >>= PyLong_SHIFT;
3203 borrow &= 1; /* Keep only one sign bit */
3204 }
3205 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003206 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003207 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003208 }
HongWeipeng036fe852019-11-26 15:54:49 +08003209 return maybe_small_long(long_normalize(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_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +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_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003225 if (z != NULL) {
3226 /* x_add received at least one multiple-digit int,
3227 and thus z must be a multiple-digit int.
3228 That also means z is not an element of
3229 small_ints, so negating it in-place is safe. */
3230 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003232 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 }
3234 else
3235 z = x_sub(b, a);
3236 }
3237 else {
3238 if (Py_SIZE(b) < 0)
3239 z = x_sub(a, b);
3240 else
3241 z = x_add(a, b);
3242 }
3243 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003244}
3245
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003246static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003247long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003252
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003253 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003254 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 }
3256 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003257 if (Py_SIZE(b) < 0) {
3258 z = x_sub(b, a);
3259 }
3260 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003262 if (z != NULL) {
3263 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
3264 Py_SIZE(z) = -(Py_SIZE(z));
3265 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003266 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 }
3268 else {
3269 if (Py_SIZE(b) < 0)
3270 z = x_add(a, b);
3271 else
3272 z = x_sub(a, b);
3273 }
3274 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003275}
3276
Tim Peters5af4e6c2002-08-12 02:31:19 +00003277/* Grade school multiplication, ignoring the signs.
3278 * Returns the absolute value of the product, or NULL if error.
3279 */
3280static PyLongObject *
3281x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003284 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3285 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 z = _PyLong_New(size_a + size_b);
3289 if (z == NULL)
3290 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3293 if (a == b) {
3294 /* Efficient squaring per HAC, Algorithm 14.16:
3295 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3296 * Gives slightly less than a 2x speedup when a == b,
3297 * via exploiting that each entry in the multiplication
3298 * pyramid appears twice (except for the size_a squares).
3299 */
3300 for (i = 0; i < size_a; ++i) {
3301 twodigits carry;
3302 twodigits f = a->ob_digit[i];
3303 digit *pz = z->ob_digit + (i << 1);
3304 digit *pa = a->ob_digit + i + 1;
3305 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003308 Py_DECREF(z);
3309 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003310 });
Tim Peters0973b992004-08-29 22:16:50 +00003311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 carry = *pz + f * f;
3313 *pz++ = (digit)(carry & PyLong_MASK);
3314 carry >>= PyLong_SHIFT;
3315 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 /* Now f is added in twice in each column of the
3318 * pyramid it appears. Same as adding f<<1 once.
3319 */
3320 f <<= 1;
3321 while (pa < paend) {
3322 carry += *pz + *pa++ * f;
3323 *pz++ = (digit)(carry & PyLong_MASK);
3324 carry >>= PyLong_SHIFT;
3325 assert(carry <= (PyLong_MASK << 1));
3326 }
3327 if (carry) {
3328 carry += *pz;
3329 *pz++ = (digit)(carry & PyLong_MASK);
3330 carry >>= PyLong_SHIFT;
3331 }
3332 if (carry)
3333 *pz += (digit)(carry & PyLong_MASK);
3334 assert((carry >> PyLong_SHIFT) == 0);
3335 }
3336 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003337 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 for (i = 0; i < size_a; ++i) {
3339 twodigits carry = 0;
3340 twodigits f = a->ob_digit[i];
3341 digit *pz = z->ob_digit + i;
3342 digit *pb = b->ob_digit;
3343 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003346 Py_DECREF(z);
3347 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003348 });
Tim Peters0973b992004-08-29 22:16:50 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 while (pb < pbend) {
3351 carry += *pz + *pb++ * f;
3352 *pz++ = (digit)(carry & PyLong_MASK);
3353 carry >>= PyLong_SHIFT;
3354 assert(carry <= PyLong_MASK);
3355 }
3356 if (carry)
3357 *pz += (digit)(carry & PyLong_MASK);
3358 assert((carry >> PyLong_SHIFT) == 0);
3359 }
3360 }
3361 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003362}
3363
3364/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003365 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003366 split, and sets low and high such that abs(n) == (high << size) + low,
3367 viewing the shift as being by digits. The sign bit is ignored, and
3368 the return values are >= 0.
3369 Returns 0 on success, -1 on failure.
3370*/
3371static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003372kmul_split(PyLongObject *n,
3373 Py_ssize_t size,
3374 PyLongObject **high,
3375 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 PyLongObject *hi, *lo;
3378 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003379 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003380
Victor Stinner640c35c2013-06-04 23:14:37 +02003381 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 if ((hi = _PyLong_New(size_hi)) == NULL)
3385 return -1;
3386 if ((lo = _PyLong_New(size_lo)) == NULL) {
3387 Py_DECREF(hi);
3388 return -1;
3389 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3392 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 *high = long_normalize(hi);
3395 *low = long_normalize(lo);
3396 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003397}
3398
Tim Peters60004642002-08-12 22:01:34 +00003399static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3400
Tim Peters5af4e6c2002-08-12 02:31:19 +00003401/* Karatsuba multiplication. Ignores the input signs, and returns the
3402 * absolute value of the product (or NULL if error).
3403 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3404 */
3405static PyLongObject *
3406k_mul(PyLongObject *a, PyLongObject *b)
3407{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003408 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3409 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 PyLongObject *ah = NULL;
3411 PyLongObject *al = NULL;
3412 PyLongObject *bh = NULL;
3413 PyLongObject *bl = NULL;
3414 PyLongObject *ret = NULL;
3415 PyLongObject *t1, *t2, *t3;
3416 Py_ssize_t shift; /* the number of digits we split off */
3417 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3420 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3421 * Then the original product is
3422 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3423 * By picking X to be a power of 2, "*X" is just shifting, and it's
3424 * been reduced to 3 multiplies on numbers half the size.
3425 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 /* We want to split based on the larger number; fiddle so that b
3428 * is largest.
3429 */
3430 if (asize > bsize) {
3431 t1 = a;
3432 a = b;
3433 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 i = asize;
3436 asize = bsize;
3437 bsize = i;
3438 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 /* Use gradeschool math when either number is too small. */
3441 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3442 if (asize <= i) {
3443 if (asize == 0)
3444 return (PyLongObject *)PyLong_FromLong(0);
3445 else
3446 return x_mul(a, b);
3447 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 /* If a is small compared to b, splitting on b gives a degenerate
3450 * case with ah==0, and Karatsuba may be (even much) less efficient
3451 * than "grade school" then. However, we can still win, by viewing
3452 * b as a string of "big digits", each of width a->ob_size. That
3453 * leads to a sequence of balanced calls to k_mul.
3454 */
3455 if (2 * asize <= bsize)
3456 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 /* Split a & b into hi & lo pieces. */
3459 shift = bsize >> 1;
3460 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3461 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 if (a == b) {
3464 bh = ah;
3465 bl = al;
3466 Py_INCREF(bh);
3467 Py_INCREF(bl);
3468 }
3469 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 /* The plan:
3472 * 1. Allocate result space (asize + bsize digits: that's always
3473 * enough).
3474 * 2. Compute ah*bh, and copy into result at 2*shift.
3475 * 3. Compute al*bl, and copy into result at 0. Note that this
3476 * can't overlap with #2.
3477 * 4. Subtract al*bl from the result, starting at shift. This may
3478 * underflow (borrow out of the high digit), but we don't care:
3479 * we're effectively doing unsigned arithmetic mod
3480 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3481 * borrows and carries out of the high digit can be ignored.
3482 * 5. Subtract ah*bh from the result, starting at shift.
3483 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3484 * at shift.
3485 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 /* 1. Allocate result space. */
3488 ret = _PyLong_New(asize + bsize);
3489 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003490#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 /* Fill with trash, to catch reference to uninitialized digits. */
3492 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003493#endif
Tim Peters44121a62002-08-12 06:17:58 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3496 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3497 assert(Py_SIZE(t1) >= 0);
3498 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3499 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3500 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 /* Zero-out the digits higher than the ah*bh copy. */
3503 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3504 if (i)
3505 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3506 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 /* 3. t2 <- al*bl, and copy into the low digits. */
3509 if ((t2 = k_mul(al, bl)) == NULL) {
3510 Py_DECREF(t1);
3511 goto fail;
3512 }
3513 assert(Py_SIZE(t2) >= 0);
3514 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3515 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 /* Zero out remaining digits. */
3518 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3519 if (i)
3520 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3523 * because it's fresher in cache.
3524 */
3525 i = Py_SIZE(ret) - shift; /* # digits after shift */
3526 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3527 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3530 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3533 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3534 Py_DECREF(ah);
3535 Py_DECREF(al);
3536 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 if (a == b) {
3539 t2 = t1;
3540 Py_INCREF(t2);
3541 }
3542 else if ((t2 = x_add(bh, bl)) == NULL) {
3543 Py_DECREF(t1);
3544 goto fail;
3545 }
3546 Py_DECREF(bh);
3547 Py_DECREF(bl);
3548 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 t3 = k_mul(t1, t2);
3551 Py_DECREF(t1);
3552 Py_DECREF(t2);
3553 if (t3 == NULL) goto fail;
3554 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 /* Add t3. It's not obvious why we can't run out of room here.
3557 * See the (*) comment after this function.
3558 */
3559 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3560 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003563
Mark Dickinson22b20182010-05-10 21:27:53 +00003564 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 Py_XDECREF(ret);
3566 Py_XDECREF(ah);
3567 Py_XDECREF(al);
3568 Py_XDECREF(bh);
3569 Py_XDECREF(bl);
3570 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003571}
3572
Tim Petersd6974a52002-08-13 20:37:51 +00003573/* (*) Why adding t3 can't "run out of room" above.
3574
Tim Petersab86c2b2002-08-15 20:06:00 +00003575Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3576to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003577
Tim Petersab86c2b2002-08-15 20:06:00 +000035781. For any integer i, i = c(i/2) + f(i/2). In particular,
3579 bsize = c(bsize/2) + f(bsize/2).
35802. shift = f(bsize/2)
35813. asize <= bsize
35824. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3583 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003584
Tim Petersab86c2b2002-08-15 20:06:00 +00003585We allocated asize + bsize result digits, and add t3 into them at an offset
3586of shift. This leaves asize+bsize-shift allocated digit positions for t3
3587to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3588asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003589
Tim Petersab86c2b2002-08-15 20:06:00 +00003590bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3591at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003592
Tim Petersab86c2b2002-08-15 20:06:00 +00003593If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3594digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3595most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003596
Tim Petersab86c2b2002-08-15 20:06:00 +00003597The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003598
Tim Petersab86c2b2002-08-15 20:06:00 +00003599 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003600
Tim Petersab86c2b2002-08-15 20:06:00 +00003601and we have asize + c(bsize/2) available digit positions. We need to show
3602this is always enough. An instance of c(bsize/2) cancels out in both, so
3603the question reduces to whether asize digits is enough to hold
3604(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3605then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3606asize 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 +00003607digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003608asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003609c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3610is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3611bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003612
Tim Peters48d52c02002-08-14 17:07:32 +00003613Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3614clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3615ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003616*/
3617
Tim Peters60004642002-08-12 22:01:34 +00003618/* b has at least twice the digits of a, and a is big enough that Karatsuba
3619 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3620 * of slices, each with a->ob_size digits, and multiply the slices by a,
3621 * one at a time. This gives k_mul balanced inputs to work with, and is
3622 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003623 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003624 * single-width slice overlap between successive partial sums).
3625 */
3626static PyLongObject *
3627k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3628{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003629 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3630 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 Py_ssize_t nbdone; /* # of b digits already multiplied */
3632 PyLongObject *ret;
3633 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 assert(asize > KARATSUBA_CUTOFF);
3636 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 /* Allocate result space, and zero it out. */
3639 ret = _PyLong_New(asize + bsize);
3640 if (ret == NULL)
3641 return NULL;
3642 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 /* Successive slices of b are copied into bslice. */
3645 bslice = _PyLong_New(asize);
3646 if (bslice == NULL)
3647 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 nbdone = 0;
3650 while (bsize > 0) {
3651 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003652 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 /* Multiply the next slice of b by a. */
3655 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3656 nbtouse * sizeof(digit));
3657 Py_SIZE(bslice) = nbtouse;
3658 product = k_mul(a, bslice);
3659 if (product == NULL)
3660 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 /* Add into result. */
3663 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3664 product->ob_digit, Py_SIZE(product));
3665 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 bsize -= nbtouse;
3668 nbdone += nbtouse;
3669 }
Tim Peters60004642002-08-12 22:01:34 +00003670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 Py_DECREF(bslice);
3672 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003673
Mark Dickinson22b20182010-05-10 21:27:53 +00003674 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 Py_DECREF(ret);
3676 Py_XDECREF(bslice);
3677 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003678}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003679
3680static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003681long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003688 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003690 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 z = k_mul(a, b);
3694 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003695 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3696 _PyLong_Negate(&z);
3697 if (z == NULL)
3698 return NULL;
3699 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003701}
3702
Yury Selivanove0b23092016-02-11 10:26:27 -05003703/* Fast modulo division for single-digit longs. */
3704static PyObject *
3705fast_mod(PyLongObject *a, PyLongObject *b)
3706{
3707 sdigit left = a->ob_digit[0];
3708 sdigit right = b->ob_digit[0];
3709 sdigit mod;
3710
3711 assert(Py_ABS(Py_SIZE(a)) == 1);
3712 assert(Py_ABS(Py_SIZE(b)) == 1);
3713
3714 if (Py_SIZE(a) == Py_SIZE(b)) {
3715 /* 'a' and 'b' have the same sign. */
3716 mod = left % right;
3717 }
3718 else {
3719 /* Either 'a' or 'b' is negative. */
3720 mod = right - 1 - (left - 1) % right;
3721 }
3722
Victor Stinnerf963c132016-03-23 18:36:54 +01003723 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003724}
3725
3726/* Fast floor division for single-digit longs. */
3727static PyObject *
3728fast_floor_div(PyLongObject *a, PyLongObject *b)
3729{
3730 sdigit left = a->ob_digit[0];
3731 sdigit right = b->ob_digit[0];
3732 sdigit div;
3733
3734 assert(Py_ABS(Py_SIZE(a)) == 1);
3735 assert(Py_ABS(Py_SIZE(b)) == 1);
3736
3737 if (Py_SIZE(a) == Py_SIZE(b)) {
3738 /* 'a' and 'b' have the same sign. */
3739 div = left / right;
3740 }
3741 else {
3742 /* Either 'a' or 'b' is negative. */
3743 div = -1 - (left - 1) / right;
3744 }
3745
3746 return PyLong_FromLong(div);
3747}
3748
Guido van Rossume32e0141992-01-19 16:31:05 +00003749/* The / and % operators are now defined in terms of divmod().
3750 The expression a mod b has the value a - b*floor(a/b).
3751 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003752 |a| by |b|, with the sign of a. This is also expressed
3753 as a - b*trunc(a/b), if trunc truncates towards zero.
3754 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 a b a rem b a mod b
3756 13 10 3 3
3757 -13 10 -3 7
3758 13 -10 3 -7
3759 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003760 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003761 have different signs. We then subtract one from the 'div'
3762 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003763
Tim Peters47e52ee2004-08-30 02:44:38 +00003764/* Compute
3765 * *pdiv, *pmod = divmod(v, w)
3766 * NULL can be passed for pdiv or pmod, in which case that part of
3767 * the result is simply thrown away. The caller owns a reference to
3768 * each of these it requests (does not pass NULL for).
3769 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003770static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003771l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003775
Yury Selivanove0b23092016-02-11 10:26:27 -05003776 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3777 /* Fast path for single-digit longs */
3778 div = NULL;
3779 if (pdiv != NULL) {
3780 div = (PyLongObject *)fast_floor_div(v, w);
3781 if (div == NULL) {
3782 return -1;
3783 }
3784 }
3785 if (pmod != NULL) {
3786 mod = (PyLongObject *)fast_mod(v, w);
3787 if (mod == NULL) {
3788 Py_XDECREF(div);
3789 return -1;
3790 }
3791 *pmod = mod;
3792 }
3793 if (pdiv != NULL) {
3794 /* We only want to set `*pdiv` when `*pmod` is
3795 set successfully. */
3796 *pdiv = div;
3797 }
3798 return 0;
3799 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 if (long_divrem(v, w, &div, &mod) < 0)
3801 return -1;
3802 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3803 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3804 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 temp = (PyLongObject *) long_add(mod, w);
3806 Py_DECREF(mod);
3807 mod = temp;
3808 if (mod == NULL) {
3809 Py_DECREF(div);
3810 return -1;
3811 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003812 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3813 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 Py_DECREF(mod);
3815 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 return -1;
3817 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 Py_DECREF(div);
3819 div = temp;
3820 }
3821 if (pdiv != NULL)
3822 *pdiv = div;
3823 else
3824 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 if (pmod != NULL)
3827 *pmod = mod;
3828 else
3829 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003832}
3833
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003834static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003835long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003840
3841 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3842 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3843 }
3844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3846 div = NULL;
3847 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003848}
3849
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003850/* PyLong/PyLong -> float, with correctly rounded result. */
3851
3852#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3853#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3854
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003855static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003856long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 PyLongObject *a, *b, *x;
3859 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3860 digit mask, low;
3861 int inexact, negate, a_is_small, b_is_small;
3862 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 CHECK_BINOP(v, w);
3865 a = (PyLongObject *)v;
3866 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 /*
3869 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3872 1. choose a suitable integer 'shift'
3873 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3874 3. adjust x for correct rounding
3875 4. convert x to a double dx with the same value
3876 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3881 returns either 0.0 or -0.0, depending on the sign of b. For a and
3882 b both nonzero, ignore signs of a and b, and add the sign back in
3883 at the end. Now write a_bits and b_bits for the bit lengths of a
3884 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3885 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3890 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3891 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3892 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 1. The integer 'shift' is chosen so that x has the right number of
3897 bits for a double, plus two or three extra bits that will be used
3898 in the rounding decisions. Writing a_bits and b_bits for the
3899 number of significant bits in a and b respectively, a
3900 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 This is fine in the usual case, but if a/b is smaller than the
3905 smallest normal float then it can lead to double rounding on an
3906 IEEE 754 platform, giving incorrectly rounded results. So we
3907 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 2. The quantity x is computed by first shifting a (left -shift bits
3912 if shift <= 0, right shift bits if shift > 0) and then dividing by
3913 b. For both the shift and the division, we keep track of whether
3914 the result is inexact, in a flag 'inexact'; this information is
3915 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 With the choice of shift above, together with our assumption that
3918 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3919 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3922 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 For float representability, we need x/2**extra_bits <
3927 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3928 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 To round, we just modify the bottom digit of x in-place; this can
3933 end up giving a digit with value > PyLONG_MASK, but that's not a
3934 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 With the original choices for shift above, extra_bits will always
3937 be 2 or 3. Then rounding under the round-half-to-even rule, we
3938 round up iff the most significant of the extra bits is 1, and
3939 either: (a) the computation of x in step 2 had an inexact result,
3940 or (b) at least one other of the extra bits is 1, or (c) the least
3941 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 4. Conversion to a double is straightforward; all floating-point
3944 operations involved in the conversion are exact, so there's no
3945 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3948 The result will always be exactly representable as a double, except
3949 in the case that it overflows. To avoid dependence on the exact
3950 behaviour of ldexp on overflow, we check for overflow before
3951 applying ldexp. The result of ldexp is adjusted for sign before
3952 returning.
3953 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003956 a_size = Py_ABS(Py_SIZE(a));
3957 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3959 if (b_size == 0) {
3960 PyErr_SetString(PyExc_ZeroDivisionError,
3961 "division by zero");
3962 goto error;
3963 }
3964 if (a_size == 0)
3965 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 /* Fast path for a and b small (exactly representable in a double).
3968 Relies on floating-point division being correctly rounded; results
3969 may be subject to double rounding on x86 machines that operate with
3970 the x87 FPU set to 64-bit precision. */
3971 a_is_small = a_size <= MANT_DIG_DIGITS ||
3972 (a_size == MANT_DIG_DIGITS+1 &&
3973 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3974 b_is_small = b_size <= MANT_DIG_DIGITS ||
3975 (b_size == MANT_DIG_DIGITS+1 &&
3976 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3977 if (a_is_small && b_is_small) {
3978 double da, db;
3979 da = a->ob_digit[--a_size];
3980 while (a_size > 0)
3981 da = da * PyLong_BASE + a->ob_digit[--a_size];
3982 db = b->ob_digit[--b_size];
3983 while (b_size > 0)
3984 db = db * PyLong_BASE + b->ob_digit[--b_size];
3985 result = da / db;
3986 goto success;
3987 }
Tim Peterse2a60002001-09-04 06:17:36 +00003988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 /* Catch obvious cases of underflow and overflow */
3990 diff = a_size - b_size;
3991 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3992 /* Extreme overflow */
3993 goto overflow;
3994 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3995 /* Extreme underflow */
3996 goto underflow_or_zero;
3997 /* Next line is now safe from overflowing a Py_ssize_t */
3998 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3999 bits_in_digit(b->ob_digit[b_size - 1]);
4000 /* Now diff = a_bits - b_bits. */
4001 if (diff > DBL_MAX_EXP)
4002 goto overflow;
4003 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
4004 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004007 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 /* x = abs(a * 2**-shift) */
4012 if (shift <= 0) {
4013 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
4014 digit rem;
4015 /* x = a << -shift */
4016 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
4017 /* In practice, it's probably impossible to end up
4018 here. Both a and b would have to be enormous,
4019 using close to SIZE_T_MAX bytes of memory each. */
4020 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004021 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 goto error;
4023 }
4024 x = _PyLong_New(a_size + shift_digits + 1);
4025 if (x == NULL)
4026 goto error;
4027 for (i = 0; i < shift_digits; i++)
4028 x->ob_digit[i] = 0;
4029 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
4030 a_size, -shift % PyLong_SHIFT);
4031 x->ob_digit[a_size + shift_digits] = rem;
4032 }
4033 else {
4034 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
4035 digit rem;
4036 /* x = a >> shift */
4037 assert(a_size >= shift_digits);
4038 x = _PyLong_New(a_size - shift_digits);
4039 if (x == NULL)
4040 goto error;
4041 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4042 a_size - shift_digits, shift % PyLong_SHIFT);
4043 /* set inexact if any of the bits shifted out is nonzero */
4044 if (rem)
4045 inexact = 1;
4046 while (!inexact && shift_digits > 0)
4047 if (a->ob_digit[--shift_digits])
4048 inexact = 1;
4049 }
4050 long_normalize(x);
4051 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4054 reference to x, so it's safe to modify it in-place. */
4055 if (b_size == 1) {
4056 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4057 b->ob_digit[0]);
4058 long_normalize(x);
4059 if (rem)
4060 inexact = 1;
4061 }
4062 else {
4063 PyLongObject *div, *rem;
4064 div = x_divrem(x, b, &rem);
4065 Py_DECREF(x);
4066 x = div;
4067 if (x == NULL)
4068 goto error;
4069 if (Py_SIZE(rem))
4070 inexact = 1;
4071 Py_DECREF(rem);
4072 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004073 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 assert(x_size > 0); /* result of division is never zero */
4075 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004078 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 /* Round by directly modifying the low digit of x. */
4082 mask = (digit)1 << (extra_bits - 1);
4083 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004084 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004086 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 /* Convert x to a double dx; the conversion is exact. */
4089 dx = x->ob_digit[--x_size];
4090 while (x_size > 0)
4091 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4092 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 /* Check whether ldexp result will overflow a double. */
4095 if (shift + x_bits >= DBL_MAX_EXP &&
4096 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4097 goto overflow;
4098 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004099
4100 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004102
4103 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004105
4106 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 PyErr_SetString(PyExc_OverflowError,
4108 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004109 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004111}
4112
4113static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004114long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 CHECK_BINOP(a, b);
4119
Yury Selivanove0b23092016-02-11 10:26:27 -05004120 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4121 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4122 }
4123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4125 mod = NULL;
4126 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004127}
4128
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004129static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004130long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 PyLongObject *div, *mod;
4133 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4138 return NULL;
4139 }
4140 z = PyTuple_New(2);
4141 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004142 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4143 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 }
4145 else {
4146 Py_DECREF(div);
4147 Py_DECREF(mod);
4148 }
4149 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004150}
4151
Mark Dickinsonc5299672019-06-02 10:24:06 +01004152
4153/* Compute an inverse to a modulo n, or raise ValueError if a is not
4154 invertible modulo n. Assumes n is positive. The inverse returned
4155 is whatever falls out of the extended Euclidean algorithm: it may
4156 be either positive or negative, but will be smaller than n in
4157 absolute value.
4158
4159 Pure Python equivalent for long_invmod:
4160
4161 def invmod(a, n):
4162 b, c = 1, 0
4163 while n:
4164 q, r = divmod(a, n)
4165 a, b, c, n = n, c, b - q*c, r
4166
4167 # at this point a is the gcd of the original inputs
4168 if a == 1:
4169 return b
4170 raise ValueError("Not invertible")
4171*/
4172
4173static PyLongObject *
4174long_invmod(PyLongObject *a, PyLongObject *n)
4175{
4176 PyLongObject *b, *c;
4177
4178 /* Should only ever be called for positive n */
4179 assert(Py_SIZE(n) > 0);
4180
4181 b = (PyLongObject *)PyLong_FromLong(1L);
4182 if (b == NULL) {
4183 return NULL;
4184 }
4185 c = (PyLongObject *)PyLong_FromLong(0L);
4186 if (c == NULL) {
4187 Py_DECREF(b);
4188 return NULL;
4189 }
4190 Py_INCREF(a);
4191 Py_INCREF(n);
4192
4193 /* references now owned: a, b, c, n */
4194 while (Py_SIZE(n) != 0) {
4195 PyLongObject *q, *r, *s, *t;
4196
4197 if (l_divmod(a, n, &q, &r) == -1) {
4198 goto Error;
4199 }
4200 Py_DECREF(a);
4201 a = n;
4202 n = r;
4203 t = (PyLongObject *)long_mul(q, c);
4204 Py_DECREF(q);
4205 if (t == NULL) {
4206 goto Error;
4207 }
4208 s = (PyLongObject *)long_sub(b, t);
4209 Py_DECREF(t);
4210 if (s == NULL) {
4211 goto Error;
4212 }
4213 Py_DECREF(b);
4214 b = c;
4215 c = s;
4216 }
4217 /* references now owned: a, b, c, n */
4218
4219 Py_DECREF(c);
4220 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004221 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004222 /* a != 1; we don't have an inverse. */
4223 Py_DECREF(a);
4224 Py_DECREF(b);
4225 PyErr_SetString(PyExc_ValueError,
4226 "base is not invertible for the given modulus");
4227 return NULL;
4228 }
4229 else {
4230 /* a == 1; b gives an inverse modulo n */
4231 Py_DECREF(a);
4232 return b;
4233 }
4234
4235 Error:
4236 Py_DECREF(a);
4237 Py_DECREF(b);
4238 Py_DECREF(c);
4239 Py_DECREF(n);
4240 return NULL;
4241}
4242
4243
Tim Peters47e52ee2004-08-30 02:44:38 +00004244/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004245static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004246long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4249 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 PyLongObject *z = NULL; /* accumulated result */
4252 Py_ssize_t i, j, k; /* counters */
4253 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 /* 5-ary values. If the exponent is large enough, table is
4256 * precomputed so that table[i] == a**i % c for i in range(32).
4257 */
4258 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4259 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 /* a, b, c = v, w, x */
4262 CHECK_BINOP(v, w);
4263 a = (PyLongObject*)v; Py_INCREF(a);
4264 b = (PyLongObject*)w; Py_INCREF(b);
4265 if (PyLong_Check(x)) {
4266 c = (PyLongObject *)x;
4267 Py_INCREF(x);
4268 }
4269 else if (x == Py_None)
4270 c = NULL;
4271 else {
4272 Py_DECREF(a);
4273 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004274 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 }
Tim Peters4c483c42001-09-05 06:24:58 +00004276
Mark Dickinsonc5299672019-06-02 10:24:06 +01004277 if (Py_SIZE(b) < 0 && c == NULL) {
4278 /* if exponent is negative and there's no modulus:
4279 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 that this calls float_pow() which converts its
4281 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004282 Py_DECREF(a);
4283 Py_DECREF(b);
4284 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 if (c) {
4288 /* if modulus == 0:
4289 raise ValueError() */
4290 if (Py_SIZE(c) == 0) {
4291 PyErr_SetString(PyExc_ValueError,
4292 "pow() 3rd argument cannot be 0");
4293 goto Error;
4294 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 /* if modulus < 0:
4297 negativeOutput = True
4298 modulus = -modulus */
4299 if (Py_SIZE(c) < 0) {
4300 negativeOutput = 1;
4301 temp = (PyLongObject *)_PyLong_Copy(c);
4302 if (temp == NULL)
4303 goto Error;
4304 Py_DECREF(c);
4305 c = temp;
4306 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004307 _PyLong_Negate(&c);
4308 if (c == NULL)
4309 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 /* if modulus == 1:
4313 return 0 */
4314 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4315 z = (PyLongObject *)PyLong_FromLong(0L);
4316 goto Done;
4317 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004318
Mark Dickinsonc5299672019-06-02 10:24:06 +01004319 /* if exponent is negative, negate the exponent and
4320 replace the base with a modular inverse */
4321 if (Py_SIZE(b) < 0) {
4322 temp = (PyLongObject *)_PyLong_Copy(b);
4323 if (temp == NULL)
4324 goto Error;
4325 Py_DECREF(b);
4326 b = temp;
4327 temp = NULL;
4328 _PyLong_Negate(&b);
4329 if (b == NULL)
4330 goto Error;
4331
4332 temp = long_invmod(a, c);
4333 if (temp == NULL)
4334 goto Error;
4335 Py_DECREF(a);
4336 a = temp;
4337 }
4338
Tim Peters81a93152013-10-05 16:53:52 -05004339 /* Reduce base by modulus in some cases:
4340 1. If base < 0. Forcing the base non-negative makes things easier.
4341 2. If base is obviously larger than the modulus. The "small
4342 exponent" case later can multiply directly by base repeatedly,
4343 while the "large exponent" case multiplies directly by base 31
4344 times. It can be unboundedly faster to multiply by
4345 base % modulus instead.
4346 We could _always_ do this reduction, but l_divmod() isn't cheap,
4347 so we only do it when it buys something. */
4348 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 if (l_divmod(a, c, NULL, &temp) < 0)
4350 goto Error;
4351 Py_DECREF(a);
4352 a = temp;
4353 temp = NULL;
4354 }
4355 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 /* At this point a, b, and c are guaranteed non-negative UNLESS
4358 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 z = (PyLongObject *)PyLong_FromLong(1L);
4361 if (z == NULL)
4362 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 /* Perform a modular reduction, X = X % c, but leave X alone if c
4365 * is NULL.
4366 */
4367#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004368 do { \
4369 if (c != NULL) { \
4370 if (l_divmod(X, c, NULL, &temp) < 0) \
4371 goto Error; \
4372 Py_XDECREF(X); \
4373 X = temp; \
4374 temp = NULL; \
4375 } \
4376 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 /* Multiply two values, then reduce the result:
4379 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004380#define MULT(X, Y, result) \
4381 do { \
4382 temp = (PyLongObject *)long_mul(X, Y); \
4383 if (temp == NULL) \
4384 goto Error; \
4385 Py_XDECREF(result); \
4386 result = temp; \
4387 temp = NULL; \
4388 REDUCE(result); \
4389 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4392 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4393 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4394 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4395 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004398 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004400 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 }
4402 }
4403 }
4404 else {
4405 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4406 Py_INCREF(z); /* still holds 1L */
4407 table[0] = z;
4408 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004409 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4412 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4415 const int index = (bi >> j) & 0x1f;
4416 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004417 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004419 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 }
4421 }
4422 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 if (negativeOutput && (Py_SIZE(z) != 0)) {
4425 temp = (PyLongObject *)long_sub(z, c);
4426 if (temp == NULL)
4427 goto Error;
4428 Py_DECREF(z);
4429 z = temp;
4430 temp = NULL;
4431 }
4432 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004433
Mark Dickinson22b20182010-05-10 21:27:53 +00004434 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004435 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004437 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4439 for (i = 0; i < 32; ++i)
4440 Py_XDECREF(table[i]);
4441 }
4442 Py_DECREF(a);
4443 Py_DECREF(b);
4444 Py_XDECREF(c);
4445 Py_XDECREF(temp);
4446 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004447}
4448
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004449static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004450long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 /* Implement ~x as -(x+1) */
4453 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004454 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004456 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 if (x == NULL)
4458 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004459 _PyLong_Negate(&x);
4460 /* No need for maybe_small_long here, since any small
4461 longs will have been caught in the Py_SIZE <= 1 fast path. */
4462 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004463}
4464
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004465static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004466long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004469 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 return PyLong_FromLong(-MEDIUM_VALUE(v));
4471 z = (PyLongObject *)_PyLong_Copy(v);
4472 if (z != NULL)
4473 Py_SIZE(z) = -(Py_SIZE(v));
4474 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004475}
4476
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004477static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004478long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 if (Py_SIZE(v) < 0)
4481 return long_neg(v);
4482 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004483 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004484}
4485
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004486static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004487long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004490}
4491
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004492/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4493static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004494divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004495{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004496 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004497 assert(Py_SIZE(shiftby) >= 0);
4498 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4499 if (lshiftby >= 0) {
4500 *wordshift = lshiftby / PyLong_SHIFT;
4501 *remshift = lshiftby % PyLong_SHIFT;
4502 return 0;
4503 }
4504 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4505 be that PyLong_AsSsize_t raised an OverflowError. */
4506 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4507 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004508 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004509 if (wordshift_obj == NULL) {
4510 return -1;
4511 }
4512 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4513 Py_DECREF(wordshift_obj);
4514 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4515 return 0;
4516 }
4517 PyErr_Clear();
4518 /* Clip the value. With such large wordshift the right shift
4519 returns 0 and the left shift raises an error in _PyLong_New(). */
4520 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4521 *remshift = 0;
4522 return 0;
4523}
4524
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004525static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004526long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004529 Py_ssize_t newsize, hishift, i, j;
4530 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 if (Py_SIZE(a) < 0) {
4533 /* Right shifting negative numbers is harder */
4534 PyLongObject *a1, *a2;
4535 a1 = (PyLongObject *) long_invert(a);
4536 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004537 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004538 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 Py_DECREF(a1);
4540 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004541 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 z = (PyLongObject *) long_invert(a2);
4543 Py_DECREF(a2);
4544 }
4545 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004546 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 if (newsize <= 0)
4548 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004549 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 lomask = ((digit)1 << hishift) - 1;
4551 himask = PyLong_MASK ^ lomask;
4552 z = _PyLong_New(newsize);
4553 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004554 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004556 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004558 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004560 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004562 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004563}
4564
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004565static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004566long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004567{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004568 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004569 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004572
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004573 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004575 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004577 if (Py_SIZE(a) == 0) {
4578 return PyLong_FromLong(0);
4579 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004580 if (divmod_shift(b, &wordshift, &remshift) < 0)
4581 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004582 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4583}
4584
4585/* Return a >> shiftby. */
4586PyObject *
4587_PyLong_Rshift(PyObject *a, size_t shiftby)
4588{
4589 Py_ssize_t wordshift;
4590 digit remshift;
4591
4592 assert(PyLong_Check(a));
4593 if (Py_SIZE(a) == 0) {
4594 return PyLong_FromLong(0);
4595 }
4596 wordshift = shiftby / PyLong_SHIFT;
4597 remshift = shiftby % PyLong_SHIFT;
4598 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4599}
4600
4601static PyObject *
4602long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4603{
4604 /* This version due to Tim Peters */
4605 PyLongObject *z = NULL;
4606 Py_ssize_t oldsize, newsize, i, j;
4607 twodigits accum;
4608
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004609 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004610 newsize = oldsize + wordshift;
4611 if (remshift)
4612 ++newsize;
4613 z = _PyLong_New(newsize);
4614 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004615 return NULL;
4616 if (Py_SIZE(a) < 0) {
4617 assert(Py_REFCNT(z) == 1);
4618 Py_SIZE(z) = -Py_SIZE(z);
4619 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 for (i = 0; i < wordshift; i++)
4621 z->ob_digit[i] = 0;
4622 accum = 0;
4623 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4624 accum |= (twodigits)a->ob_digit[j] << remshift;
4625 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4626 accum >>= PyLong_SHIFT;
4627 }
4628 if (remshift)
4629 z->ob_digit[newsize-1] = (digit)accum;
4630 else
4631 assert(!accum);
4632 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004634}
4635
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004636static PyObject *
4637long_lshift(PyObject *a, PyObject *b)
4638{
4639 Py_ssize_t wordshift;
4640 digit remshift;
4641
4642 CHECK_BINOP(a, b);
4643
4644 if (Py_SIZE(b) < 0) {
4645 PyErr_SetString(PyExc_ValueError, "negative shift count");
4646 return NULL;
4647 }
4648 if (Py_SIZE(a) == 0) {
4649 return PyLong_FromLong(0);
4650 }
4651 if (divmod_shift(b, &wordshift, &remshift) < 0)
4652 return NULL;
4653 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4654}
4655
4656/* Return a << shiftby. */
4657PyObject *
4658_PyLong_Lshift(PyObject *a, size_t shiftby)
4659{
4660 Py_ssize_t wordshift;
4661 digit remshift;
4662
4663 assert(PyLong_Check(a));
4664 if (Py_SIZE(a) == 0) {
4665 return PyLong_FromLong(0);
4666 }
4667 wordshift = shiftby / PyLong_SHIFT;
4668 remshift = shiftby % PyLong_SHIFT;
4669 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4670}
4671
Mark Dickinson27a87a22009-10-25 20:43:34 +00004672/* Compute two's complement of digit vector a[0:m], writing result to
4673 z[0:m]. The digit vector a need not be normalized, but should not
4674 be entirely zero. a and z may point to the same digit vector. */
4675
4676static void
4677v_complement(digit *z, digit *a, Py_ssize_t m)
4678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 Py_ssize_t i;
4680 digit carry = 1;
4681 for (i = 0; i < m; ++i) {
4682 carry += a[i] ^ PyLong_MASK;
4683 z[i] = carry & PyLong_MASK;
4684 carry >>= PyLong_SHIFT;
4685 }
4686 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004687}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004688
4689/* Bitwise and/xor/or operations */
4690
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004691static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004692long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004693 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004694 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 int nega, negb, negz;
4697 Py_ssize_t size_a, size_b, size_z, i;
4698 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700 /* Bitwise operations for negative numbers operate as though
4701 on a two's complement representation. So convert arguments
4702 from sign-magnitude to two's complement, and convert the
4703 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004706 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 nega = Py_SIZE(a) < 0;
4708 if (nega) {
4709 z = _PyLong_New(size_a);
4710 if (z == NULL)
4711 return NULL;
4712 v_complement(z->ob_digit, a->ob_digit, size_a);
4713 a = z;
4714 }
4715 else
4716 /* Keep reference count consistent. */
4717 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004720 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 negb = Py_SIZE(b) < 0;
4722 if (negb) {
4723 z = _PyLong_New(size_b);
4724 if (z == NULL) {
4725 Py_DECREF(a);
4726 return NULL;
4727 }
4728 v_complement(z->ob_digit, b->ob_digit, size_b);
4729 b = z;
4730 }
4731 else
4732 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 /* Swap a and b if necessary to ensure size_a >= size_b. */
4735 if (size_a < size_b) {
4736 z = a; a = b; b = z;
4737 size_z = size_a; size_a = size_b; size_b = size_z;
4738 negz = nega; nega = negb; negb = negz;
4739 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 /* JRH: The original logic here was to allocate the result value (z)
4742 as the longer of the two operands. However, there are some cases
4743 where the result is guaranteed to be shorter than that: AND of two
4744 positives, OR of two negatives: use the shorter number. AND with
4745 mixed signs: use the positive number. OR with mixed signs: use the
4746 negative number.
4747 */
4748 switch (op) {
4749 case '^':
4750 negz = nega ^ negb;
4751 size_z = size_a;
4752 break;
4753 case '&':
4754 negz = nega & negb;
4755 size_z = negb ? size_a : size_b;
4756 break;
4757 case '|':
4758 negz = nega | negb;
4759 size_z = negb ? size_b : size_a;
4760 break;
4761 default:
stratakisa10d4262019-03-18 18:59:20 +01004762 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 /* We allow an extra digit if z is negative, to make sure that
4766 the final two's complement of z doesn't overflow. */
4767 z = _PyLong_New(size_z + negz);
4768 if (z == NULL) {
4769 Py_DECREF(a);
4770 Py_DECREF(b);
4771 return NULL;
4772 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 /* Compute digits for overlap of a and b. */
4775 switch(op) {
4776 case '&':
4777 for (i = 0; i < size_b; ++i)
4778 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4779 break;
4780 case '|':
4781 for (i = 0; i < size_b; ++i)
4782 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4783 break;
4784 case '^':
4785 for (i = 0; i < size_b; ++i)
4786 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4787 break;
4788 default:
stratakisa10d4262019-03-18 18:59:20 +01004789 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004792 /* Copy any remaining digits of a, inverting if necessary. */
4793 if (op == '^' && negb)
4794 for (; i < size_z; ++i)
4795 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4796 else if (i < size_z)
4797 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4798 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 /* Complement result if negative. */
4801 if (negz) {
4802 Py_SIZE(z) = -(Py_SIZE(z));
4803 z->ob_digit[size_z] = PyLong_MASK;
4804 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4805 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 Py_DECREF(a);
4808 Py_DECREF(b);
4809 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004810}
4811
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004812static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004813long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 PyObject *c;
4816 CHECK_BINOP(a, b);
4817 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4818 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004819}
4820
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004821static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004822long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 PyObject *c;
4825 CHECK_BINOP(a, b);
4826 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4827 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004828}
4829
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004830static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004831long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004833 PyObject *c;
4834 CHECK_BINOP(a, b);
4835 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4836 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004837}
4838
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004839static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004840long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 if (PyLong_CheckExact(v))
4843 Py_INCREF(v);
4844 else
4845 v = _PyLong_Copy((PyLongObject *)v);
4846 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004847}
4848
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004849PyObject *
4850_PyLong_GCD(PyObject *aarg, PyObject *barg)
4851{
4852 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4853 stwodigits x, y, q, s, t, c_carry, d_carry;
4854 stwodigits A, B, C, D, T;
4855 int nbits, k;
4856 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4857 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4858
4859 a = (PyLongObject *)aarg;
4860 b = (PyLongObject *)barg;
4861 size_a = Py_SIZE(a);
4862 size_b = Py_SIZE(b);
4863 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4864 Py_INCREF(a);
4865 Py_INCREF(b);
4866 goto simple;
4867 }
4868
4869 /* Initial reduction: make sure that 0 <= b <= a. */
4870 a = (PyLongObject *)long_abs(a);
4871 if (a == NULL)
4872 return NULL;
4873 b = (PyLongObject *)long_abs(b);
4874 if (b == NULL) {
4875 Py_DECREF(a);
4876 return NULL;
4877 }
4878 if (long_compare(a, b) < 0) {
4879 r = a;
4880 a = b;
4881 b = r;
4882 }
4883 /* We now own references to a and b */
4884
4885 alloc_a = Py_SIZE(a);
4886 alloc_b = Py_SIZE(b);
4887 /* reduce until a fits into 2 digits */
4888 while ((size_a = Py_SIZE(a)) > 2) {
4889 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4890 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4891 corresponding bits of b into y */
4892 size_b = Py_SIZE(b);
4893 assert(size_b <= size_a);
4894 if (size_b == 0) {
4895 if (size_a < alloc_a) {
4896 r = (PyLongObject *)_PyLong_Copy(a);
4897 Py_DECREF(a);
4898 }
4899 else
4900 r = a;
4901 Py_DECREF(b);
4902 Py_XDECREF(c);
4903 Py_XDECREF(d);
4904 return (PyObject *)r;
4905 }
4906 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4907 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4908 (a->ob_digit[size_a-3] >> nbits));
4909
4910 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4911 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4912 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4913
4914 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4915 larger than PyLong_MASK during the algorithm. */
4916 A = 1; B = 0; C = 0; D = 1;
4917 for (k=0;; k++) {
4918 if (y-C == 0)
4919 break;
4920 q = (x+(A-1))/(y-C);
4921 s = B+q*D;
4922 t = x-q*y;
4923 if (s > t)
4924 break;
4925 x = y; y = t;
4926 t = A+q*C; A = D; B = C; C = s; D = t;
4927 }
4928
4929 if (k == 0) {
4930 /* no progress; do a Euclidean step */
4931 if (l_divmod(a, b, NULL, &r) < 0)
4932 goto error;
4933 Py_DECREF(a);
4934 a = b;
4935 b = r;
4936 alloc_a = alloc_b;
4937 alloc_b = Py_SIZE(b);
4938 continue;
4939 }
4940
4941 /*
4942 a, b = A*b-B*a, D*a-C*b if k is odd
4943 a, b = A*a-B*b, D*b-C*a if k is even
4944 */
4945 if (k&1) {
4946 T = -A; A = -B; B = T;
4947 T = -C; C = -D; D = T;
4948 }
4949 if (c != NULL)
4950 Py_SIZE(c) = size_a;
4951 else if (Py_REFCNT(a) == 1) {
4952 Py_INCREF(a);
4953 c = a;
4954 }
4955 else {
4956 alloc_a = size_a;
4957 c = _PyLong_New(size_a);
4958 if (c == NULL)
4959 goto error;
4960 }
4961
4962 if (d != NULL)
4963 Py_SIZE(d) = size_a;
4964 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4965 Py_INCREF(b);
4966 d = b;
4967 Py_SIZE(d) = size_a;
4968 }
4969 else {
4970 alloc_b = size_a;
4971 d = _PyLong_New(size_a);
4972 if (d == NULL)
4973 goto error;
4974 }
4975 a_end = a->ob_digit + size_a;
4976 b_end = b->ob_digit + size_b;
4977
4978 /* compute new a and new b in parallel */
4979 a_digit = a->ob_digit;
4980 b_digit = b->ob_digit;
4981 c_digit = c->ob_digit;
4982 d_digit = d->ob_digit;
4983 c_carry = 0;
4984 d_carry = 0;
4985 while (b_digit < b_end) {
4986 c_carry += (A * *a_digit) - (B * *b_digit);
4987 d_carry += (D * *b_digit++) - (C * *a_digit++);
4988 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4989 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4990 c_carry >>= PyLong_SHIFT;
4991 d_carry >>= PyLong_SHIFT;
4992 }
4993 while (a_digit < a_end) {
4994 c_carry += A * *a_digit;
4995 d_carry -= C * *a_digit++;
4996 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4997 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4998 c_carry >>= PyLong_SHIFT;
4999 d_carry >>= PyLong_SHIFT;
5000 }
5001 assert(c_carry == 0);
5002 assert(d_carry == 0);
5003
5004 Py_INCREF(c);
5005 Py_INCREF(d);
5006 Py_DECREF(a);
5007 Py_DECREF(b);
5008 a = long_normalize(c);
5009 b = long_normalize(d);
5010 }
5011 Py_XDECREF(c);
5012 Py_XDECREF(d);
5013
5014simple:
5015 assert(Py_REFCNT(a) > 0);
5016 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02005017/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
5018 undefined behaviour when LONG_MAX type is smaller than 60 bits */
5019#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005020 /* a fits into a long, so b must too */
5021 x = PyLong_AsLong((PyObject *)a);
5022 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07005023#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005024 x = PyLong_AsLongLong((PyObject *)a);
5025 y = PyLong_AsLongLong((PyObject *)b);
5026#else
5027# error "_PyLong_GCD"
5028#endif
5029 x = Py_ABS(x);
5030 y = Py_ABS(y);
5031 Py_DECREF(a);
5032 Py_DECREF(b);
5033
5034 /* usual Euclidean algorithm for longs */
5035 while (y != 0) {
5036 t = y;
5037 y = x % y;
5038 x = t;
5039 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005040#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005041 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07005042#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005043 return PyLong_FromLongLong(x);
5044#else
5045# error "_PyLong_GCD"
5046#endif
5047
5048error:
5049 Py_DECREF(a);
5050 Py_DECREF(b);
5051 Py_XDECREF(c);
5052 Py_XDECREF(d);
5053 return NULL;
5054}
5055
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005056static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005057long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005059 double result;
5060 result = PyLong_AsDouble(v);
5061 if (result == -1.0 && PyErr_Occurred())
5062 return NULL;
5063 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005064}
5065
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005066static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005067long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5068
5069/*[clinic input]
5070@classmethod
5071int.__new__ as long_new
5072 x: object(c_default="NULL") = 0
5073 /
5074 base as obase: object(c_default="NULL") = 10
5075[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005076
Tim Peters6d6c1a32001-08-02 04:15:00 +00005077static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005078long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5079/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005080{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005081 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005084 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005085 if (x == NULL) {
5086 if (obase != NULL) {
5087 PyErr_SetString(PyExc_TypeError,
5088 "int() missing string argument");
5089 return NULL;
5090 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005092 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005093 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005095
Gregory P. Smitha689e522012-12-25 22:38:32 -08005096 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005097 if (base == -1 && PyErr_Occurred())
5098 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005099 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005100 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305101 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005102 return NULL;
5103 }
5104
5105 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005106 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005107 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 if (PyByteArray_Check(x))
5110 string = PyByteArray_AS_STRING(x);
5111 else
5112 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005113 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005114 }
5115 else {
5116 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005117 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 return NULL;
5119 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005120}
5121
Serhiy Storchaka95949422013-08-27 19:40:23 +03005122/* Wimpy, slow approach to tp_new calls for subtypes of int:
5123 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005124 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005125 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005126*/
5127static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005128long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 PyLongObject *tmp, *newobj;
5131 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005134 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 if (tmp == NULL)
5136 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005137 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 n = Py_SIZE(tmp);
5139 if (n < 0)
5140 n = -n;
5141 newobj = (PyLongObject *)type->tp_alloc(type, n);
5142 if (newobj == NULL) {
5143 Py_DECREF(tmp);
5144 return NULL;
5145 }
5146 assert(PyLong_Check(newobj));
5147 Py_SIZE(newobj) = Py_SIZE(tmp);
5148 for (i = 0; i < n; i++)
5149 newobj->ob_digit[i] = tmp->ob_digit[i];
5150 Py_DECREF(tmp);
5151 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005152}
5153
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005154/*[clinic input]
5155int.__getnewargs__
5156[clinic start generated code]*/
5157
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005158static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005159int___getnewargs___impl(PyObject *self)
5160/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005161{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005162 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005163}
5164
Guido van Rossumb43daf72007-08-01 18:08:08 +00005165static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005166long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005169}
5170
5171static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005172long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005175}
5176
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005177/*[clinic input]
5178int.__format__
5179
5180 format_spec: unicode
5181 /
5182[clinic start generated code]*/
5183
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005184static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005185int___format___impl(PyObject *self, PyObject *format_spec)
5186/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005187{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005188 _PyUnicodeWriter writer;
5189 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005190
Victor Stinner8f674cc2013-04-17 23:02:17 +02005191 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005192 ret = _PyLong_FormatAdvancedWriter(
5193 &writer,
5194 self,
5195 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5196 if (ret == -1) {
5197 _PyUnicodeWriter_Dealloc(&writer);
5198 return NULL;
5199 }
5200 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005201}
5202
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005203/* Return a pair (q, r) such that a = b * q + r, and
5204 abs(r) <= abs(b)/2, with equality possible only if q is even.
5205 In other words, q == a / b, rounded to the nearest integer using
5206 round-half-to-even. */
5207
5208PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005209_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005210{
5211 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005212 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005213 int quo_is_odd, quo_is_neg;
5214 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005215
5216 /* Equivalent Python code:
5217
5218 def divmod_near(a, b):
5219 q, r = divmod(a, b)
5220 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5221 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5222 # positive, 2 * r < b if b negative.
5223 greater_than_half = 2*r > b if b > 0 else 2*r < b
5224 exactly_half = 2*r == b
5225 if greater_than_half or exactly_half and q % 2 == 1:
5226 q += 1
5227 r -= b
5228 return q, r
5229
5230 */
5231 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5232 PyErr_SetString(PyExc_TypeError,
5233 "non-integer arguments in division");
5234 return NULL;
5235 }
5236
5237 /* Do a and b have different signs? If so, quotient is negative. */
5238 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5239
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005240 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5241 goto error;
5242
5243 /* compare twice the remainder with the divisor, to see
5244 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005245 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005246 if (twice_rem == NULL)
5247 goto error;
5248 if (quo_is_neg) {
5249 temp = long_neg((PyLongObject*)twice_rem);
5250 Py_DECREF(twice_rem);
5251 twice_rem = temp;
5252 if (twice_rem == NULL)
5253 goto error;
5254 }
5255 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5256 Py_DECREF(twice_rem);
5257
5258 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5259 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5260 /* fix up quotient */
5261 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005262 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005263 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005264 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005265 Py_DECREF(quo);
5266 quo = (PyLongObject *)temp;
5267 if (quo == NULL)
5268 goto error;
5269 /* and remainder */
5270 if (quo_is_neg)
5271 temp = long_add(rem, (PyLongObject *)b);
5272 else
5273 temp = long_sub(rem, (PyLongObject *)b);
5274 Py_DECREF(rem);
5275 rem = (PyLongObject *)temp;
5276 if (rem == NULL)
5277 goto error;
5278 }
5279
5280 result = PyTuple_New(2);
5281 if (result == NULL)
5282 goto error;
5283
5284 /* PyTuple_SET_ITEM steals references */
5285 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5286 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005287 return result;
5288
5289 error:
5290 Py_XDECREF(quo);
5291 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005292 return NULL;
5293}
5294
Eric Smith8c663262007-08-25 02:26:07 +00005295static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005296long_round(PyObject *self, PyObject *args)
5297{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005298 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005299
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005300 /* To round an integer m to the nearest 10**n (n positive), we make use of
5301 * the divmod_near operation, defined by:
5302 *
5303 * divmod_near(a, b) = (q, r)
5304 *
5305 * where q is the nearest integer to the quotient a / b (the
5306 * nearest even integer in the case of a tie) and r == a - q * b.
5307 * Hence q * b = a - r is the nearest multiple of b to a,
5308 * preferring even multiples in the case of a tie.
5309 *
5310 * So the nearest multiple of 10**n to m is:
5311 *
5312 * m - divmod_near(m, 10**n)[1].
5313 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005314 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5315 return NULL;
5316 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005317 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005318
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005319 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005320 if (ndigits == NULL)
5321 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005322
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005323 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 if (Py_SIZE(ndigits) >= 0) {
5325 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005326 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005328
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005329 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5330 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005331 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005332 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005334 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005335
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005336 result = PyLong_FromLong(10L);
5337 if (result == NULL) {
5338 Py_DECREF(ndigits);
5339 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005341
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005342 temp = long_pow(result, ndigits, Py_None);
5343 Py_DECREF(ndigits);
5344 Py_DECREF(result);
5345 result = temp;
5346 if (result == NULL)
5347 return NULL;
5348
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005349 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005350 Py_DECREF(result);
5351 result = temp;
5352 if (result == NULL)
5353 return NULL;
5354
5355 temp = long_sub((PyLongObject *)self,
5356 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5357 Py_DECREF(result);
5358 result = temp;
5359
5360 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005361}
5362
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005363/*[clinic input]
5364int.__sizeof__ -> Py_ssize_t
5365
5366Returns size in memory, in bytes.
5367[clinic start generated code]*/
5368
5369static Py_ssize_t
5370int___sizeof___impl(PyObject *self)
5371/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005374
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005375 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5376 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005377}
5378
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005379/*[clinic input]
5380int.bit_length
5381
5382Number of bits necessary to represent self in binary.
5383
5384>>> bin(37)
5385'0b100101'
5386>>> (37).bit_length()
53876
5388[clinic start generated code]*/
5389
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005390static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005391int_bit_length_impl(PyObject *self)
5392/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005395 Py_ssize_t ndigits;
5396 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005398
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005399 assert(self != NULL);
5400 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005401
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005402 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 if (ndigits == 0)
5404 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005405
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005406 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005407 msd_bits = bits_in_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005409 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5410 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 /* expression above may overflow; use Python integers instead */
5413 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5414 if (result == NULL)
5415 return NULL;
5416 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5417 if (x == NULL)
5418 goto error;
5419 y = (PyLongObject *)long_mul(result, x);
5420 Py_DECREF(x);
5421 if (y == NULL)
5422 goto error;
5423 Py_DECREF(result);
5424 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005426 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5427 if (x == NULL)
5428 goto error;
5429 y = (PyLongObject *)long_add(result, x);
5430 Py_DECREF(x);
5431 if (y == NULL)
5432 goto error;
5433 Py_DECREF(result);
5434 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005437
Mark Dickinson22b20182010-05-10 21:27:53 +00005438 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 Py_DECREF(result);
5440 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005441}
5442
Christian Heimes53876d92008-04-19 00:31:39 +00005443#if 0
5444static PyObject *
5445long_is_finite(PyObject *v)
5446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005448}
5449#endif
5450
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005451/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005452int.as_integer_ratio
5453
5454Return integer ratio.
5455
5456Return a pair of integers, whose ratio is exactly equal to the original int
5457and with a positive denominator.
5458
5459>>> (10).as_integer_ratio()
5460(10, 1)
5461>>> (-10).as_integer_ratio()
5462(-10, 1)
5463>>> (0).as_integer_ratio()
5464(0, 1)
5465[clinic start generated code]*/
5466
5467static PyObject *
5468int_as_integer_ratio_impl(PyObject *self)
5469/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5470{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005471 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005472 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005473 if (numerator == NULL) {
5474 return NULL;
5475 }
5476 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5477 Py_DECREF(numerator);
5478 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005479}
5480
5481/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005482int.to_bytes
5483
5484 length: Py_ssize_t
5485 Length of bytes object to use. An OverflowError is raised if the
5486 integer is not representable with the given number of bytes.
5487 byteorder: unicode
5488 The byte order used to represent the integer. If byteorder is 'big',
5489 the most significant byte is at the beginning of the byte array. If
5490 byteorder is 'little', the most significant byte is at the end of the
5491 byte array. To request the native byte order of the host system, use
5492 `sys.byteorder' as the byte order value.
5493 *
5494 signed as is_signed: bool = False
5495 Determines whether two's complement is used to represent the integer.
5496 If signed is False and a negative integer is given, an OverflowError
5497 is raised.
5498
5499Return an array of bytes representing an integer.
5500[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005501
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005502static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005503int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5504 int is_signed)
5505/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005509
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005510 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005512 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 little_endian = 0;
5514 else {
5515 PyErr_SetString(PyExc_ValueError,
5516 "byteorder must be either 'little' or 'big'");
5517 return NULL;
5518 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 if (length < 0) {
5521 PyErr_SetString(PyExc_ValueError,
5522 "length argument must be non-negative");
5523 return NULL;
5524 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005526 bytes = PyBytes_FromStringAndSize(NULL, length);
5527 if (bytes == NULL)
5528 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005529
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005530 if (_PyLong_AsByteArray((PyLongObject *)self,
5531 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 length, little_endian, is_signed) < 0) {
5533 Py_DECREF(bytes);
5534 return NULL;
5535 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005538}
5539
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005540/*[clinic input]
5541@classmethod
5542int.from_bytes
5543
5544 bytes as bytes_obj: object
5545 Holds the array of bytes to convert. The argument must either
5546 support the buffer protocol or be an iterable object producing bytes.
5547 Bytes and bytearray are examples of built-in objects that support the
5548 buffer protocol.
5549 byteorder: unicode
5550 The byte order used to represent the integer. If byteorder is 'big',
5551 the most significant byte is at the beginning of the byte array. If
5552 byteorder is 'little', the most significant byte is at the end of the
5553 byte array. To request the native byte order of the host system, use
5554 `sys.byteorder' as the byte order value.
5555 *
5556 signed as is_signed: bool = False
5557 Indicates whether two's complement is used to represent the integer.
5558
5559Return the integer represented by the given array of bytes.
5560[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005561
5562static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005563int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5564 PyObject *byteorder, int is_signed)
5565/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005568 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005569
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005570 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005572 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005573 little_endian = 0;
5574 else {
5575 PyErr_SetString(PyExc_ValueError,
5576 "byteorder must be either 'little' or 'big'");
5577 return NULL;
5578 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005579
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005580 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005581 if (bytes == NULL)
5582 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 long_obj = _PyLong_FromByteArray(
5585 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5586 little_endian, is_signed);
5587 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005588
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005589 if (long_obj != NULL && type != &PyLong_Type) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02005590 Py_SETREF(long_obj, _PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005593 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005594}
5595
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005596static PyObject *
5597long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5598{
5599 return long_long(self);
5600}
5601
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005602static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005603 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005604 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005605 INT_BIT_LENGTH_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00005606#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005607 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5608 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005609#endif
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005610 INT_TO_BYTES_METHODDEF
5611 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005612 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005613 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005615 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005616 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005617 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005618 "Ceiling of an Integral returns itself."},
5619 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5620 "Rounding an Integral returns itself.\n"
5621 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005622 INT___GETNEWARGS___METHODDEF
5623 INT___FORMAT___METHODDEF
5624 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005626};
5627
Guido van Rossumb43daf72007-08-01 18:08:08 +00005628static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005629 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005630 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005631 "the real part of a complex number",
5632 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005633 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005634 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005635 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005636 NULL},
5637 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005638 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005639 "the numerator of a rational number in lowest terms",
5640 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005641 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005642 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005643 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005644 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005645 {NULL} /* Sentinel */
5646};
5647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005648PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005649"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005650int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005651\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005652Convert a number or string to an integer, or return 0 if no arguments\n\
5653are given. If x is a number, return x.__int__(). For floating point\n\
5654numbers, this truncates towards zero.\n\
5655\n\
5656If x is not a number or if base is given, then x must be a string,\n\
5657bytes, or bytearray instance representing an integer literal in the\n\
5658given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5659by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5660Base 0 means to interpret the base from the string as an integer literal.\n\
5661>>> int('0b100', base=0)\n\
56624");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005663
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005664static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005665 (binaryfunc)long_add, /*nb_add*/
5666 (binaryfunc)long_sub, /*nb_subtract*/
5667 (binaryfunc)long_mul, /*nb_multiply*/
5668 long_mod, /*nb_remainder*/
5669 long_divmod, /*nb_divmod*/
5670 long_pow, /*nb_power*/
5671 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005672 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005673 (unaryfunc)long_abs, /*tp_absolute*/
5674 (inquiry)long_bool, /*tp_bool*/
5675 (unaryfunc)long_invert, /*nb_invert*/
5676 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005677 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005678 long_and, /*nb_and*/
5679 long_xor, /*nb_xor*/
5680 long_or, /*nb_or*/
5681 long_long, /*nb_int*/
5682 0, /*nb_reserved*/
5683 long_float, /*nb_float*/
5684 0, /* nb_inplace_add */
5685 0, /* nb_inplace_subtract */
5686 0, /* nb_inplace_multiply */
5687 0, /* nb_inplace_remainder */
5688 0, /* nb_inplace_power */
5689 0, /* nb_inplace_lshift */
5690 0, /* nb_inplace_rshift */
5691 0, /* nb_inplace_and */
5692 0, /* nb_inplace_xor */
5693 0, /* nb_inplace_or */
5694 long_div, /* nb_floor_divide */
5695 long_true_divide, /* nb_true_divide */
5696 0, /* nb_inplace_floor_divide */
5697 0, /* nb_inplace_true_divide */
5698 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005699};
5700
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005701PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5703 "int", /* tp_name */
5704 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5705 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005706 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005707 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 0, /* tp_getattr */
5709 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005710 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 long_to_decimal_string, /* tp_repr */
5712 &long_as_number, /* tp_as_number */
5713 0, /* tp_as_sequence */
5714 0, /* tp_as_mapping */
5715 (hashfunc)long_hash, /* tp_hash */
5716 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005717 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 PyObject_GenericGetAttr, /* tp_getattro */
5719 0, /* tp_setattro */
5720 0, /* tp_as_buffer */
5721 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5722 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5723 long_doc, /* tp_doc */
5724 0, /* tp_traverse */
5725 0, /* tp_clear */
5726 long_richcompare, /* tp_richcompare */
5727 0, /* tp_weaklistoffset */
5728 0, /* tp_iter */
5729 0, /* tp_iternext */
5730 long_methods, /* tp_methods */
5731 0, /* tp_members */
5732 long_getset, /* tp_getset */
5733 0, /* tp_base */
5734 0, /* tp_dict */
5735 0, /* tp_descr_get */
5736 0, /* tp_descr_set */
5737 0, /* tp_dictoffset */
5738 0, /* tp_init */
5739 0, /* tp_alloc */
5740 long_new, /* tp_new */
5741 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005742};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005743
Mark Dickinsonbd792642009-03-18 20:06:12 +00005744static PyTypeObject Int_InfoType;
5745
5746PyDoc_STRVAR(int_info__doc__,
5747"sys.int_info\n\
5748\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005749A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005750internal representation of integers. The attributes are read only.");
5751
5752static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005754 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005755 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005756};
5757
5758static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005759 "sys.int_info", /* name */
5760 int_info__doc__, /* doc */
5761 int_info_fields, /* fields */
5762 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005763};
5764
5765PyObject *
5766PyLong_GetInfo(void)
5767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 PyObject* int_info;
5769 int field = 0;
5770 int_info = PyStructSequence_New(&Int_InfoType);
5771 if (int_info == NULL)
5772 return NULL;
5773 PyStructSequence_SET_ITEM(int_info, field++,
5774 PyLong_FromLong(PyLong_SHIFT));
5775 PyStructSequence_SET_ITEM(int_info, field++,
5776 PyLong_FromLong(sizeof(digit)));
5777 if (PyErr_Occurred()) {
5778 Py_CLEAR(int_info);
5779 return NULL;
5780 }
5781 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005782}
5783
Guido van Rossumddefaf32007-01-14 03:31:43 +00005784int
5785_PyLong_Init(void)
5786{
5787#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005788 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5789 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5790 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005791
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005792 PyLongObject *v = _PyLong_New(1);
5793 if (!v) {
5794 return -1;
5795 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005797 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005798 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005799
5800 small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005802#endif
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005803 _PyLong_Zero = PyLong_FromLong(0);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005804 if (_PyLong_Zero == NULL) {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005805 return 0;
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005806 }
5807
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005808 _PyLong_One = PyLong_FromLong(1);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005809 if (_PyLong_One == NULL) {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005810 return 0;
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005811 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005813 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005814 if (Int_InfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005815 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005816 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005817 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005818 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005821}
5822
5823void
Victor Stinnerbed48172019-08-27 00:12:32 +02005824_PyLong_Fini(void)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005825{
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005826 Py_CLEAR(_PyLong_One);
5827 Py_CLEAR(_PyLong_Zero);
Guido van Rossumddefaf32007-01-14 03:31:43 +00005828#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005829 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5830 Py_CLEAR(small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005831 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005832#endif
5833}