blob: be9301f85162c8c8988fbb9d54208d1e4e5ca2f3 [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"
Victor Stinner630c8df2019-12-17 13:02:18 +01006#include "pycore_pystate.h" /* _Py_IsMainInterpreter() */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00007#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Mark Dickinsonc6300392009-04-20 21:38:00 +00009#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000011#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000012
Serhiy Storchaka495e8802017-02-01 23:12:20 +020013#include "clinic/longobject.c.h"
14/*[clinic input]
15class int "PyObject *" "&PyLong_Type"
16[clinic start generated code]*/
17/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
18
Victor Stinner630c8df2019-12-17 13:02:18 +010019#define NSMALLPOSINTS _PY_NSMALLPOSINTS
20#define NSMALLNEGINTS _PY_NSMALLNEGINTS
Facundo Batista6e6f59b2008-07-24 18:57:11 +000021
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020022_Py_IDENTIFIER(little);
23_Py_IDENTIFIER(big);
24
Mark Dickinsone4416742009-02-15 15:14:57 +000025/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020026#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
27 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 (Py_SIZE(x) == 0 ? (sdigit)0 : \
29 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000030
Serhiy Storchakaba85d692017-03-30 09:09:41 +030031PyObject *_PyLong_Zero = NULL;
32PyObject *_PyLong_One = NULL;
33
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#if NSMALLNEGINTS + NSMALLPOSINTS > 0
animalize6b519982019-09-06 14:00:56 +080035#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050036#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070037
Guido van Rossumddefaf32007-01-14 03:31:43 +000038#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +000039Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000040#endif
41
Guido van Rossum7eaf8222007-06-18 17:58:50 +000042static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000043get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000044{
animalize6b519982019-09-06 14:00:56 +080045 assert(IS_SMALL_INT(ival));
Victor Stinner630c8df2019-12-17 13:02:18 +010046 PyThreadState *tstate = _PyThreadState_GET();
47 PyObject *v = (PyObject*)tstate->interp->small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000049#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 if (ival >= 0)
Pablo Galindo49c75a82018-10-28 15:02:17 +000051 _Py_quick_int_allocs++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 else
Pablo Galindo49c75a82018-10-28 15:02:17 +000053 _Py_quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000054#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000056}
Guido van Rossumddefaf32007-01-14 03:31:43 +000057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000059maybe_small_long(PyLongObject *v)
60{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020061 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080063 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 Py_DECREF(v);
65 return (PyLongObject *)get_small_int(ival);
66 }
67 }
68 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069}
Guido van Rossumddefaf32007-01-14 03:31:43 +000070#else
animalize6b519982019-09-06 14:00:56 +080071#define IS_SMALL_INT(ival) 0
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050072#define IS_SMALL_UINT(ival) 0
animalize6b519982019-09-06 14:00:56 +080073#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000074#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000075#endif
76
Serhiy Storchaka95949422013-08-27 19:40:23 +030077/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000078 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020079Py_LOCAL_INLINE(void)
80_PyLong_Negate(PyLongObject **x_p)
81{
82 PyLongObject *x;
83
84 x = (PyLongObject *)*x_p;
85 if (Py_REFCNT(x) == 1) {
86 Py_SIZE(x) = -Py_SIZE(x);
87 return;
88 }
89
90 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
91 Py_DECREF(x);
92}
93
Serhiy Storchaka95949422013-08-27 19:40:23 +030094/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000095 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030096 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000097 */
Tim Peters0973b992004-08-29 22:16:50 +000098#define KARATSUBA_CUTOFF 70
99#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +0000100
Tim Peters47e52ee2004-08-30 02:44:38 +0000101/* For exponentiation, use the binary left-to-right algorithm
102 * unless the exponent contains more than FIVEARY_CUTOFF digits.
103 * In that case, do 5 bits at a time. The potential drawback is that
104 * a table of 2**5 intermediate results is computed.
105 */
106#define FIVEARY_CUTOFF 8
107
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000108#define SIGCHECK(PyTryBlock) \
109 do { \
110 if (PyErr_CheckSignals()) PyTryBlock \
111 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000112
Serhiy Storchaka95949422013-08-27 19:40:23 +0300113/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000114 Doesn't attempt to free the storage--in most cases, due to the nature
115 of the algorithms used, this could save at most be one word anyway. */
116
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000117static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200118long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000119{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200120 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 while (i > 0 && v->ob_digit[i-1] == 0)
124 --i;
125 if (i != j)
126 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
127 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128}
129
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200130/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
131 using the nb_int slot, if available. Raise TypeError if either the
132 nb_int slot is not available or the result of the call to nb_int
133 returns something not of type int.
134*/
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200135PyObject *
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200136_PyLong_FromNbInt(PyObject *integral)
137{
138 PyNumberMethods *nb;
139 PyObject *result;
140
141 /* Fast path for the case that we already have an int. */
142 if (PyLong_CheckExact(integral)) {
143 Py_INCREF(integral);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200144 return integral;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200145 }
146
147 nb = Py_TYPE(integral)->tp_as_number;
148 if (nb == NULL || nb->nb_int == NULL) {
149 PyErr_Format(PyExc_TypeError,
150 "an integer is required (got type %.200s)",
151 Py_TYPE(integral)->tp_name);
152 return NULL;
153 }
154
155 /* Convert using the nb_int slot, which should return something
156 of exact type int. */
157 result = nb->nb_int(integral);
158 if (!result || PyLong_CheckExact(result))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200159 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200160 if (!PyLong_Check(result)) {
161 PyErr_Format(PyExc_TypeError,
162 "__int__ returned non-int (type %.200s)",
163 result->ob_type->tp_name);
164 Py_DECREF(result);
165 return NULL;
166 }
167 /* Issue #17576: warn if 'result' not of exact type int. */
168 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
169 "__int__ returned non-int (type %.200s). "
170 "The ability to return an instance of a strict subclass of int "
171 "is deprecated, and may be removed in a future version of Python.",
172 result->ob_type->tp_name)) {
173 Py_DECREF(result);
174 return NULL;
175 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200176 return result;
177}
178
179/* Convert the given object to a PyLongObject using the nb_index or
180 nb_int slots, if available (the latter is deprecated).
181 Raise TypeError if either nb_index and nb_int slots are not
182 available or the result of the call to nb_index or nb_int
183 returns something not of type int.
184 Should be replaced with PyNumber_Index after the end of the
185 deprecation period.
186*/
187PyObject *
188_PyLong_FromNbIndexOrNbInt(PyObject *integral)
189{
190 PyNumberMethods *nb;
191 PyObject *result;
192
193 /* Fast path for the case that we already have an int. */
194 if (PyLong_CheckExact(integral)) {
195 Py_INCREF(integral);
196 return integral;
197 }
198
199 nb = Py_TYPE(integral)->tp_as_number;
200 if (nb == NULL || (nb->nb_index == NULL && nb->nb_int == NULL)) {
201 PyErr_Format(PyExc_TypeError,
202 "an integer is required (got type %.200s)",
203 Py_TYPE(integral)->tp_name);
204 return NULL;
205 }
206
207 if (nb->nb_index) {
208 /* Convert using the nb_index slot, which should return something
209 of exact type int. */
210 result = nb->nb_index(integral);
211 if (!result || PyLong_CheckExact(result))
212 return result;
213 if (!PyLong_Check(result)) {
214 PyErr_Format(PyExc_TypeError,
215 "__index__ returned non-int (type %.200s)",
216 result->ob_type->tp_name);
217 Py_DECREF(result);
218 return NULL;
219 }
220 /* Issue #17576: warn if 'result' not of exact type int. */
221 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
222 "__index__ returned non-int (type %.200s). "
223 "The ability to return an instance of a strict subclass of int "
224 "is deprecated, and may be removed in a future version of Python.",
225 result->ob_type->tp_name))
226 {
227 Py_DECREF(result);
228 return NULL;
229 }
230 return result;
231 }
232
233 result = _PyLong_FromNbInt(integral);
234 if (result && PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
235 "an integer is required (got type %.200s). "
236 "Implicit conversion to integers using __int__ is deprecated, "
237 "and may be removed in a future version of Python.",
238 Py_TYPE(integral)->tp_name))
239 {
240 Py_DECREF(result);
241 return NULL;
242 }
243 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200244}
245
246
Serhiy Storchaka95949422013-08-27 19:40:23 +0300247/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000248 Return NULL and set exception if we run out of memory. */
249
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000250#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000252
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000253PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000254_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 PyLongObject *result;
257 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
258 sizeof(digit)*size. Previous incarnations of this code used
259 sizeof(PyVarObject) instead of the offsetof, but this risks being
260 incorrect in the presence of padding between the PyVarObject header
261 and the digits. */
262 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
263 PyErr_SetString(PyExc_OverflowError,
264 "too many digits in integer");
265 return NULL;
266 }
267 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
268 size*sizeof(digit));
269 if (!result) {
270 PyErr_NoMemory();
271 return NULL;
272 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100273 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000274}
275
Tim Peters64b5ce32001-09-10 20:52:51 +0000276PyObject *
277_PyLong_Copy(PyLongObject *src)
278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 PyLongObject *result;
280 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 assert(src != NULL);
283 i = Py_SIZE(src);
284 if (i < 0)
285 i = -(i);
286 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100287 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800288 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700289 return get_small_int(ival);
290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 }
292 result = _PyLong_New(i);
293 if (result != NULL) {
294 Py_SIZE(result) = Py_SIZE(src);
295 while (--i >= 0)
296 result->ob_digit[i] = src->ob_digit[i];
297 }
298 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000299}
300
Serhiy Storchaka95949422013-08-27 19:40:23 +0300301/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000302
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000304PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 PyLongObject *v;
307 unsigned long abs_ival;
308 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
309 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100310 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000311
animalize6b519982019-09-06 14:00:56 +0800312 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700313 return get_small_int((sdigit)ival);
314 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (ival < 0) {
317 /* negate: can't write this as abs_ival = -ival since that
318 invokes undefined behaviour when ival is LONG_MIN */
319 abs_ival = 0U-(unsigned long)ival;
320 sign = -1;
321 }
322 else {
323 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100324 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 /* Fast path for single-digit ints */
328 if (!(abs_ival >> PyLong_SHIFT)) {
329 v = _PyLong_New(1);
330 if (v) {
331 Py_SIZE(v) = sign;
332 v->ob_digit[0] = Py_SAFE_DOWNCAST(
333 abs_ival, unsigned long, digit);
334 }
335 return (PyObject*)v;
336 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000337
Mark Dickinson249b8982009-04-27 19:41:00 +0000338#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* 2 digits */
340 if (!(abs_ival >> 2*PyLong_SHIFT)) {
341 v = _PyLong_New(2);
342 if (v) {
343 Py_SIZE(v) = 2*sign;
344 v->ob_digit[0] = Py_SAFE_DOWNCAST(
345 abs_ival & PyLong_MASK, unsigned long, digit);
346 v->ob_digit[1] = Py_SAFE_DOWNCAST(
347 abs_ival >> PyLong_SHIFT, unsigned long, digit);
348 }
349 return (PyObject*)v;
350 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000351#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 /* Larger numbers: loop to determine number of digits */
354 t = abs_ival;
355 while (t) {
356 ++ndigits;
357 t >>= PyLong_SHIFT;
358 }
359 v = _PyLong_New(ndigits);
360 if (v != NULL) {
361 digit *p = v->ob_digit;
362 Py_SIZE(v) = ndigits*sign;
363 t = abs_ival;
364 while (t) {
365 *p++ = Py_SAFE_DOWNCAST(
366 t & PyLong_MASK, unsigned long, digit);
367 t >>= PyLong_SHIFT;
368 }
369 }
370 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000371}
372
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500373#define PYLONG_FROM_UINT(INT_TYPE, ival) \
374 do { \
375 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200376 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500377 } \
378 /* Count the number of Python digits. */ \
379 Py_ssize_t ndigits = 0; \
380 INT_TYPE t = (ival); \
381 while (t) { \
382 ++ndigits; \
383 t >>= PyLong_SHIFT; \
384 } \
385 PyLongObject *v = _PyLong_New(ndigits); \
386 if (v == NULL) { \
387 return NULL; \
388 } \
389 digit *p = v->ob_digit; \
390 while ((ival)) { \
391 *p++ = (digit)((ival) & PyLong_MASK); \
392 (ival) >>= PyLong_SHIFT; \
393 } \
394 return (PyObject *)v; \
395 } while(0)
396
Serhiy Storchaka95949422013-08-27 19:40:23 +0300397/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000398
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000399PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000400PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000401{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500402 PYLONG_FROM_UINT(unsigned long, ival);
403}
Tim Petersce9de2f2001-06-14 04:56:19 +0000404
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500405/* Create a new int object from a C unsigned long long int. */
406
407PyObject *
408PyLong_FromUnsignedLongLong(unsigned long long ival)
409{
410 PYLONG_FROM_UINT(unsigned long long, ival);
411}
412
413/* Create a new int object from a C size_t. */
414
415PyObject *
416PyLong_FromSize_t(size_t ival)
417{
418 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000419}
420
Serhiy Storchaka95949422013-08-27 19:40:23 +0300421/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000422
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000423PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 PyLongObject *v;
427 double frac;
428 int i, ndig, expo, neg;
429 neg = 0;
430 if (Py_IS_INFINITY(dval)) {
431 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000432 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 return NULL;
434 }
435 if (Py_IS_NAN(dval)) {
436 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000437 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 return NULL;
439 }
440 if (dval < 0.0) {
441 neg = 1;
442 dval = -dval;
443 }
444 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
445 if (expo <= 0)
446 return PyLong_FromLong(0L);
447 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
448 v = _PyLong_New(ndig);
449 if (v == NULL)
450 return NULL;
451 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
452 for (i = ndig; --i >= 0; ) {
453 digit bits = (digit)frac;
454 v->ob_digit[i] = bits;
455 frac = frac - (double)bits;
456 frac = ldexp(frac, PyLong_SHIFT);
457 }
458 if (neg)
459 Py_SIZE(v) = -(Py_SIZE(v));
460 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000461}
462
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
464 * anything about what happens when a signed integer operation overflows,
465 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700466 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000467 * (unsigned long)LONG_MAX, and for the smallest negative signed long
468 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
469 * However, some other compilers warn about applying unary minus to an
470 * unsigned operand. Hence the weird "0-".
471 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
473#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000474
Serhiy Storchaka95949422013-08-27 19:40:23 +0300475/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100476 method.
477
478 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
479 the result. Otherwise *overflow is 0.
480
481 For other errors (e.g., TypeError), return -1 and set an error condition.
482 In this case *overflow will be 0.
483*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000484
485long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000486PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200489 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 unsigned long x, prev;
491 long res;
492 Py_ssize_t i;
493 int sign;
494 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 *overflow = 0;
497 if (vv == NULL) {
498 PyErr_BadInternalCall();
499 return -1;
500 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000501
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200502 if (PyLong_Check(vv)) {
503 v = (PyLongObject *)vv;
504 }
505 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200506 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200507 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return -1;
509 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 switch (i) {
516 case -1:
517 res = -(sdigit)v->ob_digit[0];
518 break;
519 case 0:
520 res = 0;
521 break;
522 case 1:
523 res = v->ob_digit[0];
524 break;
525 default:
526 sign = 1;
527 x = 0;
528 if (i < 0) {
529 sign = -1;
530 i = -(i);
531 }
532 while (--i >= 0) {
533 prev = x;
534 x = (x << PyLong_SHIFT) | v->ob_digit[i];
535 if ((x >> PyLong_SHIFT) != prev) {
536 *overflow = sign;
537 goto exit;
538 }
539 }
540 /* Haven't lost any bits, but casting to long requires extra
541 * care (see comment above).
542 */
543 if (x <= (unsigned long)LONG_MAX) {
544 res = (long)x * sign;
545 }
546 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
547 res = LONG_MIN;
548 }
549 else {
550 *overflow = sign;
551 /* res is already set to -1 */
552 }
553 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000554 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200556 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 }
558 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000559}
560
Serhiy Storchaka95949422013-08-27 19:40:23 +0300561/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100562 method. Return -1 and set an error if overflow occurs. */
563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000565PyLong_AsLong(PyObject *obj)
566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 int overflow;
568 long result = PyLong_AsLongAndOverflow(obj, &overflow);
569 if (overflow) {
570 /* XXX: could be cute and give a different
571 message for overflow == -1 */
572 PyErr_SetString(PyExc_OverflowError,
573 "Python int too large to convert to C long");
574 }
575 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000576}
577
Serhiy Storchaka95949422013-08-27 19:40:23 +0300578/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200579 method. Return -1 and set an error if overflow occurs. */
580
581int
582_PyLong_AsInt(PyObject *obj)
583{
584 int overflow;
585 long result = PyLong_AsLongAndOverflow(obj, &overflow);
586 if (overflow || result > INT_MAX || result < INT_MIN) {
587 /* XXX: could be cute and give a different
588 message for overflow == -1 */
589 PyErr_SetString(PyExc_OverflowError,
590 "Python int too large to convert to C int");
591 return -1;
592 }
593 return (int)result;
594}
595
Serhiy Storchaka95949422013-08-27 19:40:23 +0300596/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000597 Returns -1 and sets an error condition if overflow occurs. */
598
599Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000600PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200601 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 size_t x, prev;
603 Py_ssize_t i;
604 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (vv == NULL) {
607 PyErr_BadInternalCall();
608 return -1;
609 }
610 if (!PyLong_Check(vv)) {
611 PyErr_SetString(PyExc_TypeError, "an integer is required");
612 return -1;
613 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 v = (PyLongObject *)vv;
616 i = Py_SIZE(v);
617 switch (i) {
618 case -1: return -(sdigit)v->ob_digit[0];
619 case 0: return 0;
620 case 1: return v->ob_digit[0];
621 }
622 sign = 1;
623 x = 0;
624 if (i < 0) {
625 sign = -1;
626 i = -(i);
627 }
628 while (--i >= 0) {
629 prev = x;
630 x = (x << PyLong_SHIFT) | v->ob_digit[i];
631 if ((x >> PyLong_SHIFT) != prev)
632 goto overflow;
633 }
634 /* Haven't lost any bits, but casting to a signed type requires
635 * extra care (see comment above).
636 */
637 if (x <= (size_t)PY_SSIZE_T_MAX) {
638 return (Py_ssize_t)x * sign;
639 }
640 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
641 return PY_SSIZE_T_MIN;
642 }
643 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000644
Mark Dickinson22b20182010-05-10 21:27:53 +0000645 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyErr_SetString(PyExc_OverflowError,
647 "Python int too large to convert to C ssize_t");
648 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000649}
650
Serhiy Storchaka95949422013-08-27 19:40:23 +0300651/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000652 Returns -1 and sets an error condition if overflow occurs. */
653
654unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000655PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000656{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200657 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 unsigned long x, prev;
659 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (vv == NULL) {
662 PyErr_BadInternalCall();
663 return (unsigned long)-1;
664 }
665 if (!PyLong_Check(vv)) {
666 PyErr_SetString(PyExc_TypeError, "an integer is required");
667 return (unsigned long)-1;
668 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 v = (PyLongObject *)vv;
671 i = Py_SIZE(v);
672 x = 0;
673 if (i < 0) {
674 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000675 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return (unsigned long) -1;
677 }
678 switch (i) {
679 case 0: return 0;
680 case 1: return v->ob_digit[0];
681 }
682 while (--i >= 0) {
683 prev = x;
684 x = (x << PyLong_SHIFT) | v->ob_digit[i];
685 if ((x >> PyLong_SHIFT) != prev) {
686 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100687 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000688 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 return (unsigned long) -1;
690 }
691 }
692 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000693}
694
Serhiy Storchaka95949422013-08-27 19:40:23 +0300695/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200696 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000697
698size_t
699PyLong_AsSize_t(PyObject *vv)
700{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200701 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 size_t x, prev;
703 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (vv == NULL) {
706 PyErr_BadInternalCall();
707 return (size_t) -1;
708 }
709 if (!PyLong_Check(vv)) {
710 PyErr_SetString(PyExc_TypeError, "an integer is required");
711 return (size_t)-1;
712 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 v = (PyLongObject *)vv;
715 i = Py_SIZE(v);
716 x = 0;
717 if (i < 0) {
718 PyErr_SetString(PyExc_OverflowError,
719 "can't convert negative value to size_t");
720 return (size_t) -1;
721 }
722 switch (i) {
723 case 0: return 0;
724 case 1: return v->ob_digit[0];
725 }
726 while (--i >= 0) {
727 prev = x;
728 x = (x << PyLong_SHIFT) | v->ob_digit[i];
729 if ((x >> PyLong_SHIFT) != prev) {
730 PyErr_SetString(PyExc_OverflowError,
731 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200732 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 }
734 }
735 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000736}
737
Serhiy Storchaka95949422013-08-27 19:40:23 +0300738/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000739 Returns -1 and sets an error condition if an error occurs. */
740
Guido van Rossumddefaf32007-01-14 03:31:43 +0000741static unsigned long
742_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000743{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200744 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 unsigned long x;
746 Py_ssize_t i;
747 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (vv == NULL || !PyLong_Check(vv)) {
750 PyErr_BadInternalCall();
751 return (unsigned long) -1;
752 }
753 v = (PyLongObject *)vv;
754 i = Py_SIZE(v);
755 switch (i) {
756 case 0: return 0;
757 case 1: return v->ob_digit[0];
758 }
759 sign = 1;
760 x = 0;
761 if (i < 0) {
762 sign = -1;
763 i = -i;
764 }
765 while (--i >= 0) {
766 x = (x << PyLong_SHIFT) | v->ob_digit[i];
767 }
768 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000769}
770
Guido van Rossumddefaf32007-01-14 03:31:43 +0000771unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200772PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 PyLongObject *lo;
775 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000776
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200777 if (op == NULL) {
778 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 return (unsigned long)-1;
780 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000781
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200782 if (PyLong_Check(op)) {
783 return _PyLong_AsUnsignedLongMask(op);
784 }
785
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200786 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (lo == NULL)
788 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200789
790 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
791 Py_DECREF(lo);
792 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000793}
794
Tim Peters5b8132f2003-01-31 15:52:05 +0000795int
796_PyLong_Sign(PyObject *vv)
797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 assert(v != NULL);
801 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000804}
805
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200806/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
807 2**k if d is nonzero, else 0. */
808
809static const unsigned char BitLengthTable[32] = {
810 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
811 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
812};
813
814static int
815bits_in_digit(digit d)
816{
817 int d_bits = 0;
818 while (d >= 32) {
819 d_bits += 6;
820 d >>= 6;
821 }
822 d_bits += (int)BitLengthTable[d];
823 return d_bits;
824}
825
Tim Petersbaefd9e2003-01-28 20:37:45 +0000826size_t
827_PyLong_NumBits(PyObject *vv)
828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 PyLongObject *v = (PyLongObject *)vv;
830 size_t result = 0;
831 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200832 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 assert(v != NULL);
835 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200836 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
838 if (ndigits > 0) {
839 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700840 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100842 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200843 msd_bits = bits_in_digit(msd);
844 if (SIZE_MAX - msd_bits < result)
845 goto Overflow;
846 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 }
848 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000849
Mark Dickinson22b20182010-05-10 21:27:53 +0000850 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
852 "to express in a platform size_t");
853 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000854}
855
Tim Peters2a9b3672001-06-11 21:23:58 +0000856PyObject *
857_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000859{
Mark Dickinson22b20182010-05-10 21:27:53 +0000860 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 int incr; /* direction to move pstartbyte */
862 const unsigned char* pendbyte; /* MSB of bytes */
863 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300864 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 PyLongObject* v; /* result */
866 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (n == 0)
869 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (little_endian) {
872 pstartbyte = bytes;
873 pendbyte = bytes + n - 1;
874 incr = 1;
875 }
876 else {
877 pstartbyte = bytes + n - 1;
878 pendbyte = bytes;
879 incr = -1;
880 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (is_signed)
883 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200886 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 is positive, and leading 0xff bytes if negative. */
888 {
889 size_t i;
890 const unsigned char* p = pendbyte;
891 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000892 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000895 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 break;
897 }
898 numsignificantbytes = n - i;
899 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
900 actually has 2 significant bytes. OTOH, 0xff0001 ==
901 -0x00ffff, so we wouldn't *need* to bump it there; but we
902 do for 0xffff = -0x0001. To be safe without bothering to
903 check every case, bump it regardless. */
904 if (is_signed && numsignificantbytes < n)
905 ++numsignificantbytes;
906 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000907
Serhiy Storchaka95949422013-08-27 19:40:23 +0300908 /* How many Python int digits do we need? We have
909 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
911 /* catch overflow before it happens */
912 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
913 PyErr_SetString(PyExc_OverflowError,
914 "byte array too long to convert to int");
915 return NULL;
916 }
917 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
918 v = _PyLong_New(ndigits);
919 if (v == NULL)
920 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* Copy the bits over. The tricky parts are computing 2's-comp on
923 the fly for signed numbers, and dealing with the mismatch between
924 8-bit bytes and (probably) 15-bit Python digits.*/
925 {
926 size_t i;
927 twodigits carry = 1; /* for 2's-comp calculation */
928 twodigits accum = 0; /* sliding register */
929 unsigned int accumbits = 0; /* number of bits in accum */
930 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
933 twodigits thisbyte = *p;
934 /* Compute correction for 2's comp, if needed. */
935 if (is_signed) {
936 thisbyte = (0xff ^ thisbyte) + carry;
937 carry = thisbyte >> 8;
938 thisbyte &= 0xff;
939 }
940 /* Because we're going LSB to MSB, thisbyte is
941 more significant than what's already in accum,
942 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200943 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 accumbits += 8;
945 if (accumbits >= PyLong_SHIFT) {
946 /* There's enough to fill a Python digit. */
947 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000948 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 ++idigit;
950 accum >>= PyLong_SHIFT;
951 accumbits -= PyLong_SHIFT;
952 assert(accumbits < PyLong_SHIFT);
953 }
954 }
955 assert(accumbits < PyLong_SHIFT);
956 if (accumbits) {
957 assert(idigit < ndigits);
958 v->ob_digit[idigit] = (digit)accum;
959 ++idigit;
960 }
961 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 Py_SIZE(v) = is_signed ? -idigit : idigit;
964 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000965}
966
967int
968_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 unsigned char* bytes, size_t n,
970 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000973 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000975 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
977 digit carry; /* for computing 2's-comp */
978 size_t j; /* # bytes filled */
979 unsigned char* p; /* pointer to next byte in bytes */
980 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (Py_SIZE(v) < 0) {
985 ndigits = -(Py_SIZE(v));
986 if (!is_signed) {
987 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000988 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 return -1;
990 }
991 do_twos_comp = 1;
992 }
993 else {
994 ndigits = Py_SIZE(v);
995 do_twos_comp = 0;
996 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 if (little_endian) {
999 p = bytes;
1000 pincr = 1;
1001 }
1002 else {
1003 p = bytes + n - 1;
1004 pincr = -1;
1005 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 /* Copy over all the Python digits.
1008 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +03001009 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 normalized. */
1011 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
1012 j = 0;
1013 accum = 0;
1014 accumbits = 0;
1015 carry = do_twos_comp ? 1 : 0;
1016 for (i = 0; i < ndigits; ++i) {
1017 digit thisdigit = v->ob_digit[i];
1018 if (do_twos_comp) {
1019 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
1020 carry = thisdigit >> PyLong_SHIFT;
1021 thisdigit &= PyLong_MASK;
1022 }
1023 /* Because we're going LSB to MSB, thisdigit is more
1024 significant than what's already in accum, so needs to be
1025 prepended to accum. */
1026 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* The most-significant digit may be (probably is) at least
1029 partly empty. */
1030 if (i == ndigits - 1) {
1031 /* Count # of sign bits -- they needn't be stored,
1032 * although for signed conversion we need later to
1033 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +00001034 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 while (s != 0) {
1036 s >>= 1;
1037 accumbits++;
1038 }
1039 }
1040 else
1041 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 /* Store as many bytes as possible. */
1044 while (accumbits >= 8) {
1045 if (j >= n)
1046 goto Overflow;
1047 ++j;
1048 *p = (unsigned char)(accum & 0xff);
1049 p += pincr;
1050 accumbits -= 8;
1051 accum >>= 8;
1052 }
1053 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 /* Store the straggler (if any). */
1056 assert(accumbits < 8);
1057 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1058 if (accumbits > 0) {
1059 if (j >= n)
1060 goto Overflow;
1061 ++j;
1062 if (do_twos_comp) {
1063 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +03001064 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 infinite supply of sign bits). */
1066 accum |= (~(twodigits)0) << accumbits;
1067 }
1068 *p = (unsigned char)(accum & 0xff);
1069 p += pincr;
1070 }
1071 else if (j == n && n > 0 && is_signed) {
1072 /* The main loop filled the byte array exactly, so the code
1073 just above didn't get to ensure there's a sign bit, and the
1074 loop below wouldn't add one either. Make sure a sign bit
1075 exists. */
1076 unsigned char msb = *(p - pincr);
1077 int sign_bit_set = msb >= 0x80;
1078 assert(accumbits == 0);
1079 if (sign_bit_set == do_twos_comp)
1080 return 0;
1081 else
1082 goto Overflow;
1083 }
Tim Peters05607ad2001-06-13 21:01:27 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* Fill remaining bytes with copies of the sign bit. */
1086 {
1087 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1088 for ( ; j < n; ++j, p += pincr)
1089 *p = signbyte;
1090 }
Tim Peters05607ad2001-06-13 21:01:27 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001093
Mark Dickinson22b20182010-05-10 21:27:53 +00001094 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1096 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001097
Tim Peters2a9b3672001-06-11 21:23:58 +00001098}
1099
Serhiy Storchaka95949422013-08-27 19:40:23 +03001100/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001101
1102PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001103PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001104{
Mark Dickinson91044792012-10-18 19:21:43 +01001105#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001106 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001107#else
1108
Tim Peters70128a12001-06-16 08:48:40 +00001109#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001110# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001111#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001112 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001113#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001114
Guido van Rossum78694d91998-09-18 14:14:13 +00001115}
1116
Serhiy Storchaka95949422013-08-27 19:40:23 +03001117/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001118
1119void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001120PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001121{
Tim Peters70128a12001-06-16 08:48:40 +00001122#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1126 x = PyLong_AsLong(vv);
1127 else
1128 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001129#else
Tim Peters70128a12001-06-16 08:48:40 +00001130
Tim Peters70128a12001-06-16 08:48:40 +00001131#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001132# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001133#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001134 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1137 x = PyLong_AsLongLong(vv);
1138 else
1139 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001140
1141#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (x == -1 && PyErr_Occurred())
1144 return NULL;
1145 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001146}
1147
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001148/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001149 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001150 */
1151
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001152#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001153
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001154/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001155
1156PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001157PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001160 unsigned long long abs_ival;
1161 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 int ndigits = 0;
1163 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001164
animalize6b519982019-09-06 14:00:56 +08001165 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001166 return get_small_int((sdigit)ival);
1167 }
1168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (ival < 0) {
1170 /* avoid signed overflow on negation; see comments
1171 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001172 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 negative = 1;
1174 }
1175 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001176 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 /* Count the number of Python digits.
1180 We used to pick 5 ("big enough for anything"), but that's a
1181 waste of time and space given that 5*15 = 75 bits are rarely
1182 needed. */
1183 t = abs_ival;
1184 while (t) {
1185 ++ndigits;
1186 t >>= PyLong_SHIFT;
1187 }
1188 v = _PyLong_New(ndigits);
1189 if (v != NULL) {
1190 digit *p = v->ob_digit;
1191 Py_SIZE(v) = negative ? -ndigits : ndigits;
1192 t = abs_ival;
1193 while (t) {
1194 *p++ = (digit)(t & PyLong_MASK);
1195 t >>= PyLong_SHIFT;
1196 }
1197 }
1198 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001199}
1200
Serhiy Storchaka95949422013-08-27 19:40:23 +03001201/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001202
1203PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001204PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 PyLongObject *v;
1207 size_t abs_ival;
1208 size_t t; /* unsigned so >> doesn't propagate sign bit */
1209 int ndigits = 0;
1210 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001211
animalize6b519982019-09-06 14:00:56 +08001212 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001213 return get_small_int((sdigit)ival);
1214 }
1215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (ival < 0) {
1217 /* avoid signed overflow when ival = SIZE_T_MIN */
1218 abs_ival = (size_t)(-1-ival)+1;
1219 negative = 1;
1220 }
1221 else {
1222 abs_ival = (size_t)ival;
1223 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /* Count the number of Python digits. */
1226 t = abs_ival;
1227 while (t) {
1228 ++ndigits;
1229 t >>= PyLong_SHIFT;
1230 }
1231 v = _PyLong_New(ndigits);
1232 if (v != NULL) {
1233 digit *p = v->ob_digit;
1234 Py_SIZE(v) = negative ? -ndigits : ndigits;
1235 t = abs_ival;
1236 while (t) {
1237 *p++ = (digit)(t & PyLong_MASK);
1238 t >>= PyLong_SHIFT;
1239 }
1240 }
1241 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001242}
1243
Serhiy Storchaka95949422013-08-27 19:40:23 +03001244/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001245 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001246
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001247long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001248PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001251 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001253 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (vv == NULL) {
1256 PyErr_BadInternalCall();
1257 return -1;
1258 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001259
1260 if (PyLong_Check(vv)) {
1261 v = (PyLongObject *)vv;
1262 }
1263 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001264 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001265 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001267 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001269
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001270 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001272 case -1:
1273 bytes = -(sdigit)v->ob_digit[0];
1274 break;
1275 case 0:
1276 bytes = 0;
1277 break;
1278 case 1:
1279 bytes = v->ob_digit[0];
1280 break;
1281 default:
1282 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001283 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001285 if (do_decref) {
1286 Py_DECREF(v);
1287 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001288
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001289 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001291 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 else
1293 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001294}
1295
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001296/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001297 Return -1 and set an error if overflow occurs. */
1298
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001299unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001300PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001303 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001305
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001306 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001308 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001310 if (!PyLong_Check(vv)) {
1311 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001312 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001313 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 v = (PyLongObject*)vv;
1316 switch(Py_SIZE(v)) {
1317 case 0: return 0;
1318 case 1: return v->ob_digit[0];
1319 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001320
Mark Dickinson22b20182010-05-10 21:27:53 +00001321 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001322 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001323
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001324 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001326 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 else
1328 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001329}
Tim Petersd1a7da62001-06-13 00:35:57 +00001330
Serhiy Storchaka95949422013-08-27 19:40:23 +03001331/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001332 Returns -1 and sets an error condition if an error occurs. */
1333
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001334static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001335_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001336{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001337 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001338 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 Py_ssize_t i;
1340 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (vv == NULL || !PyLong_Check(vv)) {
1343 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001344 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 }
1346 v = (PyLongObject *)vv;
1347 switch(Py_SIZE(v)) {
1348 case 0: return 0;
1349 case 1: return v->ob_digit[0];
1350 }
1351 i = Py_SIZE(v);
1352 sign = 1;
1353 x = 0;
1354 if (i < 0) {
1355 sign = -1;
1356 i = -i;
1357 }
1358 while (--i >= 0) {
1359 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1360 }
1361 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001362}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001363
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001364unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001365PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001368 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001369
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001370 if (op == NULL) {
1371 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001372 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001374
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001375 if (PyLong_Check(op)) {
1376 return _PyLong_AsUnsignedLongLongMask(op);
1377 }
1378
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001379 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001381 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001382
1383 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1384 Py_DECREF(lo);
1385 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001386}
Tim Petersd1a7da62001-06-13 00:35:57 +00001387
Serhiy Storchaka95949422013-08-27 19:40:23 +03001388/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001389 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001390
Mark Dickinson8d48b432011-10-23 20:47:14 +01001391 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1392 the result. Otherwise *overflow is 0.
1393
1394 For other errors (e.g., TypeError), return -1 and set an error condition.
1395 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001396*/
1397
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001398long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001399PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001402 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001403 unsigned long long x, prev;
1404 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 Py_ssize_t i;
1406 int sign;
1407 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 *overflow = 0;
1410 if (vv == NULL) {
1411 PyErr_BadInternalCall();
1412 return -1;
1413 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001414
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001415 if (PyLong_Check(vv)) {
1416 v = (PyLongObject *)vv;
1417 }
1418 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001419 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001420 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 return -1;
1422 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 switch (i) {
1429 case -1:
1430 res = -(sdigit)v->ob_digit[0];
1431 break;
1432 case 0:
1433 res = 0;
1434 break;
1435 case 1:
1436 res = v->ob_digit[0];
1437 break;
1438 default:
1439 sign = 1;
1440 x = 0;
1441 if (i < 0) {
1442 sign = -1;
1443 i = -(i);
1444 }
1445 while (--i >= 0) {
1446 prev = x;
1447 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1448 if ((x >> PyLong_SHIFT) != prev) {
1449 *overflow = sign;
1450 goto exit;
1451 }
1452 }
1453 /* Haven't lost any bits, but casting to long requires extra
1454 * care (see comment above).
1455 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001456 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001457 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 }
1459 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001460 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 }
1462 else {
1463 *overflow = sign;
1464 /* res is already set to -1 */
1465 }
1466 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001467 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001469 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 }
1471 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001472}
1473
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001474int
1475_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1476{
1477 unsigned long uval;
1478
1479 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1480 PyErr_SetString(PyExc_ValueError, "value must be positive");
1481 return 0;
1482 }
1483 uval = PyLong_AsUnsignedLong(obj);
1484 if (uval == (unsigned long)-1 && PyErr_Occurred())
1485 return 0;
1486 if (uval > USHRT_MAX) {
1487 PyErr_SetString(PyExc_OverflowError,
1488 "Python int too large for C unsigned short");
1489 return 0;
1490 }
1491
1492 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1493 return 1;
1494}
1495
1496int
1497_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1498{
1499 unsigned long uval;
1500
1501 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1502 PyErr_SetString(PyExc_ValueError, "value must be positive");
1503 return 0;
1504 }
1505 uval = PyLong_AsUnsignedLong(obj);
1506 if (uval == (unsigned long)-1 && PyErr_Occurred())
1507 return 0;
1508 if (uval > UINT_MAX) {
1509 PyErr_SetString(PyExc_OverflowError,
1510 "Python int too large for C unsigned int");
1511 return 0;
1512 }
1513
1514 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1515 return 1;
1516}
1517
1518int
1519_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1520{
1521 unsigned long uval;
1522
1523 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1524 PyErr_SetString(PyExc_ValueError, "value must be positive");
1525 return 0;
1526 }
1527 uval = PyLong_AsUnsignedLong(obj);
1528 if (uval == (unsigned long)-1 && PyErr_Occurred())
1529 return 0;
1530
1531 *(unsigned long *)ptr = uval;
1532 return 1;
1533}
1534
1535int
1536_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1537{
1538 unsigned long long uval;
1539
1540 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1541 PyErr_SetString(PyExc_ValueError, "value must be positive");
1542 return 0;
1543 }
1544 uval = PyLong_AsUnsignedLongLong(obj);
1545 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1546 return 0;
1547
1548 *(unsigned long long *)ptr = uval;
1549 return 1;
1550}
1551
1552int
1553_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1554{
1555 size_t uval;
1556
1557 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1558 PyErr_SetString(PyExc_ValueError, "value must be positive");
1559 return 0;
1560 }
1561 uval = PyLong_AsSize_t(obj);
1562 if (uval == (size_t)-1 && PyErr_Occurred())
1563 return 0;
1564
1565 *(size_t *)ptr = uval;
1566 return 1;
1567}
1568
1569
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001570#define CHECK_BINOP(v,w) \
1571 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001572 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1573 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001574 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001575
Tim Peters877a2122002-08-12 05:09:36 +00001576/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1577 * is modified in place, by adding y to it. Carries are propagated as far as
1578 * x[m-1], and the remaining carry (0 or 1) is returned.
1579 */
1580static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001581v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 Py_ssize_t i;
1584 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 assert(m >= n);
1587 for (i = 0; i < n; ++i) {
1588 carry += x[i] + y[i];
1589 x[i] = carry & PyLong_MASK;
1590 carry >>= PyLong_SHIFT;
1591 assert((carry & 1) == carry);
1592 }
1593 for (; carry && i < m; ++i) {
1594 carry += x[i];
1595 x[i] = carry & PyLong_MASK;
1596 carry >>= PyLong_SHIFT;
1597 assert((carry & 1) == carry);
1598 }
1599 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001600}
1601
1602/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1603 * is modified in place, by subtracting y from it. Borrows are propagated as
1604 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1605 */
1606static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001607v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 Py_ssize_t i;
1610 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 assert(m >= n);
1613 for (i = 0; i < n; ++i) {
1614 borrow = x[i] - y[i] - borrow;
1615 x[i] = borrow & PyLong_MASK;
1616 borrow >>= PyLong_SHIFT;
1617 borrow &= 1; /* keep only 1 sign bit */
1618 }
1619 for (; borrow && i < m; ++i) {
1620 borrow = x[i] - borrow;
1621 x[i] = borrow & PyLong_MASK;
1622 borrow >>= PyLong_SHIFT;
1623 borrow &= 1;
1624 }
1625 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001626}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001627
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001628/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1629 * result in z[0:m], and return the d bits shifted out of the top.
1630 */
1631static digit
1632v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 Py_ssize_t i;
1635 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 assert(0 <= d && d < PyLong_SHIFT);
1638 for (i=0; i < m; i++) {
1639 twodigits acc = (twodigits)a[i] << d | carry;
1640 z[i] = (digit)acc & PyLong_MASK;
1641 carry = (digit)(acc >> PyLong_SHIFT);
1642 }
1643 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001644}
1645
1646/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1647 * result in z[0:m], and return the d bits shifted out of the bottom.
1648 */
1649static digit
1650v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 Py_ssize_t i;
1653 digit carry = 0;
1654 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 assert(0 <= d && d < PyLong_SHIFT);
1657 for (i=m; i-- > 0;) {
1658 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1659 carry = (digit)acc & mask;
1660 z[i] = (digit)(acc >> d);
1661 }
1662 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001663}
1664
Tim Peters212e6142001-07-14 12:23:19 +00001665/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1666 in pout, and returning the remainder. pin and pout point at the LSD.
1667 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001668 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001669 immutable. */
1670
1671static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001672inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 assert(n > 0 && n <= PyLong_MASK);
1677 pin += size;
1678 pout += size;
1679 while (--size >= 0) {
1680 digit hi;
1681 rem = (rem << PyLong_SHIFT) | *--pin;
1682 *--pout = hi = (digit)(rem / n);
1683 rem -= (twodigits)hi * n;
1684 }
1685 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001686}
1687
Serhiy Storchaka95949422013-08-27 19:40:23 +03001688/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001689 (as function result) and the remainder (through *prem).
1690 The sign of a is ignored; n should not be zero. */
1691
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001692static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001693divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001694{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001695 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 assert(n > 0 && n <= PyLong_MASK);
1699 z = _PyLong_New(size);
1700 if (z == NULL)
1701 return NULL;
1702 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1703 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001704}
1705
Serhiy Storchaka95949422013-08-27 19:40:23 +03001706/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001707 string. (Return value is non-shared so that callers can modify the
1708 returned value if necessary.) */
1709
Victor Stinnerd3f08822012-05-29 12:57:52 +02001710static int
1711long_to_decimal_string_internal(PyObject *aa,
1712 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001713 _PyUnicodeWriter *writer,
1714 _PyBytesWriter *bytes_writer,
1715 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001718 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 Py_ssize_t size, strlen, size_a, i, j;
1720 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001722 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001723 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 a = (PyLongObject *)aa;
1726 if (a == NULL || !PyLong_Check(a)) {
1727 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001728 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001730 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 /* quick and dirty upper bound for the number of digits
1734 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 But log2(a) < size_a * PyLong_SHIFT, and
1739 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001740 > 3.3 * _PyLong_DECIMAL_SHIFT
1741
1742 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1743 size_a + size_a / d < size_a + size_a / floor(d),
1744 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1745 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001747 d = (33 * _PyLong_DECIMAL_SHIFT) /
1748 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1749 assert(size_a < PY_SSIZE_T_MAX/2);
1750 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 scratch = _PyLong_New(size);
1752 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001753 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 /* convert array of base _PyLong_BASE digits in pin to an array of
1756 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1757 Volume 2 (3rd edn), section 4.4, Method 1b). */
1758 pin = a->ob_digit;
1759 pout = scratch->ob_digit;
1760 size = 0;
1761 for (i = size_a; --i >= 0; ) {
1762 digit hi = pin[i];
1763 for (j = 0; j < size; j++) {
1764 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1765 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1766 pout[j] = (digit)(z - (twodigits)hi *
1767 _PyLong_DECIMAL_BASE);
1768 }
1769 while (hi) {
1770 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1771 hi /= _PyLong_DECIMAL_BASE;
1772 }
1773 /* check for keyboard interrupt */
1774 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001775 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001776 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001777 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 }
1779 /* pout should have at least one digit, so that the case when a = 0
1780 works correctly */
1781 if (size == 0)
1782 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 /* calculate exact length of output string, and allocate */
1785 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1786 tenpow = 10;
1787 rem = pout[size-1];
1788 while (rem >= tenpow) {
1789 tenpow *= 10;
1790 strlen++;
1791 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001792 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001793 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1794 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001795 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001796 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001797 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001799 else if (bytes_writer) {
1800 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1801 if (*bytes_str == NULL) {
1802 Py_DECREF(scratch);
1803 return -1;
1804 }
1805 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001806 else {
1807 str = PyUnicode_New(strlen, '9');
1808 if (str == NULL) {
1809 Py_DECREF(scratch);
1810 return -1;
1811 }
1812 kind = PyUnicode_KIND(str);
1813 }
1814
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001815#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001816 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001817 /* pout[0] through pout[size-2] contribute exactly \
1818 _PyLong_DECIMAL_SHIFT digits each */ \
1819 for (i=0; i < size - 1; i++) { \
1820 rem = pout[i]; \
1821 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1822 *--p = '0' + rem % 10; \
1823 rem /= 10; \
1824 } \
1825 } \
1826 /* pout[size-1]: always produce at least one decimal digit */ \
1827 rem = pout[i]; \
1828 do { \
1829 *--p = '0' + rem % 10; \
1830 rem /= 10; \
1831 } while (rem != 0); \
1832 \
1833 /* and sign */ \
1834 if (negative) \
1835 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001836 } while (0)
1837
1838#define WRITE_UNICODE_DIGITS(TYPE) \
1839 do { \
1840 if (writer) \
1841 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1842 else \
1843 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1844 \
1845 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001846 \
1847 /* check we've counted correctly */ \
1848 if (writer) \
1849 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1850 else \
1851 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1852 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001855 if (bytes_writer) {
1856 char *p = *bytes_str + strlen;
1857 WRITE_DIGITS(p);
1858 assert(p == *bytes_str);
1859 }
1860 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001861 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001862 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001864 else if (kind == PyUnicode_2BYTE_KIND) {
1865 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001866 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001867 }
1868 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001869 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001870 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001871 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001872 }
1873#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001874#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001877 if (writer) {
1878 writer->pos += strlen;
1879 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001880 else if (bytes_writer) {
1881 (*bytes_str) += strlen;
1882 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001883 else {
1884 assert(_PyUnicode_CheckConsistency(str, 1));
1885 *p_output = (PyObject *)str;
1886 }
1887 return 0;
1888}
1889
1890static PyObject *
1891long_to_decimal_string(PyObject *aa)
1892{
1893 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001894 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001895 return NULL;
1896 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001897}
1898
Serhiy Storchaka95949422013-08-27 19:40:23 +03001899/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001900 which should be one of 2, 8 or 16. Return a string object.
1901 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1902 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001903
Victor Stinnerd3f08822012-05-29 12:57:52 +02001904static int
1905long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001906 PyObject **p_output, _PyUnicodeWriter *writer,
1907 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001908{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001909 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001910 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001911 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001913 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001914 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001916
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 if (a == NULL || !PyLong_Check(a)) {
1919 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001922 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001923 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 /* Compute a rough upper bound for the length of the string */
1926 switch (base) {
1927 case 16:
1928 bits = 4;
1929 break;
1930 case 8:
1931 bits = 3;
1932 break;
1933 case 2:
1934 bits = 1;
1935 break;
1936 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001937 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001939
Mark Dickinsone2846542012-04-20 21:21:24 +01001940 /* Compute exact length 'sz' of output string. */
1941 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001942 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001943 }
1944 else {
1945 Py_ssize_t size_a_in_bits;
1946 /* Ensure overflow doesn't occur during computation of sz. */
1947 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1948 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001949 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001950 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001951 }
1952 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1953 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001954 /* Allow 1 character for a '-' sign. */
1955 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1956 }
1957 if (alternate) {
1958 /* 2 characters for prefix */
1959 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001960 }
1961
Victor Stinnerd3f08822012-05-29 12:57:52 +02001962 if (writer) {
1963 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1964 return -1;
1965 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001967 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001968 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1969 if (*bytes_str == NULL)
1970 return -1;
1971 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001973 v = PyUnicode_New(sz, 'x');
1974 if (v == NULL)
1975 return -1;
1976 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001978
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001979#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001980 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001981 if (size_a == 0) { \
1982 *--p = '0'; \
1983 } \
1984 else { \
1985 /* JRH: special case for power-of-2 bases */ \
1986 twodigits accum = 0; \
1987 int accumbits = 0; /* # of bits in accum */ \
1988 Py_ssize_t i; \
1989 for (i = 0; i < size_a; ++i) { \
1990 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1991 accumbits += PyLong_SHIFT; \
1992 assert(accumbits >= bits); \
1993 do { \
1994 char cdigit; \
1995 cdigit = (char)(accum & (base - 1)); \
1996 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1997 *--p = cdigit; \
1998 accumbits -= bits; \
1999 accum >>= bits; \
2000 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
2001 } \
2002 } \
2003 \
2004 if (alternate) { \
2005 if (base == 16) \
2006 *--p = 'x'; \
2007 else if (base == 8) \
2008 *--p = 'o'; \
2009 else /* (base == 2) */ \
2010 *--p = 'b'; \
2011 *--p = '0'; \
2012 } \
2013 if (negative) \
2014 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002015 } while (0)
2016
2017#define WRITE_UNICODE_DIGITS(TYPE) \
2018 do { \
2019 if (writer) \
2020 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
2021 else \
2022 p = (TYPE*)PyUnicode_DATA(v) + sz; \
2023 \
2024 WRITE_DIGITS(p); \
2025 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002026 if (writer) \
2027 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2028 else \
2029 assert(p == (TYPE*)PyUnicode_DATA(v)); \
2030 } while (0)
2031
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002032 if (bytes_writer) {
2033 char *p = *bytes_str + sz;
2034 WRITE_DIGITS(p);
2035 assert(p == *bytes_str);
2036 }
2037 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002038 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002039 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002040 }
2041 else if (kind == PyUnicode_2BYTE_KIND) {
2042 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002043 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002044 }
2045 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002046 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002047 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002048 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002049 }
2050#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002051#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002052
2053 if (writer) {
2054 writer->pos += sz;
2055 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002056 else if (bytes_writer) {
2057 (*bytes_str) += sz;
2058 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002059 else {
2060 assert(_PyUnicode_CheckConsistency(v, 1));
2061 *p_output = v;
2062 }
2063 return 0;
2064}
2065
2066PyObject *
2067_PyLong_Format(PyObject *obj, int base)
2068{
2069 PyObject *str;
2070 int err;
2071 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002072 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002073 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002074 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002075 if (err == -1)
2076 return NULL;
2077 return str;
2078}
2079
2080int
2081_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2082 PyObject *obj,
2083 int base, int alternate)
2084{
2085 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002086 return long_to_decimal_string_internal(obj, NULL, writer,
2087 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002088 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002089 return long_format_binary(obj, base, alternate, NULL, writer,
2090 NULL, NULL);
2091}
2092
2093char*
2094_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2095 PyObject *obj,
2096 int base, int alternate)
2097{
2098 char *str2;
2099 int res;
2100 str2 = str;
2101 if (base == 10)
2102 res = long_to_decimal_string_internal(obj, NULL, NULL,
2103 writer, &str2);
2104 else
2105 res = long_format_binary(obj, base, alternate, NULL, NULL,
2106 writer, &str2);
2107 if (res < 0)
2108 return NULL;
2109 assert(str2 != NULL);
2110 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002111}
2112
Thomas Wouters477c8d52006-05-27 19:21:47 +00002113/* Table of digit values for 8-bit string -> integer conversion.
2114 * '0' maps to 0, ..., '9' maps to 9.
2115 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2116 * All other indices map to 37.
2117 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002118 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002119 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002120unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2122 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2123 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2124 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2125 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2126 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2127 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2128 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2129 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2130 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2134 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2135 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2136 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002137};
2138
2139/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002140 * 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 +03002141 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002142 * The point to this routine is that it takes time linear in the number of
2143 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002144 *
2145 * Return values:
2146 * -1 on syntax error (exception needs to be set, *res is untouched)
2147 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002148 */
Brett Cannona721aba2016-09-09 14:57:09 -07002149static int
2150long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002151{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002152 const char *p = *str;
2153 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002154 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002155 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 int bits_per_char;
2157 Py_ssize_t n;
2158 PyLongObject *z;
2159 twodigits accum;
2160 int bits_in_accum;
2161 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2164 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002165 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002167 }
2168 /* count digits and set p to end-of-string */
2169 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2170 if (*p == '_') {
2171 if (prev == '_') {
2172 *str = p - 1;
2173 return -1;
2174 }
2175 } else {
2176 ++digits;
2177 }
2178 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002180 }
2181 if (prev == '_') {
2182 /* Trailing underscore not allowed. */
2183 *str = p - 1;
2184 return -1;
2185 }
2186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002188 /* n <- the number of Python digits needed,
2189 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2190 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 PyErr_SetString(PyExc_ValueError,
2192 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002193 *res = NULL;
2194 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002196 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002198 if (z == NULL) {
2199 *res = NULL;
2200 return 0;
2201 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002202 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 * from least to most significant in both.
2204 */
2205 accum = 0;
2206 bits_in_accum = 0;
2207 pdigit = z->ob_digit;
2208 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002209 int k;
2210 if (*p == '_') {
2211 continue;
2212 }
2213 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 assert(k >= 0 && k < base);
2215 accum |= (twodigits)k << bits_in_accum;
2216 bits_in_accum += bits_per_char;
2217 if (bits_in_accum >= PyLong_SHIFT) {
2218 *pdigit++ = (digit)(accum & PyLong_MASK);
2219 assert(pdigit - z->ob_digit <= n);
2220 accum >>= PyLong_SHIFT;
2221 bits_in_accum -= PyLong_SHIFT;
2222 assert(bits_in_accum < PyLong_SHIFT);
2223 }
2224 }
2225 if (bits_in_accum) {
2226 assert(bits_in_accum <= PyLong_SHIFT);
2227 *pdigit++ = (digit)accum;
2228 assert(pdigit - z->ob_digit <= n);
2229 }
2230 while (pdigit - z->ob_digit < n)
2231 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002232 *res = long_normalize(z);
2233 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002234}
2235
Serhiy Storchaka95949422013-08-27 19:40:23 +03002236/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002237 * ignored.
2238 *
2239 * If successful, a PyLong object will be returned and 'pend' will be pointing
2240 * to the first unused byte unless it's NULL.
2241 *
2242 * If unsuccessful, NULL will be returned.
2243 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002244PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002245PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002248 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 PyLongObject *z = NULL;
2250 PyObject *strobj;
2251 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 if ((base != 0 && base < 2) || base > 36) {
2254 PyErr_SetString(PyExc_ValueError,
2255 "int() arg 2 must be >= 2 and <= 36");
2256 return NULL;
2257 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002258 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002260 }
2261 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002263 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 else if (*str == '-') {
2265 ++str;
2266 sign = -1;
2267 }
2268 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002269 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002271 }
2272 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002274 }
2275 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002277 }
2278 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 else {
2282 /* "old" (C-style) octal literal, now invalid.
2283 it might still be zero though */
2284 error_if_nonzero = 1;
2285 base = 10;
2286 }
2287 }
2288 if (str[0] == '0' &&
2289 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2290 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002291 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002293 /* One underscore allowed here. */
2294 if (*str == '_') {
2295 ++str;
2296 }
2297 }
2298 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002299 /* May not start with underscores. */
2300 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002301 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002304 if ((base & (base - 1)) == 0) {
2305 int res = long_from_binary_base(&str, base, &z);
2306 if (res < 0) {
2307 /* Syntax error. */
2308 goto onError;
2309 }
2310 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002312/***
2313Binary bases can be converted in time linear in the number of digits, because
2314Python's representation base is binary. Other bases (including decimal!) use
2315the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002316
Thomas Wouters477c8d52006-05-27 19:21:47 +00002317First some math: the largest integer that can be expressed in N base-B digits
2318is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2319case number of Python digits needed to hold it is the smallest integer n s.t.
2320
2321 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2322 BASE**n >= B**N [taking logs to base BASE]
2323 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2324
2325The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002326this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002327and the result is computed into it.
2328
2329The input string is actually treated as being in base base**i (i.e., i digits
2330are processed at a time), where two more static arrays hold:
2331
2332 convwidth_base[base] = the largest integer i such that base**i <= BASE
2333 convmultmax_base[base] = base ** convwidth_base[base]
2334
2335The first of these is the largest i such that i consecutive input digits
2336must fit in a single Python digit. The second is effectively the input
2337base we're really using.
2338
2339Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2340convmultmax_base[base], the result is "simply"
2341
2342 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2343
2344where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002345
2346Error analysis: as above, the number of Python digits `n` needed is worst-
2347case
2348
2349 n >= N * log(B)/log(BASE)
2350
2351where `N` is the number of input digits in base `B`. This is computed via
2352
2353 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2354
2355below. Two numeric concerns are how much space this can waste, and whether
2356the computed result can be too small. To be concrete, assume BASE = 2**15,
2357which is the default (and it's unlikely anyone changes that).
2358
2359Waste isn't a problem: provided the first input digit isn't 0, the difference
2360between the worst-case input with N digits and the smallest input with N
2361digits is about a factor of B, but B is small compared to BASE so at most
2362one allocated Python digit can remain unused on that count. If
2363N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2364and adding 1 returns a result 1 larger than necessary. However, that can't
2365happen: whenever B is a power of 2, long_from_binary_base() is called
2366instead, and it's impossible for B**i to be an integer power of 2**15 when
2367B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2368an exact integer when B is not a power of 2, since B**i has a prime factor
2369other than 2 in that case, but (2**15)**j's only prime factor is 2).
2370
2371The computed result can be too small if the true value of N*log(B)/log(BASE)
2372is a little bit larger than an exact integer, but due to roundoff errors (in
2373computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2374yields a numeric result a little less than that integer. Unfortunately, "how
2375close can a transcendental function get to an integer over some range?"
2376questions are generally theoretically intractable. Computer analysis via
2377continued fractions is practical: expand log(B)/log(BASE) via continued
2378fractions, giving a sequence i/j of "the best" rational approximations. Then
2379j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2380we can get very close to being in trouble, but very rarely. For example,
238176573 is a denominator in one of the continued-fraction approximations to
2382log(10)/log(2**15), and indeed:
2383
2384 >>> log(10)/log(2**15)*76573
2385 16958.000000654003
2386
2387is very close to an integer. If we were working with IEEE single-precision,
2388rounding errors could kill us. Finding worst cases in IEEE double-precision
2389requires better-than-double-precision log() functions, and Tim didn't bother.
2390Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002391new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002392This should happen extremely rarely, and in fact I don't have a test case
2393that triggers it(!). Instead the code was tested by artificially allocating
2394just 1 digit at the start, so that the copying code was exercised for every
2395digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002396***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002397 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002399 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 int i;
2401 int convwidth;
2402 twodigits convmultmax, convmult;
2403 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002404 const char *scan, *lastdigit;
2405 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 static double log_base_BASE[37] = {0.0e0,};
2408 static int convwidth_base[37] = {0,};
2409 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 if (log_base_BASE[base] == 0.0) {
2412 twodigits convmax = base;
2413 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002414
Mark Dickinson22b20182010-05-10 21:27:53 +00002415 log_base_BASE[base] = (log((double)base) /
2416 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 for (;;) {
2418 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002419 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002421 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 convmax = next;
2423 ++i;
2424 }
2425 convmultmax_base[base] = convmax;
2426 assert(i > 0);
2427 convwidth_base[base] = i;
2428 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 /* Find length of the string of numeric characters. */
2431 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002432 lastdigit = str;
2433
2434 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2435 if (*scan == '_') {
2436 if (prev == '_') {
2437 /* Only one underscore allowed. */
2438 str = lastdigit + 1;
2439 goto onError;
2440 }
2441 }
2442 else {
2443 ++digits;
2444 lastdigit = scan;
2445 }
2446 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002448 }
2449 if (prev == '_') {
2450 /* Trailing underscore not allowed. */
2451 /* Set error pointer to first underscore. */
2452 str = lastdigit + 1;
2453 goto onError;
2454 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002455
Serhiy Storchaka95949422013-08-27 19:40:23 +03002456 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 * integer with this base and length. Note that there's no
2458 * need to initialize z->ob_digit -- no slot is read up before
2459 * being stored into.
2460 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002461 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2462 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002463 /* The same exception as in _PyLong_New(). */
2464 PyErr_SetString(PyExc_OverflowError,
2465 "too many digits in integer");
2466 return NULL;
2467 }
2468 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 /* Uncomment next line to test exceedingly rare copy code */
2470 /* size_z = 1; */
2471 assert(size_z > 0);
2472 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002473 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002475 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 /* `convwidth` consecutive input digits are treated as a single
2479 * digit in base `convmultmax`.
2480 */
2481 convwidth = convwidth_base[base];
2482 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 /* Work ;-) */
2485 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002486 if (*str == '_') {
2487 str++;
2488 continue;
2489 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* grab up to convwidth digits from the input string */
2491 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002492 for (i = 1; i < convwidth && str != scan; ++str) {
2493 if (*str == '_') {
2494 continue;
2495 }
2496 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002498 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 assert(c < PyLong_BASE);
2500 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 convmult = convmultmax;
2503 /* Calculate the shift only if we couldn't get
2504 * convwidth digits.
2505 */
2506 if (i != convwidth) {
2507 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002508 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002510 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 /* Multiply z by convmult, and add c. */
2514 pz = z->ob_digit;
2515 pzstop = pz + Py_SIZE(z);
2516 for (; pz < pzstop; ++pz) {
2517 c += (twodigits)*pz * convmult;
2518 *pz = (digit)(c & PyLong_MASK);
2519 c >>= PyLong_SHIFT;
2520 }
2521 /* carry off the current end? */
2522 if (c) {
2523 assert(c < PyLong_BASE);
2524 if (Py_SIZE(z) < size_z) {
2525 *pz = (digit)c;
2526 ++Py_SIZE(z);
2527 }
2528 else {
2529 PyLongObject *tmp;
2530 /* Extremely rare. Get more space. */
2531 assert(Py_SIZE(z) == size_z);
2532 tmp = _PyLong_New(size_z + 1);
2533 if (tmp == NULL) {
2534 Py_DECREF(z);
2535 return NULL;
2536 }
2537 memcpy(tmp->ob_digit,
2538 z->ob_digit,
2539 sizeof(digit) * size_z);
2540 Py_DECREF(z);
2541 z = tmp;
2542 z->ob_digit[size_z] = (digit)c;
2543 ++size_z;
2544 }
2545 }
2546 }
2547 }
Brett Cannona721aba2016-09-09 14:57:09 -07002548 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002550 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 if (error_if_nonzero) {
2552 /* reset the base to 0, else the exception message
2553 doesn't make too much sense */
2554 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002555 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002557 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 /* there might still be other problems, therefore base
2559 remains zero here for the same reason */
2560 }
Brett Cannona721aba2016-09-09 14:57:09 -07002561 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002563 }
2564 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002566 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002567 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002569 }
2570 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002572 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002574 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002575 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002576 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002577 }
2578 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002579 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002580 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002581 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002582
Mark Dickinson22b20182010-05-10 21:27:53 +00002583 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002584 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002585 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002586 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 Py_XDECREF(z);
2588 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2589 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002590 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002594 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 base, strobj);
2596 Py_DECREF(strobj);
2597 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002598}
2599
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002600/* Since PyLong_FromString doesn't have a length parameter,
2601 * check here for possible NULs in the string.
2602 *
2603 * Reports an invalid literal as a bytes object.
2604 */
2605PyObject *
2606_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2607{
2608 PyObject *result, *strobj;
2609 char *end = NULL;
2610
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002611 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002612 if (end == NULL || (result != NULL && end == s + len))
2613 return result;
2614 Py_XDECREF(result);
2615 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2616 if (strobj != NULL) {
2617 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002618 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002619 base, strobj);
2620 Py_DECREF(strobj);
2621 }
2622 return NULL;
2623}
2624
Guido van Rossum9e896b32000-04-05 20:11:21 +00002625PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002626PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002627{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002628 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002629 if (unicode == NULL)
2630 return NULL;
2631 v = PyLong_FromUnicodeObject(unicode, base);
2632 Py_DECREF(unicode);
2633 return v;
2634}
2635
2636PyObject *
2637PyLong_FromUnicodeObject(PyObject *u, int base)
2638{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002639 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002640 const char *buffer;
2641 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002642 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002643
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002644 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002645 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002647 assert(PyUnicode_IS_ASCII(asciidig));
2648 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002649 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002650 assert(buffer != NULL);
2651
2652 result = PyLong_FromString(buffer, &end, base);
2653 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002654 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002655 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002657 Py_DECREF(asciidig);
2658 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002659 PyErr_Format(PyExc_ValueError,
2660 "invalid literal for int() with base %d: %.200R",
2661 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002662 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002663}
2664
Tim Peters9f688bf2000-07-07 15:53:28 +00002665/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002666static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002668static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002669
Serhiy Storchaka95949422013-08-27 19:40:23 +03002670/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002671
Guido van Rossume32e0141992-01-19 16:31:05 +00002672static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002673long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002675{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002676 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 if (size_b == 0) {
2680 PyErr_SetString(PyExc_ZeroDivisionError,
2681 "integer division or modulo by zero");
2682 return -1;
2683 }
2684 if (size_a < size_b ||
2685 (size_a == size_b &&
2686 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2687 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002688 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002689 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002690 return -1;
2691 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002692 Py_INCREF(_PyLong_Zero);
2693 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 return 0;
2695 }
2696 if (size_b == 1) {
2697 digit rem = 0;
2698 z = divrem1(a, b->ob_digit[0], &rem);
2699 if (z == NULL)
2700 return -1;
2701 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2702 if (*prem == NULL) {
2703 Py_DECREF(z);
2704 return -1;
2705 }
2706 }
2707 else {
2708 z = x_divrem(a, b, prem);
2709 if (z == NULL)
2710 return -1;
2711 }
2712 /* Set the signs.
2713 The quotient z has the sign of a*b;
2714 the remainder r has the sign of a,
2715 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002716 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2717 _PyLong_Negate(&z);
2718 if (z == NULL) {
2719 Py_CLEAR(*prem);
2720 return -1;
2721 }
2722 }
2723 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2724 _PyLong_Negate(prem);
2725 if (*prem == NULL) {
2726 Py_DECREF(z);
2727 Py_CLEAR(*prem);
2728 return -1;
2729 }
2730 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 *pdiv = maybe_small_long(z);
2732 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002733}
2734
Serhiy Storchaka95949422013-08-27 19:40:23 +03002735/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002736 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002737
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002738static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002739x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 PyLongObject *v, *w, *a;
2742 Py_ssize_t i, k, size_v, size_w;
2743 int d;
2744 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2745 twodigits vv;
2746 sdigit zhi;
2747 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2750 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2751 handle the special case when the initial estimate q for a quotient
2752 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2753 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002756 size_v = Py_ABS(Py_SIZE(v1));
2757 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2759 v = _PyLong_New(size_v+1);
2760 if (v == NULL) {
2761 *prem = NULL;
2762 return NULL;
2763 }
2764 w = _PyLong_New(size_w);
2765 if (w == NULL) {
2766 Py_DECREF(v);
2767 *prem = NULL;
2768 return NULL;
2769 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2772 shift v1 left by the same amount. Results go into w and v. */
2773 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2774 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2775 assert(carry == 0);
2776 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2777 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2778 v->ob_digit[size_v] = carry;
2779 size_v++;
2780 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2783 at most (and usually exactly) k = size_v - size_w digits. */
2784 k = size_v - size_w;
2785 assert(k >= 0);
2786 a = _PyLong_New(k);
2787 if (a == NULL) {
2788 Py_DECREF(w);
2789 Py_DECREF(v);
2790 *prem = NULL;
2791 return NULL;
2792 }
2793 v0 = v->ob_digit;
2794 w0 = w->ob_digit;
2795 wm1 = w0[size_w-1];
2796 wm2 = w0[size_w-2];
2797 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2798 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2799 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002802 Py_DECREF(a);
2803 Py_DECREF(w);
2804 Py_DECREF(v);
2805 *prem = NULL;
2806 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002807 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 /* estimate quotient digit q; may overestimate by 1 (rare) */
2810 vtop = vk[size_w];
2811 assert(vtop <= wm1);
2812 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2813 q = (digit)(vv / wm1);
2814 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2815 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2816 | vk[size_w-2])) {
2817 --q;
2818 r += wm1;
2819 if (r >= PyLong_BASE)
2820 break;
2821 }
2822 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2825 zhi = 0;
2826 for (i = 0; i < size_w; ++i) {
2827 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2828 -PyLong_BASE * q <= z < PyLong_BASE */
2829 z = (sdigit)vk[i] + zhi -
2830 (stwodigits)q * (stwodigits)w0[i];
2831 vk[i] = (digit)z & PyLong_MASK;
2832 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002833 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 /* add w back if q was too large (this branch taken rarely) */
2837 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2838 if ((sdigit)vtop + zhi < 0) {
2839 carry = 0;
2840 for (i = 0; i < size_w; ++i) {
2841 carry += vk[i] + w0[i];
2842 vk[i] = carry & PyLong_MASK;
2843 carry >>= PyLong_SHIFT;
2844 }
2845 --q;
2846 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 /* store quotient digit */
2849 assert(q < PyLong_BASE);
2850 *--ak = q;
2851 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 /* unshift remainder; we reuse w to store the result */
2854 carry = v_rshift(w0, v0, size_w, d);
2855 assert(carry==0);
2856 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 *prem = long_normalize(w);
2859 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002860}
2861
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002862/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2863 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2864 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2865 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2866 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2867 -1.0. */
2868
2869/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2870#if DBL_MANT_DIG == 53
2871#define EXP2_DBL_MANT_DIG 9007199254740992.0
2872#else
2873#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2874#endif
2875
2876double
2877_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2880 /* See below for why x_digits is always large enough. */
2881 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2882 double dx;
2883 /* Correction term for round-half-to-even rounding. For a digit x,
2884 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2885 multiple of 4, rounding ties to a multiple of 8. */
2886 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002887
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002888 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 if (a_size == 0) {
2890 /* Special case for 0: significand 0.0, exponent 0. */
2891 *e = 0;
2892 return 0.0;
2893 }
2894 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2895 /* The following is an overflow-free version of the check
2896 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2897 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2898 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2899 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002900 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2904 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 Number of digits needed for result: write // for floor division.
2907 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2916 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2919 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2920 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 in both cases.
2927 */
2928 if (a_bits <= DBL_MANT_DIG + 2) {
2929 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2930 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2931 x_size = 0;
2932 while (x_size < shift_digits)
2933 x_digits[x_size++] = 0;
2934 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2935 (int)shift_bits);
2936 x_size += a_size;
2937 x_digits[x_size++] = rem;
2938 }
2939 else {
2940 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2941 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2942 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2943 a_size - shift_digits, (int)shift_bits);
2944 x_size = a_size - shift_digits;
2945 /* For correct rounding below, we need the least significant
2946 bit of x to be 'sticky' for this shift: if any of the bits
2947 shifted out was nonzero, we set the least significant bit
2948 of x. */
2949 if (rem)
2950 x_digits[0] |= 1;
2951 else
2952 while (shift_digits > 0)
2953 if (a->ob_digit[--shift_digits]) {
2954 x_digits[0] |= 1;
2955 break;
2956 }
2957 }
Victor Stinner63941882011-09-29 00:42:28 +02002958 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 /* Round, and convert to double. */
2961 x_digits[0] += half_even_correction[x_digits[0] & 7];
2962 dx = x_digits[--x_size];
2963 while (x_size > 0)
2964 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 /* Rescale; make correction if result is 1.0. */
2967 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2968 if (dx == 1.0) {
2969 if (a_bits == PY_SSIZE_T_MAX)
2970 goto overflow;
2971 dx = 0.5;
2972 a_bits += 1;
2973 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 *e = a_bits;
2976 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002977
2978 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 /* exponent > PY_SSIZE_T_MAX */
2980 PyErr_SetString(PyExc_OverflowError,
2981 "huge integer: number of bits overflows a Py_ssize_t");
2982 *e = 0;
2983 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002984}
2985
Serhiy Storchaka95949422013-08-27 19:40:23 +03002986/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002987 using the round-half-to-even rule in the case of a tie. */
2988
2989double
2990PyLong_AsDouble(PyObject *v)
2991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 Py_ssize_t exponent;
2993 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002994
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002995 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 PyErr_BadInternalCall();
2997 return -1.0;
2998 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002999 if (!PyLong_Check(v)) {
3000 PyErr_SetString(PyExc_TypeError, "an integer is required");
3001 return -1.0;
3002 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05003003 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05003004 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01003005 to double. This improves performance of FP/long operations
3006 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05003007 */
3008 return (double)MEDIUM_VALUE((PyLongObject *)v);
3009 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
3011 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
3012 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01003013 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 return -1.0;
3015 }
3016 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003017}
3018
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003019/* Methods */
3020
HongWeipeng42acb7b2019-09-18 23:10:15 +08003021/* if a < b, return a negative number
3022 if a == b, return 0
3023 if a > b, return a positive number */
3024
3025static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003026long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003027{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003028 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
3029 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003030 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08003031 sdigit diff = 0;
3032 while (--i >= 0) {
3033 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
3034 if (diff) {
3035 break;
3036 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003038 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003040 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003041}
3042
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003043static PyObject *
3044long_richcompare(PyObject *self, PyObject *other, int op)
3045{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003046 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 CHECK_BINOP(self, other);
3048 if (self == other)
3049 result = 0;
3050 else
3051 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003052 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003053}
3054
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003055static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003056long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003057{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003058 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 Py_ssize_t i;
3060 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 i = Py_SIZE(v);
3063 switch(i) {
3064 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3065 case 0: return 0;
3066 case 1: return v->ob_digit[0];
3067 }
3068 sign = 1;
3069 x = 0;
3070 if (i < 0) {
3071 sign = -1;
3072 i = -(i);
3073 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003075 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3076 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3077 _PyHASH_MODULUS.
3078
3079 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3080 amounts to a rotation of the bits of x. To see this, write
3081
3082 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3083
3084 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3085 PyLong_SHIFT bits of x (those that are shifted out of the
3086 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3087 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3088 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3089 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3090 congruent to y modulo _PyHASH_MODULUS. So
3091
3092 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3093
3094 The right-hand side is just the result of rotating the
3095 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3096 not all _PyHASH_BITS bits of x are 1s, the same is true
3097 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3098 the reduction of x*2**PyLong_SHIFT modulo
3099 _PyHASH_MODULUS. */
3100 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3101 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003103 if (x >= _PyHASH_MODULUS)
3104 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 }
3106 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003107 if (x == (Py_uhash_t)-1)
3108 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003109 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003110}
3111
3112
Serhiy Storchaka95949422013-08-27 19:40:23 +03003113/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003114
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003115static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003116x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003117{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003118 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 PyLongObject *z;
3120 Py_ssize_t i;
3121 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 /* Ensure a is the larger of the two: */
3124 if (size_a < size_b) {
3125 { PyLongObject *temp = a; a = b; b = temp; }
3126 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003127 size_a = size_b;
3128 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 }
3130 z = _PyLong_New(size_a+1);
3131 if (z == NULL)
3132 return NULL;
3133 for (i = 0; i < size_b; ++i) {
3134 carry += a->ob_digit[i] + b->ob_digit[i];
3135 z->ob_digit[i] = carry & PyLong_MASK;
3136 carry >>= PyLong_SHIFT;
3137 }
3138 for (; i < size_a; ++i) {
3139 carry += a->ob_digit[i];
3140 z->ob_digit[i] = carry & PyLong_MASK;
3141 carry >>= PyLong_SHIFT;
3142 }
3143 z->ob_digit[i] = carry;
3144 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003145}
3146
3147/* Subtract the absolute values of two integers. */
3148
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003149static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003150x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003151{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003152 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 PyLongObject *z;
3154 Py_ssize_t i;
3155 int sign = 1;
3156 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 /* Ensure a is the larger of the two: */
3159 if (size_a < size_b) {
3160 sign = -1;
3161 { PyLongObject *temp = a; a = b; b = temp; }
3162 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003163 size_a = size_b;
3164 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 }
3166 else if (size_a == size_b) {
3167 /* Find highest digit where a and b differ: */
3168 i = size_a;
3169 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3170 ;
3171 if (i < 0)
3172 return (PyLongObject *)PyLong_FromLong(0);
3173 if (a->ob_digit[i] < b->ob_digit[i]) {
3174 sign = -1;
3175 { PyLongObject *temp = a; a = b; b = temp; }
3176 }
3177 size_a = size_b = i+1;
3178 }
3179 z = _PyLong_New(size_a);
3180 if (z == NULL)
3181 return NULL;
3182 for (i = 0; i < size_b; ++i) {
3183 /* The following assumes unsigned arithmetic
3184 works module 2**N for some N>PyLong_SHIFT. */
3185 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3186 z->ob_digit[i] = borrow & PyLong_MASK;
3187 borrow >>= PyLong_SHIFT;
3188 borrow &= 1; /* Keep only one sign bit */
3189 }
3190 for (; i < size_a; ++i) {
3191 borrow = a->ob_digit[i] - borrow;
3192 z->ob_digit[i] = borrow & PyLong_MASK;
3193 borrow >>= PyLong_SHIFT;
3194 borrow &= 1; /* Keep only one sign bit */
3195 }
3196 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003197 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003198 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003199 }
HongWeipeng036fe852019-11-26 15:54:49 +08003200 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003201}
3202
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003203static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003204long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003209
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003210 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003211 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 }
3213 if (Py_SIZE(a) < 0) {
3214 if (Py_SIZE(b) < 0) {
3215 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003216 if (z != NULL) {
3217 /* x_add received at least one multiple-digit int,
3218 and thus z must be a multiple-digit int.
3219 That also means z is not an element of
3220 small_ints, so negating it in-place is safe. */
3221 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003223 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 }
3225 else
3226 z = x_sub(b, a);
3227 }
3228 else {
3229 if (Py_SIZE(b) < 0)
3230 z = x_sub(a, b);
3231 else
3232 z = x_add(a, b);
3233 }
3234 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003235}
3236
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003237static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003238long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003243
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003244 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003245 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 }
3247 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003248 if (Py_SIZE(b) < 0) {
3249 z = x_sub(b, a);
3250 }
3251 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003253 if (z != NULL) {
3254 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
3255 Py_SIZE(z) = -(Py_SIZE(z));
3256 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003257 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 }
3259 else {
3260 if (Py_SIZE(b) < 0)
3261 z = x_add(a, b);
3262 else
3263 z = x_sub(a, b);
3264 }
3265 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003266}
3267
Tim Peters5af4e6c2002-08-12 02:31:19 +00003268/* Grade school multiplication, ignoring the signs.
3269 * Returns the absolute value of the product, or NULL if error.
3270 */
3271static PyLongObject *
3272x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003275 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3276 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 z = _PyLong_New(size_a + size_b);
3280 if (z == NULL)
3281 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3284 if (a == b) {
3285 /* Efficient squaring per HAC, Algorithm 14.16:
3286 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3287 * Gives slightly less than a 2x speedup when a == b,
3288 * via exploiting that each entry in the multiplication
3289 * pyramid appears twice (except for the size_a squares).
3290 */
3291 for (i = 0; i < size_a; ++i) {
3292 twodigits carry;
3293 twodigits f = a->ob_digit[i];
3294 digit *pz = z->ob_digit + (i << 1);
3295 digit *pa = a->ob_digit + i + 1;
3296 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003299 Py_DECREF(z);
3300 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003301 });
Tim Peters0973b992004-08-29 22:16:50 +00003302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 carry = *pz + f * f;
3304 *pz++ = (digit)(carry & PyLong_MASK);
3305 carry >>= PyLong_SHIFT;
3306 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 /* Now f is added in twice in each column of the
3309 * pyramid it appears. Same as adding f<<1 once.
3310 */
3311 f <<= 1;
3312 while (pa < paend) {
3313 carry += *pz + *pa++ * f;
3314 *pz++ = (digit)(carry & PyLong_MASK);
3315 carry >>= PyLong_SHIFT;
3316 assert(carry <= (PyLong_MASK << 1));
3317 }
3318 if (carry) {
3319 carry += *pz;
3320 *pz++ = (digit)(carry & PyLong_MASK);
3321 carry >>= PyLong_SHIFT;
3322 }
3323 if (carry)
3324 *pz += (digit)(carry & PyLong_MASK);
3325 assert((carry >> PyLong_SHIFT) == 0);
3326 }
3327 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003328 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 for (i = 0; i < size_a; ++i) {
3330 twodigits carry = 0;
3331 twodigits f = a->ob_digit[i];
3332 digit *pz = z->ob_digit + i;
3333 digit *pb = b->ob_digit;
3334 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003337 Py_DECREF(z);
3338 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003339 });
Tim Peters0973b992004-08-29 22:16:50 +00003340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 while (pb < pbend) {
3342 carry += *pz + *pb++ * f;
3343 *pz++ = (digit)(carry & PyLong_MASK);
3344 carry >>= PyLong_SHIFT;
3345 assert(carry <= PyLong_MASK);
3346 }
3347 if (carry)
3348 *pz += (digit)(carry & PyLong_MASK);
3349 assert((carry >> PyLong_SHIFT) == 0);
3350 }
3351 }
3352 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003353}
3354
3355/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003356 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003357 split, and sets low and high such that abs(n) == (high << size) + low,
3358 viewing the shift as being by digits. The sign bit is ignored, and
3359 the return values are >= 0.
3360 Returns 0 on success, -1 on failure.
3361*/
3362static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003363kmul_split(PyLongObject *n,
3364 Py_ssize_t size,
3365 PyLongObject **high,
3366 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 PyLongObject *hi, *lo;
3369 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003370 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003371
Victor Stinner640c35c2013-06-04 23:14:37 +02003372 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 if ((hi = _PyLong_New(size_hi)) == NULL)
3376 return -1;
3377 if ((lo = _PyLong_New(size_lo)) == NULL) {
3378 Py_DECREF(hi);
3379 return -1;
3380 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3383 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 *high = long_normalize(hi);
3386 *low = long_normalize(lo);
3387 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003388}
3389
Tim Peters60004642002-08-12 22:01:34 +00003390static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3391
Tim Peters5af4e6c2002-08-12 02:31:19 +00003392/* Karatsuba multiplication. Ignores the input signs, and returns the
3393 * absolute value of the product (or NULL if error).
3394 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3395 */
3396static PyLongObject *
3397k_mul(PyLongObject *a, PyLongObject *b)
3398{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003399 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3400 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 PyLongObject *ah = NULL;
3402 PyLongObject *al = NULL;
3403 PyLongObject *bh = NULL;
3404 PyLongObject *bl = NULL;
3405 PyLongObject *ret = NULL;
3406 PyLongObject *t1, *t2, *t3;
3407 Py_ssize_t shift; /* the number of digits we split off */
3408 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3411 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3412 * Then the original product is
3413 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3414 * By picking X to be a power of 2, "*X" is just shifting, and it's
3415 * been reduced to 3 multiplies on numbers half the size.
3416 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 /* We want to split based on the larger number; fiddle so that b
3419 * is largest.
3420 */
3421 if (asize > bsize) {
3422 t1 = a;
3423 a = b;
3424 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 i = asize;
3427 asize = bsize;
3428 bsize = i;
3429 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 /* Use gradeschool math when either number is too small. */
3432 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3433 if (asize <= i) {
3434 if (asize == 0)
3435 return (PyLongObject *)PyLong_FromLong(0);
3436 else
3437 return x_mul(a, b);
3438 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 /* If a is small compared to b, splitting on b gives a degenerate
3441 * case with ah==0, and Karatsuba may be (even much) less efficient
3442 * than "grade school" then. However, we can still win, by viewing
3443 * b as a string of "big digits", each of width a->ob_size. That
3444 * leads to a sequence of balanced calls to k_mul.
3445 */
3446 if (2 * asize <= bsize)
3447 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 /* Split a & b into hi & lo pieces. */
3450 shift = bsize >> 1;
3451 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3452 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 if (a == b) {
3455 bh = ah;
3456 bl = al;
3457 Py_INCREF(bh);
3458 Py_INCREF(bl);
3459 }
3460 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 /* The plan:
3463 * 1. Allocate result space (asize + bsize digits: that's always
3464 * enough).
3465 * 2. Compute ah*bh, and copy into result at 2*shift.
3466 * 3. Compute al*bl, and copy into result at 0. Note that this
3467 * can't overlap with #2.
3468 * 4. Subtract al*bl from the result, starting at shift. This may
3469 * underflow (borrow out of the high digit), but we don't care:
3470 * we're effectively doing unsigned arithmetic mod
3471 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3472 * borrows and carries out of the high digit can be ignored.
3473 * 5. Subtract ah*bh from the result, starting at shift.
3474 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3475 * at shift.
3476 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 /* 1. Allocate result space. */
3479 ret = _PyLong_New(asize + bsize);
3480 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003481#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 /* Fill with trash, to catch reference to uninitialized digits. */
3483 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003484#endif
Tim Peters44121a62002-08-12 06:17:58 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3487 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3488 assert(Py_SIZE(t1) >= 0);
3489 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3490 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3491 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 /* Zero-out the digits higher than the ah*bh copy. */
3494 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3495 if (i)
3496 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3497 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 /* 3. t2 <- al*bl, and copy into the low digits. */
3500 if ((t2 = k_mul(al, bl)) == NULL) {
3501 Py_DECREF(t1);
3502 goto fail;
3503 }
3504 assert(Py_SIZE(t2) >= 0);
3505 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3506 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 /* Zero out remaining digits. */
3509 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3510 if (i)
3511 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3514 * because it's fresher in cache.
3515 */
3516 i = Py_SIZE(ret) - shift; /* # digits after shift */
3517 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3518 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3521 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3524 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3525 Py_DECREF(ah);
3526 Py_DECREF(al);
3527 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 if (a == b) {
3530 t2 = t1;
3531 Py_INCREF(t2);
3532 }
3533 else if ((t2 = x_add(bh, bl)) == NULL) {
3534 Py_DECREF(t1);
3535 goto fail;
3536 }
3537 Py_DECREF(bh);
3538 Py_DECREF(bl);
3539 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 t3 = k_mul(t1, t2);
3542 Py_DECREF(t1);
3543 Py_DECREF(t2);
3544 if (t3 == NULL) goto fail;
3545 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 /* Add t3. It's not obvious why we can't run out of room here.
3548 * See the (*) comment after this function.
3549 */
3550 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3551 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003554
Mark Dickinson22b20182010-05-10 21:27:53 +00003555 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 Py_XDECREF(ret);
3557 Py_XDECREF(ah);
3558 Py_XDECREF(al);
3559 Py_XDECREF(bh);
3560 Py_XDECREF(bl);
3561 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003562}
3563
Tim Petersd6974a52002-08-13 20:37:51 +00003564/* (*) Why adding t3 can't "run out of room" above.
3565
Tim Petersab86c2b2002-08-15 20:06:00 +00003566Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3567to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003568
Tim Petersab86c2b2002-08-15 20:06:00 +000035691. For any integer i, i = c(i/2) + f(i/2). In particular,
3570 bsize = c(bsize/2) + f(bsize/2).
35712. shift = f(bsize/2)
35723. asize <= bsize
35734. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3574 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003575
Tim Petersab86c2b2002-08-15 20:06:00 +00003576We allocated asize + bsize result digits, and add t3 into them at an offset
3577of shift. This leaves asize+bsize-shift allocated digit positions for t3
3578to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3579asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003580
Tim Petersab86c2b2002-08-15 20:06:00 +00003581bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3582at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003583
Tim Petersab86c2b2002-08-15 20:06:00 +00003584If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3585digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3586most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003587
Tim Petersab86c2b2002-08-15 20:06:00 +00003588The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003589
Tim Petersab86c2b2002-08-15 20:06:00 +00003590 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003591
Tim Petersab86c2b2002-08-15 20:06:00 +00003592and we have asize + c(bsize/2) available digit positions. We need to show
3593this is always enough. An instance of c(bsize/2) cancels out in both, so
3594the question reduces to whether asize digits is enough to hold
3595(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3596then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3597asize 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 +00003598digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003599asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003600c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3601is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3602bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003603
Tim Peters48d52c02002-08-14 17:07:32 +00003604Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3605clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3606ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003607*/
3608
Tim Peters60004642002-08-12 22:01:34 +00003609/* b has at least twice the digits of a, and a is big enough that Karatsuba
3610 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3611 * of slices, each with a->ob_size digits, and multiply the slices by a,
3612 * one at a time. This gives k_mul balanced inputs to work with, and is
3613 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003614 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003615 * single-width slice overlap between successive partial sums).
3616 */
3617static PyLongObject *
3618k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3619{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003620 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3621 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 Py_ssize_t nbdone; /* # of b digits already multiplied */
3623 PyLongObject *ret;
3624 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 assert(asize > KARATSUBA_CUTOFF);
3627 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 /* Allocate result space, and zero it out. */
3630 ret = _PyLong_New(asize + bsize);
3631 if (ret == NULL)
3632 return NULL;
3633 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 /* Successive slices of b are copied into bslice. */
3636 bslice = _PyLong_New(asize);
3637 if (bslice == NULL)
3638 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 nbdone = 0;
3641 while (bsize > 0) {
3642 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003643 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 /* Multiply the next slice of b by a. */
3646 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3647 nbtouse * sizeof(digit));
3648 Py_SIZE(bslice) = nbtouse;
3649 product = k_mul(a, bslice);
3650 if (product == NULL)
3651 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 /* Add into result. */
3654 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3655 product->ob_digit, Py_SIZE(product));
3656 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 bsize -= nbtouse;
3659 nbdone += nbtouse;
3660 }
Tim Peters60004642002-08-12 22:01:34 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 Py_DECREF(bslice);
3663 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003664
Mark Dickinson22b20182010-05-10 21:27:53 +00003665 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 Py_DECREF(ret);
3667 Py_XDECREF(bslice);
3668 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003669}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003670
3671static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003672long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003679 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003681 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 z = k_mul(a, b);
3685 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003686 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3687 _PyLong_Negate(&z);
3688 if (z == NULL)
3689 return NULL;
3690 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003692}
3693
Yury Selivanove0b23092016-02-11 10:26:27 -05003694/* Fast modulo division for single-digit longs. */
3695static PyObject *
3696fast_mod(PyLongObject *a, PyLongObject *b)
3697{
3698 sdigit left = a->ob_digit[0];
3699 sdigit right = b->ob_digit[0];
3700 sdigit mod;
3701
3702 assert(Py_ABS(Py_SIZE(a)) == 1);
3703 assert(Py_ABS(Py_SIZE(b)) == 1);
3704
3705 if (Py_SIZE(a) == Py_SIZE(b)) {
3706 /* 'a' and 'b' have the same sign. */
3707 mod = left % right;
3708 }
3709 else {
3710 /* Either 'a' or 'b' is negative. */
3711 mod = right - 1 - (left - 1) % right;
3712 }
3713
Victor Stinnerf963c132016-03-23 18:36:54 +01003714 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003715}
3716
3717/* Fast floor division for single-digit longs. */
3718static PyObject *
3719fast_floor_div(PyLongObject *a, PyLongObject *b)
3720{
3721 sdigit left = a->ob_digit[0];
3722 sdigit right = b->ob_digit[0];
3723 sdigit div;
3724
3725 assert(Py_ABS(Py_SIZE(a)) == 1);
3726 assert(Py_ABS(Py_SIZE(b)) == 1);
3727
3728 if (Py_SIZE(a) == Py_SIZE(b)) {
3729 /* 'a' and 'b' have the same sign. */
3730 div = left / right;
3731 }
3732 else {
3733 /* Either 'a' or 'b' is negative. */
3734 div = -1 - (left - 1) / right;
3735 }
3736
3737 return PyLong_FromLong(div);
3738}
3739
Guido van Rossume32e0141992-01-19 16:31:05 +00003740/* The / and % operators are now defined in terms of divmod().
3741 The expression a mod b has the value a - b*floor(a/b).
3742 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003743 |a| by |b|, with the sign of a. This is also expressed
3744 as a - b*trunc(a/b), if trunc truncates towards zero.
3745 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 a b a rem b a mod b
3747 13 10 3 3
3748 -13 10 -3 7
3749 13 -10 3 -7
3750 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003751 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003752 have different signs. We then subtract one from the 'div'
3753 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003754
Tim Peters47e52ee2004-08-30 02:44:38 +00003755/* Compute
3756 * *pdiv, *pmod = divmod(v, w)
3757 * NULL can be passed for pdiv or pmod, in which case that part of
3758 * the result is simply thrown away. The caller owns a reference to
3759 * each of these it requests (does not pass NULL for).
3760 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003761static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003762l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003766
Yury Selivanove0b23092016-02-11 10:26:27 -05003767 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3768 /* Fast path for single-digit longs */
3769 div = NULL;
3770 if (pdiv != NULL) {
3771 div = (PyLongObject *)fast_floor_div(v, w);
3772 if (div == NULL) {
3773 return -1;
3774 }
3775 }
3776 if (pmod != NULL) {
3777 mod = (PyLongObject *)fast_mod(v, w);
3778 if (mod == NULL) {
3779 Py_XDECREF(div);
3780 return -1;
3781 }
3782 *pmod = mod;
3783 }
3784 if (pdiv != NULL) {
3785 /* We only want to set `*pdiv` when `*pmod` is
3786 set successfully. */
3787 *pdiv = div;
3788 }
3789 return 0;
3790 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 if (long_divrem(v, w, &div, &mod) < 0)
3792 return -1;
3793 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3794 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3795 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 temp = (PyLongObject *) long_add(mod, w);
3797 Py_DECREF(mod);
3798 mod = temp;
3799 if (mod == NULL) {
3800 Py_DECREF(div);
3801 return -1;
3802 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003803 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3804 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 Py_DECREF(mod);
3806 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 return -1;
3808 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 Py_DECREF(div);
3810 div = temp;
3811 }
3812 if (pdiv != NULL)
3813 *pdiv = div;
3814 else
3815 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 if (pmod != NULL)
3818 *pmod = mod;
3819 else
3820 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003823}
3824
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003825static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003826long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003831
3832 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3833 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3834 }
3835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3837 div = NULL;
3838 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003839}
3840
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003841/* PyLong/PyLong -> float, with correctly rounded result. */
3842
3843#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3844#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3845
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003846static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003847long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 PyLongObject *a, *b, *x;
3850 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3851 digit mask, low;
3852 int inexact, negate, a_is_small, b_is_small;
3853 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 CHECK_BINOP(v, w);
3856 a = (PyLongObject *)v;
3857 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 /*
3860 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3863 1. choose a suitable integer 'shift'
3864 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3865 3. adjust x for correct rounding
3866 4. convert x to a double dx with the same value
3867 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3872 returns either 0.0 or -0.0, depending on the sign of b. For a and
3873 b both nonzero, ignore signs of a and b, and add the sign back in
3874 at the end. Now write a_bits and b_bits for the bit lengths of a
3875 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3876 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3881 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3882 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3883 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 1. The integer 'shift' is chosen so that x has the right number of
3888 bits for a double, plus two or three extra bits that will be used
3889 in the rounding decisions. Writing a_bits and b_bits for the
3890 number of significant bits in a and b respectively, a
3891 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 This is fine in the usual case, but if a/b is smaller than the
3896 smallest normal float then it can lead to double rounding on an
3897 IEEE 754 platform, giving incorrectly rounded results. So we
3898 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 2. The quantity x is computed by first shifting a (left -shift bits
3903 if shift <= 0, right shift bits if shift > 0) and then dividing by
3904 b. For both the shift and the division, we keep track of whether
3905 the result is inexact, in a flag 'inexact'; this information is
3906 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 With the choice of shift above, together with our assumption that
3909 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3910 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3913 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 For float representability, we need x/2**extra_bits <
3918 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3919 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 To round, we just modify the bottom digit of x in-place; this can
3924 end up giving a digit with value > PyLONG_MASK, but that's not a
3925 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 With the original choices for shift above, extra_bits will always
3928 be 2 or 3. Then rounding under the round-half-to-even rule, we
3929 round up iff the most significant of the extra bits is 1, and
3930 either: (a) the computation of x in step 2 had an inexact result,
3931 or (b) at least one other of the extra bits is 1, or (c) the least
3932 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 4. Conversion to a double is straightforward; all floating-point
3935 operations involved in the conversion are exact, so there's no
3936 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3939 The result will always be exactly representable as a double, except
3940 in the case that it overflows. To avoid dependence on the exact
3941 behaviour of ldexp on overflow, we check for overflow before
3942 applying ldexp. The result of ldexp is adjusted for sign before
3943 returning.
3944 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003947 a_size = Py_ABS(Py_SIZE(a));
3948 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3950 if (b_size == 0) {
3951 PyErr_SetString(PyExc_ZeroDivisionError,
3952 "division by zero");
3953 goto error;
3954 }
3955 if (a_size == 0)
3956 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 /* Fast path for a and b small (exactly representable in a double).
3959 Relies on floating-point division being correctly rounded; results
3960 may be subject to double rounding on x86 machines that operate with
3961 the x87 FPU set to 64-bit precision. */
3962 a_is_small = a_size <= MANT_DIG_DIGITS ||
3963 (a_size == MANT_DIG_DIGITS+1 &&
3964 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3965 b_is_small = b_size <= MANT_DIG_DIGITS ||
3966 (b_size == MANT_DIG_DIGITS+1 &&
3967 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3968 if (a_is_small && b_is_small) {
3969 double da, db;
3970 da = a->ob_digit[--a_size];
3971 while (a_size > 0)
3972 da = da * PyLong_BASE + a->ob_digit[--a_size];
3973 db = b->ob_digit[--b_size];
3974 while (b_size > 0)
3975 db = db * PyLong_BASE + b->ob_digit[--b_size];
3976 result = da / db;
3977 goto success;
3978 }
Tim Peterse2a60002001-09-04 06:17:36 +00003979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 /* Catch obvious cases of underflow and overflow */
3981 diff = a_size - b_size;
3982 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3983 /* Extreme overflow */
3984 goto overflow;
3985 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3986 /* Extreme underflow */
3987 goto underflow_or_zero;
3988 /* Next line is now safe from overflowing a Py_ssize_t */
3989 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3990 bits_in_digit(b->ob_digit[b_size - 1]);
3991 /* Now diff = a_bits - b_bits. */
3992 if (diff > DBL_MAX_EXP)
3993 goto overflow;
3994 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3995 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003998 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 /* x = abs(a * 2**-shift) */
4003 if (shift <= 0) {
4004 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
4005 digit rem;
4006 /* x = a << -shift */
4007 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
4008 /* In practice, it's probably impossible to end up
4009 here. Both a and b would have to be enormous,
4010 using close to SIZE_T_MAX bytes of memory each. */
4011 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004012 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 goto error;
4014 }
4015 x = _PyLong_New(a_size + shift_digits + 1);
4016 if (x == NULL)
4017 goto error;
4018 for (i = 0; i < shift_digits; i++)
4019 x->ob_digit[i] = 0;
4020 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
4021 a_size, -shift % PyLong_SHIFT);
4022 x->ob_digit[a_size + shift_digits] = rem;
4023 }
4024 else {
4025 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
4026 digit rem;
4027 /* x = a >> shift */
4028 assert(a_size >= shift_digits);
4029 x = _PyLong_New(a_size - shift_digits);
4030 if (x == NULL)
4031 goto error;
4032 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4033 a_size - shift_digits, shift % PyLong_SHIFT);
4034 /* set inexact if any of the bits shifted out is nonzero */
4035 if (rem)
4036 inexact = 1;
4037 while (!inexact && shift_digits > 0)
4038 if (a->ob_digit[--shift_digits])
4039 inexact = 1;
4040 }
4041 long_normalize(x);
4042 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4045 reference to x, so it's safe to modify it in-place. */
4046 if (b_size == 1) {
4047 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4048 b->ob_digit[0]);
4049 long_normalize(x);
4050 if (rem)
4051 inexact = 1;
4052 }
4053 else {
4054 PyLongObject *div, *rem;
4055 div = x_divrem(x, b, &rem);
4056 Py_DECREF(x);
4057 x = div;
4058 if (x == NULL)
4059 goto error;
4060 if (Py_SIZE(rem))
4061 inexact = 1;
4062 Py_DECREF(rem);
4063 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004064 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 assert(x_size > 0); /* result of division is never zero */
4066 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004069 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 /* Round by directly modifying the low digit of x. */
4073 mask = (digit)1 << (extra_bits - 1);
4074 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004075 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004077 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 /* Convert x to a double dx; the conversion is exact. */
4080 dx = x->ob_digit[--x_size];
4081 while (x_size > 0)
4082 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4083 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 /* Check whether ldexp result will overflow a double. */
4086 if (shift + x_bits >= DBL_MAX_EXP &&
4087 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4088 goto overflow;
4089 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004090
4091 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004093
4094 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004096
4097 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 PyErr_SetString(PyExc_OverflowError,
4099 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004100 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004102}
4103
4104static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004105long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 CHECK_BINOP(a, b);
4110
Yury Selivanove0b23092016-02-11 10:26:27 -05004111 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4112 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4113 }
4114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4116 mod = NULL;
4117 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004118}
4119
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004120static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004121long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 PyLongObject *div, *mod;
4124 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4129 return NULL;
4130 }
4131 z = PyTuple_New(2);
4132 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004133 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4134 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 }
4136 else {
4137 Py_DECREF(div);
4138 Py_DECREF(mod);
4139 }
4140 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004141}
4142
Mark Dickinsonc5299672019-06-02 10:24:06 +01004143
4144/* Compute an inverse to a modulo n, or raise ValueError if a is not
4145 invertible modulo n. Assumes n is positive. The inverse returned
4146 is whatever falls out of the extended Euclidean algorithm: it may
4147 be either positive or negative, but will be smaller than n in
4148 absolute value.
4149
4150 Pure Python equivalent for long_invmod:
4151
4152 def invmod(a, n):
4153 b, c = 1, 0
4154 while n:
4155 q, r = divmod(a, n)
4156 a, b, c, n = n, c, b - q*c, r
4157
4158 # at this point a is the gcd of the original inputs
4159 if a == 1:
4160 return b
4161 raise ValueError("Not invertible")
4162*/
4163
4164static PyLongObject *
4165long_invmod(PyLongObject *a, PyLongObject *n)
4166{
4167 PyLongObject *b, *c;
4168
4169 /* Should only ever be called for positive n */
4170 assert(Py_SIZE(n) > 0);
4171
4172 b = (PyLongObject *)PyLong_FromLong(1L);
4173 if (b == NULL) {
4174 return NULL;
4175 }
4176 c = (PyLongObject *)PyLong_FromLong(0L);
4177 if (c == NULL) {
4178 Py_DECREF(b);
4179 return NULL;
4180 }
4181 Py_INCREF(a);
4182 Py_INCREF(n);
4183
4184 /* references now owned: a, b, c, n */
4185 while (Py_SIZE(n) != 0) {
4186 PyLongObject *q, *r, *s, *t;
4187
4188 if (l_divmod(a, n, &q, &r) == -1) {
4189 goto Error;
4190 }
4191 Py_DECREF(a);
4192 a = n;
4193 n = r;
4194 t = (PyLongObject *)long_mul(q, c);
4195 Py_DECREF(q);
4196 if (t == NULL) {
4197 goto Error;
4198 }
4199 s = (PyLongObject *)long_sub(b, t);
4200 Py_DECREF(t);
4201 if (s == NULL) {
4202 goto Error;
4203 }
4204 Py_DECREF(b);
4205 b = c;
4206 c = s;
4207 }
4208 /* references now owned: a, b, c, n */
4209
4210 Py_DECREF(c);
4211 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004212 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004213 /* a != 1; we don't have an inverse. */
4214 Py_DECREF(a);
4215 Py_DECREF(b);
4216 PyErr_SetString(PyExc_ValueError,
4217 "base is not invertible for the given modulus");
4218 return NULL;
4219 }
4220 else {
4221 /* a == 1; b gives an inverse modulo n */
4222 Py_DECREF(a);
4223 return b;
4224 }
4225
4226 Error:
4227 Py_DECREF(a);
4228 Py_DECREF(b);
4229 Py_DECREF(c);
4230 Py_DECREF(n);
4231 return NULL;
4232}
4233
4234
Tim Peters47e52ee2004-08-30 02:44:38 +00004235/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004236static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004237long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4240 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 PyLongObject *z = NULL; /* accumulated result */
4243 Py_ssize_t i, j, k; /* counters */
4244 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 /* 5-ary values. If the exponent is large enough, table is
4247 * precomputed so that table[i] == a**i % c for i in range(32).
4248 */
4249 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4250 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 /* a, b, c = v, w, x */
4253 CHECK_BINOP(v, w);
4254 a = (PyLongObject*)v; Py_INCREF(a);
4255 b = (PyLongObject*)w; Py_INCREF(b);
4256 if (PyLong_Check(x)) {
4257 c = (PyLongObject *)x;
4258 Py_INCREF(x);
4259 }
4260 else if (x == Py_None)
4261 c = NULL;
4262 else {
4263 Py_DECREF(a);
4264 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004265 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 }
Tim Peters4c483c42001-09-05 06:24:58 +00004267
Mark Dickinsonc5299672019-06-02 10:24:06 +01004268 if (Py_SIZE(b) < 0 && c == NULL) {
4269 /* if exponent is negative and there's no modulus:
4270 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 that this calls float_pow() which converts its
4272 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004273 Py_DECREF(a);
4274 Py_DECREF(b);
4275 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 if (c) {
4279 /* if modulus == 0:
4280 raise ValueError() */
4281 if (Py_SIZE(c) == 0) {
4282 PyErr_SetString(PyExc_ValueError,
4283 "pow() 3rd argument cannot be 0");
4284 goto Error;
4285 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 /* if modulus < 0:
4288 negativeOutput = True
4289 modulus = -modulus */
4290 if (Py_SIZE(c) < 0) {
4291 negativeOutput = 1;
4292 temp = (PyLongObject *)_PyLong_Copy(c);
4293 if (temp == NULL)
4294 goto Error;
4295 Py_DECREF(c);
4296 c = temp;
4297 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004298 _PyLong_Negate(&c);
4299 if (c == NULL)
4300 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 /* if modulus == 1:
4304 return 0 */
4305 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4306 z = (PyLongObject *)PyLong_FromLong(0L);
4307 goto Done;
4308 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004309
Mark Dickinsonc5299672019-06-02 10:24:06 +01004310 /* if exponent is negative, negate the exponent and
4311 replace the base with a modular inverse */
4312 if (Py_SIZE(b) < 0) {
4313 temp = (PyLongObject *)_PyLong_Copy(b);
4314 if (temp == NULL)
4315 goto Error;
4316 Py_DECREF(b);
4317 b = temp;
4318 temp = NULL;
4319 _PyLong_Negate(&b);
4320 if (b == NULL)
4321 goto Error;
4322
4323 temp = long_invmod(a, c);
4324 if (temp == NULL)
4325 goto Error;
4326 Py_DECREF(a);
4327 a = temp;
4328 }
4329
Tim Peters81a93152013-10-05 16:53:52 -05004330 /* Reduce base by modulus in some cases:
4331 1. If base < 0. Forcing the base non-negative makes things easier.
4332 2. If base is obviously larger than the modulus. The "small
4333 exponent" case later can multiply directly by base repeatedly,
4334 while the "large exponent" case multiplies directly by base 31
4335 times. It can be unboundedly faster to multiply by
4336 base % modulus instead.
4337 We could _always_ do this reduction, but l_divmod() isn't cheap,
4338 so we only do it when it buys something. */
4339 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 if (l_divmod(a, c, NULL, &temp) < 0)
4341 goto Error;
4342 Py_DECREF(a);
4343 a = temp;
4344 temp = NULL;
4345 }
4346 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 /* At this point a, b, and c are guaranteed non-negative UNLESS
4349 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 z = (PyLongObject *)PyLong_FromLong(1L);
4352 if (z == NULL)
4353 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 /* Perform a modular reduction, X = X % c, but leave X alone if c
4356 * is NULL.
4357 */
4358#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004359 do { \
4360 if (c != NULL) { \
4361 if (l_divmod(X, c, NULL, &temp) < 0) \
4362 goto Error; \
4363 Py_XDECREF(X); \
4364 X = temp; \
4365 temp = NULL; \
4366 } \
4367 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 /* Multiply two values, then reduce the result:
4370 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004371#define MULT(X, Y, result) \
4372 do { \
4373 temp = (PyLongObject *)long_mul(X, Y); \
4374 if (temp == NULL) \
4375 goto Error; \
4376 Py_XDECREF(result); \
4377 result = temp; \
4378 temp = NULL; \
4379 REDUCE(result); \
4380 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4383 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4384 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4385 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4386 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004389 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004391 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 }
4393 }
4394 }
4395 else {
4396 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4397 Py_INCREF(z); /* still holds 1L */
4398 table[0] = z;
4399 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004400 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4403 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4406 const int index = (bi >> j) & 0x1f;
4407 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004408 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004409 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004410 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 }
4412 }
4413 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 if (negativeOutput && (Py_SIZE(z) != 0)) {
4416 temp = (PyLongObject *)long_sub(z, c);
4417 if (temp == NULL)
4418 goto Error;
4419 Py_DECREF(z);
4420 z = temp;
4421 temp = NULL;
4422 }
4423 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004424
Mark Dickinson22b20182010-05-10 21:27:53 +00004425 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004426 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004428 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4430 for (i = 0; i < 32; ++i)
4431 Py_XDECREF(table[i]);
4432 }
4433 Py_DECREF(a);
4434 Py_DECREF(b);
4435 Py_XDECREF(c);
4436 Py_XDECREF(temp);
4437 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004438}
4439
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004440static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004441long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 /* Implement ~x as -(x+1) */
4444 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004445 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004447 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 if (x == NULL)
4449 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004450 _PyLong_Negate(&x);
4451 /* No need for maybe_small_long here, since any small
4452 longs will have been caught in the Py_SIZE <= 1 fast path. */
4453 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004454}
4455
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004456static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004457long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004460 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 return PyLong_FromLong(-MEDIUM_VALUE(v));
4462 z = (PyLongObject *)_PyLong_Copy(v);
4463 if (z != NULL)
4464 Py_SIZE(z) = -(Py_SIZE(v));
4465 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004466}
4467
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004468static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004469long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 if (Py_SIZE(v) < 0)
4472 return long_neg(v);
4473 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004474 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004475}
4476
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004477static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004478long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004481}
4482
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004483/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4484static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004485divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004486{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004487 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004488 assert(Py_SIZE(shiftby) >= 0);
4489 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4490 if (lshiftby >= 0) {
4491 *wordshift = lshiftby / PyLong_SHIFT;
4492 *remshift = lshiftby % PyLong_SHIFT;
4493 return 0;
4494 }
4495 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4496 be that PyLong_AsSsize_t raised an OverflowError. */
4497 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4498 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004499 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004500 if (wordshift_obj == NULL) {
4501 return -1;
4502 }
4503 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4504 Py_DECREF(wordshift_obj);
4505 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4506 return 0;
4507 }
4508 PyErr_Clear();
4509 /* Clip the value. With such large wordshift the right shift
4510 returns 0 and the left shift raises an error in _PyLong_New(). */
4511 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4512 *remshift = 0;
4513 return 0;
4514}
4515
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004516static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004517long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004520 Py_ssize_t newsize, hishift, i, j;
4521 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 if (Py_SIZE(a) < 0) {
4524 /* Right shifting negative numbers is harder */
4525 PyLongObject *a1, *a2;
4526 a1 = (PyLongObject *) long_invert(a);
4527 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004528 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004529 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 Py_DECREF(a1);
4531 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004532 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 z = (PyLongObject *) long_invert(a2);
4534 Py_DECREF(a2);
4535 }
4536 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004537 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 if (newsize <= 0)
4539 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004540 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 lomask = ((digit)1 << hishift) - 1;
4542 himask = PyLong_MASK ^ lomask;
4543 z = _PyLong_New(newsize);
4544 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004545 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004547 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004549 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004551 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004553 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004554}
4555
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004556static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004557long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004558{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004559 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004560 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004563
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004564 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004565 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004566 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004568 if (Py_SIZE(a) == 0) {
4569 return PyLong_FromLong(0);
4570 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004571 if (divmod_shift(b, &wordshift, &remshift) < 0)
4572 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004573 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4574}
4575
4576/* Return a >> shiftby. */
4577PyObject *
4578_PyLong_Rshift(PyObject *a, size_t shiftby)
4579{
4580 Py_ssize_t wordshift;
4581 digit remshift;
4582
4583 assert(PyLong_Check(a));
4584 if (Py_SIZE(a) == 0) {
4585 return PyLong_FromLong(0);
4586 }
4587 wordshift = shiftby / PyLong_SHIFT;
4588 remshift = shiftby % PyLong_SHIFT;
4589 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4590}
4591
4592static PyObject *
4593long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4594{
4595 /* This version due to Tim Peters */
4596 PyLongObject *z = NULL;
4597 Py_ssize_t oldsize, newsize, i, j;
4598 twodigits accum;
4599
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004600 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 newsize = oldsize + wordshift;
4602 if (remshift)
4603 ++newsize;
4604 z = _PyLong_New(newsize);
4605 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004606 return NULL;
4607 if (Py_SIZE(a) < 0) {
4608 assert(Py_REFCNT(z) == 1);
4609 Py_SIZE(z) = -Py_SIZE(z);
4610 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 for (i = 0; i < wordshift; i++)
4612 z->ob_digit[i] = 0;
4613 accum = 0;
4614 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4615 accum |= (twodigits)a->ob_digit[j] << remshift;
4616 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4617 accum >>= PyLong_SHIFT;
4618 }
4619 if (remshift)
4620 z->ob_digit[newsize-1] = (digit)accum;
4621 else
4622 assert(!accum);
4623 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004625}
4626
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004627static PyObject *
4628long_lshift(PyObject *a, PyObject *b)
4629{
4630 Py_ssize_t wordshift;
4631 digit remshift;
4632
4633 CHECK_BINOP(a, b);
4634
4635 if (Py_SIZE(b) < 0) {
4636 PyErr_SetString(PyExc_ValueError, "negative shift count");
4637 return NULL;
4638 }
4639 if (Py_SIZE(a) == 0) {
4640 return PyLong_FromLong(0);
4641 }
4642 if (divmod_shift(b, &wordshift, &remshift) < 0)
4643 return NULL;
4644 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4645}
4646
4647/* Return a << shiftby. */
4648PyObject *
4649_PyLong_Lshift(PyObject *a, size_t shiftby)
4650{
4651 Py_ssize_t wordshift;
4652 digit remshift;
4653
4654 assert(PyLong_Check(a));
4655 if (Py_SIZE(a) == 0) {
4656 return PyLong_FromLong(0);
4657 }
4658 wordshift = shiftby / PyLong_SHIFT;
4659 remshift = shiftby % PyLong_SHIFT;
4660 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4661}
4662
Mark Dickinson27a87a22009-10-25 20:43:34 +00004663/* Compute two's complement of digit vector a[0:m], writing result to
4664 z[0:m]. The digit vector a need not be normalized, but should not
4665 be entirely zero. a and z may point to the same digit vector. */
4666
4667static void
4668v_complement(digit *z, digit *a, Py_ssize_t m)
4669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 Py_ssize_t i;
4671 digit carry = 1;
4672 for (i = 0; i < m; ++i) {
4673 carry += a[i] ^ PyLong_MASK;
4674 z[i] = carry & PyLong_MASK;
4675 carry >>= PyLong_SHIFT;
4676 }
4677 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004678}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004679
4680/* Bitwise and/xor/or operations */
4681
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004682static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004683long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004684 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004685 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 int nega, negb, negz;
4688 Py_ssize_t size_a, size_b, size_z, i;
4689 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004691 /* Bitwise operations for negative numbers operate as though
4692 on a two's complement representation. So convert arguments
4693 from sign-magnitude to two's complement, and convert the
4694 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004697 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 nega = Py_SIZE(a) < 0;
4699 if (nega) {
4700 z = _PyLong_New(size_a);
4701 if (z == NULL)
4702 return NULL;
4703 v_complement(z->ob_digit, a->ob_digit, size_a);
4704 a = z;
4705 }
4706 else
4707 /* Keep reference count consistent. */
4708 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004711 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 negb = Py_SIZE(b) < 0;
4713 if (negb) {
4714 z = _PyLong_New(size_b);
4715 if (z == NULL) {
4716 Py_DECREF(a);
4717 return NULL;
4718 }
4719 v_complement(z->ob_digit, b->ob_digit, size_b);
4720 b = z;
4721 }
4722 else
4723 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 /* Swap a and b if necessary to ensure size_a >= size_b. */
4726 if (size_a < size_b) {
4727 z = a; a = b; b = z;
4728 size_z = size_a; size_a = size_b; size_b = size_z;
4729 negz = nega; nega = negb; negb = negz;
4730 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 /* JRH: The original logic here was to allocate the result value (z)
4733 as the longer of the two operands. However, there are some cases
4734 where the result is guaranteed to be shorter than that: AND of two
4735 positives, OR of two negatives: use the shorter number. AND with
4736 mixed signs: use the positive number. OR with mixed signs: use the
4737 negative number.
4738 */
4739 switch (op) {
4740 case '^':
4741 negz = nega ^ negb;
4742 size_z = size_a;
4743 break;
4744 case '&':
4745 negz = nega & negb;
4746 size_z = negb ? size_a : size_b;
4747 break;
4748 case '|':
4749 negz = nega | negb;
4750 size_z = negb ? size_b : size_a;
4751 break;
4752 default:
stratakisa10d4262019-03-18 18:59:20 +01004753 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 /* We allow an extra digit if z is negative, to make sure that
4757 the final two's complement of z doesn't overflow. */
4758 z = _PyLong_New(size_z + negz);
4759 if (z == NULL) {
4760 Py_DECREF(a);
4761 Py_DECREF(b);
4762 return NULL;
4763 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 /* Compute digits for overlap of a and b. */
4766 switch(op) {
4767 case '&':
4768 for (i = 0; i < size_b; ++i)
4769 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4770 break;
4771 case '|':
4772 for (i = 0; i < size_b; ++i)
4773 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4774 break;
4775 case '^':
4776 for (i = 0; i < size_b; ++i)
4777 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4778 break;
4779 default:
stratakisa10d4262019-03-18 18:59:20 +01004780 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004783 /* Copy any remaining digits of a, inverting if necessary. */
4784 if (op == '^' && negb)
4785 for (; i < size_z; ++i)
4786 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4787 else if (i < size_z)
4788 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4789 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 /* Complement result if negative. */
4792 if (negz) {
4793 Py_SIZE(z) = -(Py_SIZE(z));
4794 z->ob_digit[size_z] = PyLong_MASK;
4795 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4796 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 Py_DECREF(a);
4799 Py_DECREF(b);
4800 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004801}
4802
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004803static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004804long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 PyObject *c;
4807 CHECK_BINOP(a, b);
4808 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4809 return c;
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_xor(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_or(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 Rossum23d6f0e1991-05-14 12:06:49 +00004828}
4829
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004830static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004831long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004833 if (PyLong_CheckExact(v))
4834 Py_INCREF(v);
4835 else
4836 v = _PyLong_Copy((PyLongObject *)v);
4837 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004838}
4839
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004840PyObject *
4841_PyLong_GCD(PyObject *aarg, PyObject *barg)
4842{
4843 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4844 stwodigits x, y, q, s, t, c_carry, d_carry;
4845 stwodigits A, B, C, D, T;
4846 int nbits, k;
4847 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4848 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4849
4850 a = (PyLongObject *)aarg;
4851 b = (PyLongObject *)barg;
4852 size_a = Py_SIZE(a);
4853 size_b = Py_SIZE(b);
4854 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4855 Py_INCREF(a);
4856 Py_INCREF(b);
4857 goto simple;
4858 }
4859
4860 /* Initial reduction: make sure that 0 <= b <= a. */
4861 a = (PyLongObject *)long_abs(a);
4862 if (a == NULL)
4863 return NULL;
4864 b = (PyLongObject *)long_abs(b);
4865 if (b == NULL) {
4866 Py_DECREF(a);
4867 return NULL;
4868 }
4869 if (long_compare(a, b) < 0) {
4870 r = a;
4871 a = b;
4872 b = r;
4873 }
4874 /* We now own references to a and b */
4875
4876 alloc_a = Py_SIZE(a);
4877 alloc_b = Py_SIZE(b);
4878 /* reduce until a fits into 2 digits */
4879 while ((size_a = Py_SIZE(a)) > 2) {
4880 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4881 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4882 corresponding bits of b into y */
4883 size_b = Py_SIZE(b);
4884 assert(size_b <= size_a);
4885 if (size_b == 0) {
4886 if (size_a < alloc_a) {
4887 r = (PyLongObject *)_PyLong_Copy(a);
4888 Py_DECREF(a);
4889 }
4890 else
4891 r = a;
4892 Py_DECREF(b);
4893 Py_XDECREF(c);
4894 Py_XDECREF(d);
4895 return (PyObject *)r;
4896 }
4897 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4898 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4899 (a->ob_digit[size_a-3] >> nbits));
4900
4901 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4902 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4903 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4904
4905 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4906 larger than PyLong_MASK during the algorithm. */
4907 A = 1; B = 0; C = 0; D = 1;
4908 for (k=0;; k++) {
4909 if (y-C == 0)
4910 break;
4911 q = (x+(A-1))/(y-C);
4912 s = B+q*D;
4913 t = x-q*y;
4914 if (s > t)
4915 break;
4916 x = y; y = t;
4917 t = A+q*C; A = D; B = C; C = s; D = t;
4918 }
4919
4920 if (k == 0) {
4921 /* no progress; do a Euclidean step */
4922 if (l_divmod(a, b, NULL, &r) < 0)
4923 goto error;
4924 Py_DECREF(a);
4925 a = b;
4926 b = r;
4927 alloc_a = alloc_b;
4928 alloc_b = Py_SIZE(b);
4929 continue;
4930 }
4931
4932 /*
4933 a, b = A*b-B*a, D*a-C*b if k is odd
4934 a, b = A*a-B*b, D*b-C*a if k is even
4935 */
4936 if (k&1) {
4937 T = -A; A = -B; B = T;
4938 T = -C; C = -D; D = T;
4939 }
4940 if (c != NULL)
4941 Py_SIZE(c) = size_a;
4942 else if (Py_REFCNT(a) == 1) {
4943 Py_INCREF(a);
4944 c = a;
4945 }
4946 else {
4947 alloc_a = size_a;
4948 c = _PyLong_New(size_a);
4949 if (c == NULL)
4950 goto error;
4951 }
4952
4953 if (d != NULL)
4954 Py_SIZE(d) = size_a;
4955 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4956 Py_INCREF(b);
4957 d = b;
4958 Py_SIZE(d) = size_a;
4959 }
4960 else {
4961 alloc_b = size_a;
4962 d = _PyLong_New(size_a);
4963 if (d == NULL)
4964 goto error;
4965 }
4966 a_end = a->ob_digit + size_a;
4967 b_end = b->ob_digit + size_b;
4968
4969 /* compute new a and new b in parallel */
4970 a_digit = a->ob_digit;
4971 b_digit = b->ob_digit;
4972 c_digit = c->ob_digit;
4973 d_digit = d->ob_digit;
4974 c_carry = 0;
4975 d_carry = 0;
4976 while (b_digit < b_end) {
4977 c_carry += (A * *a_digit) - (B * *b_digit);
4978 d_carry += (D * *b_digit++) - (C * *a_digit++);
4979 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4980 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4981 c_carry >>= PyLong_SHIFT;
4982 d_carry >>= PyLong_SHIFT;
4983 }
4984 while (a_digit < a_end) {
4985 c_carry += A * *a_digit;
4986 d_carry -= C * *a_digit++;
4987 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4988 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4989 c_carry >>= PyLong_SHIFT;
4990 d_carry >>= PyLong_SHIFT;
4991 }
4992 assert(c_carry == 0);
4993 assert(d_carry == 0);
4994
4995 Py_INCREF(c);
4996 Py_INCREF(d);
4997 Py_DECREF(a);
4998 Py_DECREF(b);
4999 a = long_normalize(c);
5000 b = long_normalize(d);
5001 }
5002 Py_XDECREF(c);
5003 Py_XDECREF(d);
5004
5005simple:
5006 assert(Py_REFCNT(a) > 0);
5007 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02005008/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
5009 undefined behaviour when LONG_MAX type is smaller than 60 bits */
5010#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005011 /* a fits into a long, so b must too */
5012 x = PyLong_AsLong((PyObject *)a);
5013 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05005014#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005015 x = PyLong_AsLongLong((PyObject *)a);
5016 y = PyLong_AsLongLong((PyObject *)b);
5017#else
5018# error "_PyLong_GCD"
5019#endif
5020 x = Py_ABS(x);
5021 y = Py_ABS(y);
5022 Py_DECREF(a);
5023 Py_DECREF(b);
5024
5025 /* usual Euclidean algorithm for longs */
5026 while (y != 0) {
5027 t = y;
5028 y = x % y;
5029 x = t;
5030 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005031#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005032 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05005033#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005034 return PyLong_FromLongLong(x);
5035#else
5036# error "_PyLong_GCD"
5037#endif
5038
5039error:
5040 Py_DECREF(a);
5041 Py_DECREF(b);
5042 Py_XDECREF(c);
5043 Py_XDECREF(d);
5044 return NULL;
5045}
5046
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005047static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005048long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 double result;
5051 result = PyLong_AsDouble(v);
5052 if (result == -1.0 && PyErr_Occurred())
5053 return NULL;
5054 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005055}
5056
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005057static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005058long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5059
5060/*[clinic input]
5061@classmethod
5062int.__new__ as long_new
5063 x: object(c_default="NULL") = 0
5064 /
5065 base as obase: object(c_default="NULL") = 10
5066[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005067
Tim Peters6d6c1a32001-08-02 04:15:00 +00005068static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005069long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5070/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005071{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005072 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005075 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005076 if (x == NULL) {
5077 if (obase != NULL) {
5078 PyErr_SetString(PyExc_TypeError,
5079 "int() missing string argument");
5080 return NULL;
5081 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005083 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005084 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005086
Gregory P. Smitha689e522012-12-25 22:38:32 -08005087 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005088 if (base == -1 && PyErr_Occurred())
5089 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005090 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005091 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305092 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005093 return NULL;
5094 }
5095
5096 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005097 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005100 if (PyByteArray_Check(x))
5101 string = PyByteArray_AS_STRING(x);
5102 else
5103 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005104 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 }
5106 else {
5107 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005108 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 return NULL;
5110 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005111}
5112
Serhiy Storchaka95949422013-08-27 19:40:23 +03005113/* Wimpy, slow approach to tp_new calls for subtypes of int:
5114 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005115 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005116 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005117*/
5118static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005119long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 PyLongObject *tmp, *newobj;
5122 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005125 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 if (tmp == NULL)
5127 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005128 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 n = Py_SIZE(tmp);
5130 if (n < 0)
5131 n = -n;
5132 newobj = (PyLongObject *)type->tp_alloc(type, n);
5133 if (newobj == NULL) {
5134 Py_DECREF(tmp);
5135 return NULL;
5136 }
5137 assert(PyLong_Check(newobj));
5138 Py_SIZE(newobj) = Py_SIZE(tmp);
5139 for (i = 0; i < n; i++)
5140 newobj->ob_digit[i] = tmp->ob_digit[i];
5141 Py_DECREF(tmp);
5142 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005143}
5144
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005145/*[clinic input]
5146int.__getnewargs__
5147[clinic start generated code]*/
5148
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005149static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005150int___getnewargs___impl(PyObject *self)
5151/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005152{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005153 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005154}
5155
Guido van Rossumb43daf72007-08-01 18:08:08 +00005156static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005157long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005159 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005160}
5161
5162static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005163long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005166}
5167
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005168/*[clinic input]
5169int.__format__
5170
5171 format_spec: unicode
5172 /
5173[clinic start generated code]*/
5174
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005175static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005176int___format___impl(PyObject *self, PyObject *format_spec)
5177/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005178{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005179 _PyUnicodeWriter writer;
5180 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005181
Victor Stinner8f674cc2013-04-17 23:02:17 +02005182 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005183 ret = _PyLong_FormatAdvancedWriter(
5184 &writer,
5185 self,
5186 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5187 if (ret == -1) {
5188 _PyUnicodeWriter_Dealloc(&writer);
5189 return NULL;
5190 }
5191 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005192}
5193
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005194/* Return a pair (q, r) such that a = b * q + r, and
5195 abs(r) <= abs(b)/2, with equality possible only if q is even.
5196 In other words, q == a / b, rounded to the nearest integer using
5197 round-half-to-even. */
5198
5199PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005200_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005201{
5202 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005203 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005204 int quo_is_odd, quo_is_neg;
5205 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005206
5207 /* Equivalent Python code:
5208
5209 def divmod_near(a, b):
5210 q, r = divmod(a, b)
5211 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5212 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5213 # positive, 2 * r < b if b negative.
5214 greater_than_half = 2*r > b if b > 0 else 2*r < b
5215 exactly_half = 2*r == b
5216 if greater_than_half or exactly_half and q % 2 == 1:
5217 q += 1
5218 r -= b
5219 return q, r
5220
5221 */
5222 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5223 PyErr_SetString(PyExc_TypeError,
5224 "non-integer arguments in division");
5225 return NULL;
5226 }
5227
5228 /* Do a and b have different signs? If so, quotient is negative. */
5229 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5230
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005231 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5232 goto error;
5233
5234 /* compare twice the remainder with the divisor, to see
5235 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005236 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005237 if (twice_rem == NULL)
5238 goto error;
5239 if (quo_is_neg) {
5240 temp = long_neg((PyLongObject*)twice_rem);
5241 Py_DECREF(twice_rem);
5242 twice_rem = temp;
5243 if (twice_rem == NULL)
5244 goto error;
5245 }
5246 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5247 Py_DECREF(twice_rem);
5248
5249 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5250 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5251 /* fix up quotient */
5252 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005253 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005254 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005255 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005256 Py_DECREF(quo);
5257 quo = (PyLongObject *)temp;
5258 if (quo == NULL)
5259 goto error;
5260 /* and remainder */
5261 if (quo_is_neg)
5262 temp = long_add(rem, (PyLongObject *)b);
5263 else
5264 temp = long_sub(rem, (PyLongObject *)b);
5265 Py_DECREF(rem);
5266 rem = (PyLongObject *)temp;
5267 if (rem == NULL)
5268 goto error;
5269 }
5270
5271 result = PyTuple_New(2);
5272 if (result == NULL)
5273 goto error;
5274
5275 /* PyTuple_SET_ITEM steals references */
5276 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5277 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005278 return result;
5279
5280 error:
5281 Py_XDECREF(quo);
5282 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005283 return NULL;
5284}
5285
Eric Smith8c663262007-08-25 02:26:07 +00005286static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005287long_round(PyObject *self, PyObject *args)
5288{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005289 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005290
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005291 /* To round an integer m to the nearest 10**n (n positive), we make use of
5292 * the divmod_near operation, defined by:
5293 *
5294 * divmod_near(a, b) = (q, r)
5295 *
5296 * where q is the nearest integer to the quotient a / b (the
5297 * nearest even integer in the case of a tie) and r == a - q * b.
5298 * Hence q * b = a - r is the nearest multiple of b to a,
5299 * preferring even multiples in the case of a tie.
5300 *
5301 * So the nearest multiple of 10**n to m is:
5302 *
5303 * m - divmod_near(m, 10**n)[1].
5304 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5306 return NULL;
5307 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005308 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005309
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005310 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 if (ndigits == NULL)
5312 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005313
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005314 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005315 if (Py_SIZE(ndigits) >= 0) {
5316 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005317 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005319
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005320 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5321 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005323 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005325 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005326
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005327 result = PyLong_FromLong(10L);
5328 if (result == NULL) {
5329 Py_DECREF(ndigits);
5330 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005331 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005332
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005333 temp = long_pow(result, ndigits, Py_None);
5334 Py_DECREF(ndigits);
5335 Py_DECREF(result);
5336 result = temp;
5337 if (result == NULL)
5338 return NULL;
5339
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005340 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005341 Py_DECREF(result);
5342 result = temp;
5343 if (result == NULL)
5344 return NULL;
5345
5346 temp = long_sub((PyLongObject *)self,
5347 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5348 Py_DECREF(result);
5349 result = temp;
5350
5351 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005352}
5353
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005354/*[clinic input]
5355int.__sizeof__ -> Py_ssize_t
5356
5357Returns size in memory, in bytes.
5358[clinic start generated code]*/
5359
5360static Py_ssize_t
5361int___sizeof___impl(PyObject *self)
5362/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005365
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005366 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5367 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005368}
5369
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005370/*[clinic input]
5371int.bit_length
5372
5373Number of bits necessary to represent self in binary.
5374
5375>>> bin(37)
5376'0b100101'
5377>>> (37).bit_length()
53786
5379[clinic start generated code]*/
5380
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005381static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005382int_bit_length_impl(PyObject *self)
5383/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005386 Py_ssize_t ndigits;
5387 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005388 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005389
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005390 assert(self != NULL);
5391 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005392
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005393 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 if (ndigits == 0)
5395 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005396
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005397 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005398 msd_bits = bits_in_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5401 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 /* expression above may overflow; use Python integers instead */
5404 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5405 if (result == NULL)
5406 return NULL;
5407 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5408 if (x == NULL)
5409 goto error;
5410 y = (PyLongObject *)long_mul(result, x);
5411 Py_DECREF(x);
5412 if (y == NULL)
5413 goto error;
5414 Py_DECREF(result);
5415 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5418 if (x == NULL)
5419 goto error;
5420 y = (PyLongObject *)long_add(result, x);
5421 Py_DECREF(x);
5422 if (y == NULL)
5423 goto error;
5424 Py_DECREF(result);
5425 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005427 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005428
Mark Dickinson22b20182010-05-10 21:27:53 +00005429 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 Py_DECREF(result);
5431 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005432}
5433
Christian Heimes53876d92008-04-19 00:31:39 +00005434#if 0
5435static PyObject *
5436long_is_finite(PyObject *v)
5437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005439}
5440#endif
5441
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005442/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005443int.as_integer_ratio
5444
5445Return integer ratio.
5446
5447Return a pair of integers, whose ratio is exactly equal to the original int
5448and with a positive denominator.
5449
5450>>> (10).as_integer_ratio()
5451(10, 1)
5452>>> (-10).as_integer_ratio()
5453(-10, 1)
5454>>> (0).as_integer_ratio()
5455(0, 1)
5456[clinic start generated code]*/
5457
5458static PyObject *
5459int_as_integer_ratio_impl(PyObject *self)
5460/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5461{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005462 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005463 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005464 if (numerator == NULL) {
5465 return NULL;
5466 }
5467 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5468 Py_DECREF(numerator);
5469 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005470}
5471
5472/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005473int.to_bytes
5474
5475 length: Py_ssize_t
5476 Length of bytes object to use. An OverflowError is raised if the
5477 integer is not representable with the given number of bytes.
5478 byteorder: unicode
5479 The byte order used to represent the integer. If byteorder is 'big',
5480 the most significant byte is at the beginning of the byte array. If
5481 byteorder is 'little', the most significant byte is at the end of the
5482 byte array. To request the native byte order of the host system, use
5483 `sys.byteorder' as the byte order value.
5484 *
5485 signed as is_signed: bool = False
5486 Determines whether two's complement is used to represent the integer.
5487 If signed is False and a negative integer is given, an OverflowError
5488 is raised.
5489
5490Return an array of bytes representing an integer.
5491[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005492
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005493static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005494int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5495 int is_signed)
5496/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005500
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005501 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005502 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005503 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 little_endian = 0;
5505 else {
5506 PyErr_SetString(PyExc_ValueError,
5507 "byteorder must be either 'little' or 'big'");
5508 return NULL;
5509 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 if (length < 0) {
5512 PyErr_SetString(PyExc_ValueError,
5513 "length argument must be non-negative");
5514 return NULL;
5515 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 bytes = PyBytes_FromStringAndSize(NULL, length);
5518 if (bytes == NULL)
5519 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005520
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005521 if (_PyLong_AsByteArray((PyLongObject *)self,
5522 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 length, little_endian, is_signed) < 0) {
5524 Py_DECREF(bytes);
5525 return NULL;
5526 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005529}
5530
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005531/*[clinic input]
5532@classmethod
5533int.from_bytes
5534
5535 bytes as bytes_obj: object
5536 Holds the array of bytes to convert. The argument must either
5537 support the buffer protocol or be an iterable object producing bytes.
5538 Bytes and bytearray are examples of built-in objects that support the
5539 buffer protocol.
5540 byteorder: unicode
5541 The byte order used to represent the integer. If byteorder is 'big',
5542 the most significant byte is at the beginning of the byte array. If
5543 byteorder is 'little', the most significant byte is at the end of the
5544 byte array. To request the native byte order of the host system, use
5545 `sys.byteorder' as the byte order value.
5546 *
5547 signed as is_signed: bool = False
5548 Indicates whether two's complement is used to represent the integer.
5549
5550Return the integer represented by the given array of bytes.
5551[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005552
5553static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005554int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5555 PyObject *byteorder, int is_signed)
5556/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005559 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005560
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005561 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005562 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005563 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 little_endian = 0;
5565 else {
5566 PyErr_SetString(PyExc_ValueError,
5567 "byteorder must be either 'little' or 'big'");
5568 return NULL;
5569 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005570
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005571 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 if (bytes == NULL)
5573 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 long_obj = _PyLong_FromByteArray(
5576 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5577 little_endian, is_signed);
5578 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005579
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005580 if (long_obj != NULL && type != &PyLong_Type) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02005581 Py_SETREF(long_obj, _PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005585}
5586
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005587static PyObject *
5588long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5589{
5590 return long_long(self);
5591}
5592
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005593static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005594 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005596 INT_BIT_LENGTH_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00005597#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5599 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005600#endif
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005601 INT_TO_BYTES_METHODDEF
5602 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005603 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005604 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005605 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005606 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005607 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005608 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005609 "Ceiling of an Integral returns itself."},
5610 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5611 "Rounding an Integral returns itself.\n"
5612 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005613 INT___GETNEWARGS___METHODDEF
5614 INT___FORMAT___METHODDEF
5615 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005616 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005617};
5618
Guido van Rossumb43daf72007-08-01 18:08:08 +00005619static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005620 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005621 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005622 "the real part of a complex number",
5623 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005624 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005625 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005626 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005627 NULL},
5628 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005629 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005630 "the numerator of a rational number in lowest terms",
5631 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005632 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005633 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005634 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005635 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005636 {NULL} /* Sentinel */
5637};
5638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005639PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005640"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005641int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005642\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005643Convert a number or string to an integer, or return 0 if no arguments\n\
5644are given. If x is a number, return x.__int__(). For floating point\n\
5645numbers, this truncates towards zero.\n\
5646\n\
5647If x is not a number or if base is given, then x must be a string,\n\
5648bytes, or bytearray instance representing an integer literal in the\n\
5649given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5650by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5651Base 0 means to interpret the base from the string as an integer literal.\n\
5652>>> int('0b100', base=0)\n\
56534");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005654
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005655static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005656 (binaryfunc)long_add, /*nb_add*/
5657 (binaryfunc)long_sub, /*nb_subtract*/
5658 (binaryfunc)long_mul, /*nb_multiply*/
5659 long_mod, /*nb_remainder*/
5660 long_divmod, /*nb_divmod*/
5661 long_pow, /*nb_power*/
5662 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005663 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005664 (unaryfunc)long_abs, /*tp_absolute*/
5665 (inquiry)long_bool, /*tp_bool*/
5666 (unaryfunc)long_invert, /*nb_invert*/
5667 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005668 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005669 long_and, /*nb_and*/
5670 long_xor, /*nb_xor*/
5671 long_or, /*nb_or*/
5672 long_long, /*nb_int*/
5673 0, /*nb_reserved*/
5674 long_float, /*nb_float*/
5675 0, /* nb_inplace_add */
5676 0, /* nb_inplace_subtract */
5677 0, /* nb_inplace_multiply */
5678 0, /* nb_inplace_remainder */
5679 0, /* nb_inplace_power */
5680 0, /* nb_inplace_lshift */
5681 0, /* nb_inplace_rshift */
5682 0, /* nb_inplace_and */
5683 0, /* nb_inplace_xor */
5684 0, /* nb_inplace_or */
5685 long_div, /* nb_floor_divide */
5686 long_true_divide, /* nb_true_divide */
5687 0, /* nb_inplace_floor_divide */
5688 0, /* nb_inplace_true_divide */
5689 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005690};
5691
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005692PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5694 "int", /* tp_name */
5695 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5696 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005697 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005698 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 0, /* tp_getattr */
5700 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005701 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 long_to_decimal_string, /* tp_repr */
5703 &long_as_number, /* tp_as_number */
5704 0, /* tp_as_sequence */
5705 0, /* tp_as_mapping */
5706 (hashfunc)long_hash, /* tp_hash */
5707 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005708 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 PyObject_GenericGetAttr, /* tp_getattro */
5710 0, /* tp_setattro */
5711 0, /* tp_as_buffer */
5712 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5713 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5714 long_doc, /* tp_doc */
5715 0, /* tp_traverse */
5716 0, /* tp_clear */
5717 long_richcompare, /* tp_richcompare */
5718 0, /* tp_weaklistoffset */
5719 0, /* tp_iter */
5720 0, /* tp_iternext */
5721 long_methods, /* tp_methods */
5722 0, /* tp_members */
5723 long_getset, /* tp_getset */
5724 0, /* tp_base */
5725 0, /* tp_dict */
5726 0, /* tp_descr_get */
5727 0, /* tp_descr_set */
5728 0, /* tp_dictoffset */
5729 0, /* tp_init */
5730 0, /* tp_alloc */
5731 long_new, /* tp_new */
5732 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005733};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005734
Mark Dickinsonbd792642009-03-18 20:06:12 +00005735static PyTypeObject Int_InfoType;
5736
5737PyDoc_STRVAR(int_info__doc__,
5738"sys.int_info\n\
5739\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005740A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005741internal representation of integers. The attributes are read only.");
5742
5743static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005744 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005745 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005747};
5748
5749static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 "sys.int_info", /* name */
5751 int_info__doc__, /* doc */
5752 int_info_fields, /* fields */
5753 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005754};
5755
5756PyObject *
5757PyLong_GetInfo(void)
5758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005759 PyObject* int_info;
5760 int field = 0;
5761 int_info = PyStructSequence_New(&Int_InfoType);
5762 if (int_info == NULL)
5763 return NULL;
5764 PyStructSequence_SET_ITEM(int_info, field++,
5765 PyLong_FromLong(PyLong_SHIFT));
5766 PyStructSequence_SET_ITEM(int_info, field++,
5767 PyLong_FromLong(sizeof(digit)));
5768 if (PyErr_Occurred()) {
5769 Py_CLEAR(int_info);
5770 return NULL;
5771 }
5772 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005773}
5774
Guido van Rossumddefaf32007-01-14 03:31:43 +00005775int
Victor Stinner630c8df2019-12-17 13:02:18 +01005776_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005777{
5778#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005779 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5780 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5781 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005782
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005783 PyLongObject *v = _PyLong_New(1);
5784 if (!v) {
5785 return -1;
5786 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005788 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005789 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005790
Victor Stinner630c8df2019-12-17 13:02:18 +01005791 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005792 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005793#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005794
Victor Stinner630c8df2019-12-17 13:02:18 +01005795 if (_Py_IsMainInterpreter(tstate)) {
5796 _PyLong_Zero = PyLong_FromLong(0);
5797 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005798 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005799 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005800
5801 _PyLong_One = PyLong_FromLong(1);
5802 if (_PyLong_One == NULL) {
5803 return 0;
5804 }
5805
5806 /* initialize int_info */
5807 if (Int_InfoType.tp_name == NULL) {
5808 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5809 return 0;
5810 }
5811 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005812 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005815}
5816
5817void
Victor Stinner630c8df2019-12-17 13:02:18 +01005818_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005819{
Victor Stinner630c8df2019-12-17 13:02:18 +01005820 if (_Py_IsMainInterpreter(tstate)) {
5821 Py_CLEAR(_PyLong_One);
5822 Py_CLEAR(_PyLong_Zero);
5823 }
5824
Guido van Rossumddefaf32007-01-14 03:31:43 +00005825#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005826 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005827 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005829#endif
5830}