blob: 9115fa184f37ea12f6beccce7e1ae5e1d7e253c1 [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 Rossum7eaf8222007-06-18 17:58:50 +000038static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000039get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000040{
animalize6b519982019-09-06 14:00:56 +080041 assert(IS_SMALL_INT(ival));
Victor Stinner630c8df2019-12-17 13:02:18 +010042 PyThreadState *tstate = _PyThreadState_GET();
43 PyObject *v = (PyObject*)tstate->interp->small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046}
Guido van Rossumddefaf32007-01-14 03:31:43 +000047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000049maybe_small_long(PyLongObject *v)
50{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020051 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080053 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 Py_DECREF(v);
55 return (PyLongObject *)get_small_int(ival);
56 }
57 }
58 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000059}
Guido van Rossumddefaf32007-01-14 03:31:43 +000060#else
animalize6b519982019-09-06 14:00:56 +080061#define IS_SMALL_INT(ival) 0
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050062#define IS_SMALL_UINT(ival) 0
animalize6b519982019-09-06 14:00:56 +080063#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000064#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000065#endif
66
Serhiy Storchaka95949422013-08-27 19:40:23 +030067/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000068 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020069Py_LOCAL_INLINE(void)
70_PyLong_Negate(PyLongObject **x_p)
71{
72 PyLongObject *x;
73
74 x = (PyLongObject *)*x_p;
75 if (Py_REFCNT(x) == 1) {
76 Py_SIZE(x) = -Py_SIZE(x);
77 return;
78 }
79
80 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
81 Py_DECREF(x);
82}
83
Serhiy Storchaka95949422013-08-27 19:40:23 +030084/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000085 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030086 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000087 */
Tim Peters0973b992004-08-29 22:16:50 +000088#define KARATSUBA_CUTOFF 70
89#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000090
Tim Peters47e52ee2004-08-30 02:44:38 +000091/* For exponentiation, use the binary left-to-right algorithm
92 * unless the exponent contains more than FIVEARY_CUTOFF digits.
93 * In that case, do 5 bits at a time. The potential drawback is that
94 * a table of 2**5 intermediate results is computed.
95 */
96#define FIVEARY_CUTOFF 8
97
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000098#define SIGCHECK(PyTryBlock) \
99 do { \
100 if (PyErr_CheckSignals()) PyTryBlock \
101 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000102
Serhiy Storchaka95949422013-08-27 19:40:23 +0300103/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000104 Doesn't attempt to free the storage--in most cases, due to the nature
105 of the algorithms used, this could save at most be one word anyway. */
106
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000107static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200108long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000109{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200110 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 while (i > 0 && v->ob_digit[i-1] == 0)
114 --i;
115 if (i != j)
116 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
117 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000118}
119
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200120/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
121 using the nb_int slot, if available. Raise TypeError if either the
122 nb_int slot is not available or the result of the call to nb_int
123 returns something not of type int.
124*/
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200125PyObject *
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200126_PyLong_FromNbInt(PyObject *integral)
127{
128 PyNumberMethods *nb;
129 PyObject *result;
130
131 /* Fast path for the case that we already have an int. */
132 if (PyLong_CheckExact(integral)) {
133 Py_INCREF(integral);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200134 return integral;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200135 }
136
137 nb = Py_TYPE(integral)->tp_as_number;
138 if (nb == NULL || nb->nb_int == NULL) {
139 PyErr_Format(PyExc_TypeError,
140 "an integer is required (got type %.200s)",
141 Py_TYPE(integral)->tp_name);
142 return NULL;
143 }
144
145 /* Convert using the nb_int slot, which should return something
146 of exact type int. */
147 result = nb->nb_int(integral);
148 if (!result || PyLong_CheckExact(result))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200149 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200150 if (!PyLong_Check(result)) {
151 PyErr_Format(PyExc_TypeError,
152 "__int__ returned non-int (type %.200s)",
153 result->ob_type->tp_name);
154 Py_DECREF(result);
155 return NULL;
156 }
157 /* Issue #17576: warn if 'result' not of exact type int. */
158 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
159 "__int__ returned non-int (type %.200s). "
160 "The ability to return an instance of a strict subclass of int "
161 "is deprecated, and may be removed in a future version of Python.",
162 result->ob_type->tp_name)) {
163 Py_DECREF(result);
164 return NULL;
165 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200166 return result;
167}
168
169/* Convert the given object to a PyLongObject using the nb_index or
170 nb_int slots, if available (the latter is deprecated).
171 Raise TypeError if either nb_index and nb_int slots are not
172 available or the result of the call to nb_index or nb_int
173 returns something not of type int.
174 Should be replaced with PyNumber_Index after the end of the
175 deprecation period.
176*/
177PyObject *
178_PyLong_FromNbIndexOrNbInt(PyObject *integral)
179{
180 PyNumberMethods *nb;
181 PyObject *result;
182
183 /* Fast path for the case that we already have an int. */
184 if (PyLong_CheckExact(integral)) {
185 Py_INCREF(integral);
186 return integral;
187 }
188
189 nb = Py_TYPE(integral)->tp_as_number;
190 if (nb == NULL || (nb->nb_index == NULL && nb->nb_int == NULL)) {
191 PyErr_Format(PyExc_TypeError,
192 "an integer is required (got type %.200s)",
193 Py_TYPE(integral)->tp_name);
194 return NULL;
195 }
196
197 if (nb->nb_index) {
198 /* Convert using the nb_index slot, which should return something
199 of exact type int. */
200 result = nb->nb_index(integral);
201 if (!result || PyLong_CheckExact(result))
202 return result;
203 if (!PyLong_Check(result)) {
204 PyErr_Format(PyExc_TypeError,
205 "__index__ returned non-int (type %.200s)",
206 result->ob_type->tp_name);
207 Py_DECREF(result);
208 return NULL;
209 }
210 /* Issue #17576: warn if 'result' not of exact type int. */
211 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
212 "__index__ returned non-int (type %.200s). "
213 "The ability to return an instance of a strict subclass of int "
214 "is deprecated, and may be removed in a future version of Python.",
215 result->ob_type->tp_name))
216 {
217 Py_DECREF(result);
218 return NULL;
219 }
220 return result;
221 }
222
223 result = _PyLong_FromNbInt(integral);
224 if (result && PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
225 "an integer is required (got type %.200s). "
226 "Implicit conversion to integers using __int__ is deprecated, "
227 "and may be removed in a future version of Python.",
228 Py_TYPE(integral)->tp_name))
229 {
230 Py_DECREF(result);
231 return NULL;
232 }
233 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200234}
235
236
Serhiy Storchaka95949422013-08-27 19:40:23 +0300237/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238 Return NULL and set exception if we run out of memory. */
239
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000240#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000242
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000244_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyLongObject *result;
247 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
248 sizeof(digit)*size. Previous incarnations of this code used
249 sizeof(PyVarObject) instead of the offsetof, but this risks being
250 incorrect in the presence of padding between the PyVarObject header
251 and the digits. */
252 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
253 PyErr_SetString(PyExc_OverflowError,
254 "too many digits in integer");
255 return NULL;
256 }
257 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
258 size*sizeof(digit));
259 if (!result) {
260 PyErr_NoMemory();
261 return NULL;
262 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100263 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000264}
265
Tim Peters64b5ce32001-09-10 20:52:51 +0000266PyObject *
267_PyLong_Copy(PyLongObject *src)
268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 PyLongObject *result;
270 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 assert(src != NULL);
273 i = Py_SIZE(src);
274 if (i < 0)
275 i = -(i);
276 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100277 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800278 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700279 return get_small_int(ival);
280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 }
282 result = _PyLong_New(i);
283 if (result != NULL) {
284 Py_SIZE(result) = Py_SIZE(src);
285 while (--i >= 0)
286 result->ob_digit[i] = src->ob_digit[i];
287 }
288 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000289}
290
Serhiy Storchaka95949422013-08-27 19:40:23 +0300291/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000292
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000293PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000294PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 PyLongObject *v;
297 unsigned long abs_ival;
298 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
299 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100300 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000301
animalize6b519982019-09-06 14:00:56 +0800302 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700303 return get_small_int((sdigit)ival);
304 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (ival < 0) {
307 /* negate: can't write this as abs_ival = -ival since that
308 invokes undefined behaviour when ival is LONG_MIN */
309 abs_ival = 0U-(unsigned long)ival;
310 sign = -1;
311 }
312 else {
313 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100314 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 /* Fast path for single-digit ints */
318 if (!(abs_ival >> PyLong_SHIFT)) {
319 v = _PyLong_New(1);
320 if (v) {
321 Py_SIZE(v) = sign;
322 v->ob_digit[0] = Py_SAFE_DOWNCAST(
323 abs_ival, unsigned long, digit);
324 }
325 return (PyObject*)v;
326 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000327
Mark Dickinson249b8982009-04-27 19:41:00 +0000328#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 /* 2 digits */
330 if (!(abs_ival >> 2*PyLong_SHIFT)) {
331 v = _PyLong_New(2);
332 if (v) {
333 Py_SIZE(v) = 2*sign;
334 v->ob_digit[0] = Py_SAFE_DOWNCAST(
335 abs_ival & PyLong_MASK, unsigned long, digit);
336 v->ob_digit[1] = Py_SAFE_DOWNCAST(
337 abs_ival >> PyLong_SHIFT, unsigned long, digit);
338 }
339 return (PyObject*)v;
340 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000341#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 /* Larger numbers: loop to determine number of digits */
344 t = abs_ival;
345 while (t) {
346 ++ndigits;
347 t >>= PyLong_SHIFT;
348 }
349 v = _PyLong_New(ndigits);
350 if (v != NULL) {
351 digit *p = v->ob_digit;
352 Py_SIZE(v) = ndigits*sign;
353 t = abs_ival;
354 while (t) {
355 *p++ = Py_SAFE_DOWNCAST(
356 t & PyLong_MASK, unsigned long, digit);
357 t >>= PyLong_SHIFT;
358 }
359 }
360 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000361}
362
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500363#define PYLONG_FROM_UINT(INT_TYPE, ival) \
364 do { \
365 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200366 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500367 } \
368 /* Count the number of Python digits. */ \
369 Py_ssize_t ndigits = 0; \
370 INT_TYPE t = (ival); \
371 while (t) { \
372 ++ndigits; \
373 t >>= PyLong_SHIFT; \
374 } \
375 PyLongObject *v = _PyLong_New(ndigits); \
376 if (v == NULL) { \
377 return NULL; \
378 } \
379 digit *p = v->ob_digit; \
380 while ((ival)) { \
381 *p++ = (digit)((ival) & PyLong_MASK); \
382 (ival) >>= PyLong_SHIFT; \
383 } \
384 return (PyObject *)v; \
385 } while(0)
386
Serhiy Storchaka95949422013-08-27 19:40:23 +0300387/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000388
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000389PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000390PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000391{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500392 PYLONG_FROM_UINT(unsigned long, ival);
393}
Tim Petersce9de2f2001-06-14 04:56:19 +0000394
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500395/* Create a new int object from a C unsigned long long int. */
396
397PyObject *
398PyLong_FromUnsignedLongLong(unsigned long long ival)
399{
400 PYLONG_FROM_UINT(unsigned long long, ival);
401}
402
403/* Create a new int object from a C size_t. */
404
405PyObject *
406PyLong_FromSize_t(size_t ival)
407{
408 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000409}
410
Serhiy Storchaka95949422013-08-27 19:40:23 +0300411/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000412
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000414PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 PyLongObject *v;
417 double frac;
418 int i, ndig, expo, neg;
419 neg = 0;
420 if (Py_IS_INFINITY(dval)) {
421 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000422 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 return NULL;
424 }
425 if (Py_IS_NAN(dval)) {
426 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000427 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 return NULL;
429 }
430 if (dval < 0.0) {
431 neg = 1;
432 dval = -dval;
433 }
434 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
435 if (expo <= 0)
436 return PyLong_FromLong(0L);
437 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
438 v = _PyLong_New(ndig);
439 if (v == NULL)
440 return NULL;
441 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
442 for (i = ndig; --i >= 0; ) {
443 digit bits = (digit)frac;
444 v->ob_digit[i] = bits;
445 frac = frac - (double)bits;
446 frac = ldexp(frac, PyLong_SHIFT);
447 }
448 if (neg)
449 Py_SIZE(v) = -(Py_SIZE(v));
450 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000451}
452
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
454 * anything about what happens when a signed integer operation overflows,
455 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700456 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000457 * (unsigned long)LONG_MAX, and for the smallest negative signed long
458 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
459 * However, some other compilers warn about applying unary minus to an
460 * unsigned operand. Hence the weird "0-".
461 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
463#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000464
Serhiy Storchaka95949422013-08-27 19:40:23 +0300465/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100466 method.
467
468 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
469 the result. Otherwise *overflow is 0.
470
471 For other errors (e.g., TypeError), return -1 and set an error condition.
472 In this case *overflow will be 0.
473*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000474
475long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000476PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200479 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 unsigned long x, prev;
481 long res;
482 Py_ssize_t i;
483 int sign;
484 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 *overflow = 0;
487 if (vv == NULL) {
488 PyErr_BadInternalCall();
489 return -1;
490 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000491
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200492 if (PyLong_Check(vv)) {
493 v = (PyLongObject *)vv;
494 }
495 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200496 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200497 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 return -1;
499 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 switch (i) {
506 case -1:
507 res = -(sdigit)v->ob_digit[0];
508 break;
509 case 0:
510 res = 0;
511 break;
512 case 1:
513 res = v->ob_digit[0];
514 break;
515 default:
516 sign = 1;
517 x = 0;
518 if (i < 0) {
519 sign = -1;
520 i = -(i);
521 }
522 while (--i >= 0) {
523 prev = x;
524 x = (x << PyLong_SHIFT) | v->ob_digit[i];
525 if ((x >> PyLong_SHIFT) != prev) {
526 *overflow = sign;
527 goto exit;
528 }
529 }
530 /* Haven't lost any bits, but casting to long requires extra
531 * care (see comment above).
532 */
533 if (x <= (unsigned long)LONG_MAX) {
534 res = (long)x * sign;
535 }
536 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
537 res = LONG_MIN;
538 }
539 else {
540 *overflow = sign;
541 /* res is already set to -1 */
542 }
543 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000544 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200546 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 }
548 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000549}
550
Serhiy Storchaka95949422013-08-27 19:40:23 +0300551/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100552 method. Return -1 and set an error if overflow occurs. */
553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000555PyLong_AsLong(PyObject *obj)
556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 int overflow;
558 long result = PyLong_AsLongAndOverflow(obj, &overflow);
559 if (overflow) {
560 /* XXX: could be cute and give a different
561 message for overflow == -1 */
562 PyErr_SetString(PyExc_OverflowError,
563 "Python int too large to convert to C long");
564 }
565 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000566}
567
Serhiy Storchaka95949422013-08-27 19:40:23 +0300568/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200569 method. Return -1 and set an error if overflow occurs. */
570
571int
572_PyLong_AsInt(PyObject *obj)
573{
574 int overflow;
575 long result = PyLong_AsLongAndOverflow(obj, &overflow);
576 if (overflow || result > INT_MAX || result < INT_MIN) {
577 /* XXX: could be cute and give a different
578 message for overflow == -1 */
579 PyErr_SetString(PyExc_OverflowError,
580 "Python int too large to convert to C int");
581 return -1;
582 }
583 return (int)result;
584}
585
Serhiy Storchaka95949422013-08-27 19:40:23 +0300586/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000587 Returns -1 and sets an error condition if overflow occurs. */
588
589Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000590PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200591 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 size_t x, prev;
593 Py_ssize_t i;
594 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (vv == NULL) {
597 PyErr_BadInternalCall();
598 return -1;
599 }
600 if (!PyLong_Check(vv)) {
601 PyErr_SetString(PyExc_TypeError, "an integer is required");
602 return -1;
603 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 v = (PyLongObject *)vv;
606 i = Py_SIZE(v);
607 switch (i) {
608 case -1: return -(sdigit)v->ob_digit[0];
609 case 0: return 0;
610 case 1: return v->ob_digit[0];
611 }
612 sign = 1;
613 x = 0;
614 if (i < 0) {
615 sign = -1;
616 i = -(i);
617 }
618 while (--i >= 0) {
619 prev = x;
620 x = (x << PyLong_SHIFT) | v->ob_digit[i];
621 if ((x >> PyLong_SHIFT) != prev)
622 goto overflow;
623 }
624 /* Haven't lost any bits, but casting to a signed type requires
625 * extra care (see comment above).
626 */
627 if (x <= (size_t)PY_SSIZE_T_MAX) {
628 return (Py_ssize_t)x * sign;
629 }
630 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
631 return PY_SSIZE_T_MIN;
632 }
633 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000634
Mark Dickinson22b20182010-05-10 21:27:53 +0000635 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyErr_SetString(PyExc_OverflowError,
637 "Python int too large to convert to C ssize_t");
638 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000639}
640
Serhiy Storchaka95949422013-08-27 19:40:23 +0300641/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000642 Returns -1 and sets an error condition if overflow occurs. */
643
644unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000645PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000646{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200647 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 unsigned long x, prev;
649 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (vv == NULL) {
652 PyErr_BadInternalCall();
653 return (unsigned long)-1;
654 }
655 if (!PyLong_Check(vv)) {
656 PyErr_SetString(PyExc_TypeError, "an integer is required");
657 return (unsigned long)-1;
658 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 v = (PyLongObject *)vv;
661 i = Py_SIZE(v);
662 x = 0;
663 if (i < 0) {
664 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000665 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 return (unsigned long) -1;
667 }
668 switch (i) {
669 case 0: return 0;
670 case 1: return v->ob_digit[0];
671 }
672 while (--i >= 0) {
673 prev = x;
674 x = (x << PyLong_SHIFT) | v->ob_digit[i];
675 if ((x >> PyLong_SHIFT) != prev) {
676 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100677 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000678 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 return (unsigned long) -1;
680 }
681 }
682 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000683}
684
Serhiy Storchaka95949422013-08-27 19:40:23 +0300685/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200686 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000687
688size_t
689PyLong_AsSize_t(PyObject *vv)
690{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200691 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 size_t x, prev;
693 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (vv == NULL) {
696 PyErr_BadInternalCall();
697 return (size_t) -1;
698 }
699 if (!PyLong_Check(vv)) {
700 PyErr_SetString(PyExc_TypeError, "an integer is required");
701 return (size_t)-1;
702 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 v = (PyLongObject *)vv;
705 i = Py_SIZE(v);
706 x = 0;
707 if (i < 0) {
708 PyErr_SetString(PyExc_OverflowError,
709 "can't convert negative value to size_t");
710 return (size_t) -1;
711 }
712 switch (i) {
713 case 0: return 0;
714 case 1: return v->ob_digit[0];
715 }
716 while (--i >= 0) {
717 prev = x;
718 x = (x << PyLong_SHIFT) | v->ob_digit[i];
719 if ((x >> PyLong_SHIFT) != prev) {
720 PyErr_SetString(PyExc_OverflowError,
721 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200722 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 }
724 }
725 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000726}
727
Serhiy Storchaka95949422013-08-27 19:40:23 +0300728/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000729 Returns -1 and sets an error condition if an error occurs. */
730
Guido van Rossumddefaf32007-01-14 03:31:43 +0000731static unsigned long
732_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000733{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200734 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 unsigned long x;
736 Py_ssize_t i;
737 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (vv == NULL || !PyLong_Check(vv)) {
740 PyErr_BadInternalCall();
741 return (unsigned long) -1;
742 }
743 v = (PyLongObject *)vv;
744 i = Py_SIZE(v);
745 switch (i) {
746 case 0: return 0;
747 case 1: return v->ob_digit[0];
748 }
749 sign = 1;
750 x = 0;
751 if (i < 0) {
752 sign = -1;
753 i = -i;
754 }
755 while (--i >= 0) {
756 x = (x << PyLong_SHIFT) | v->ob_digit[i];
757 }
758 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000759}
760
Guido van Rossumddefaf32007-01-14 03:31:43 +0000761unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200762PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 PyLongObject *lo;
765 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000766
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200767 if (op == NULL) {
768 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 return (unsigned long)-1;
770 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000771
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200772 if (PyLong_Check(op)) {
773 return _PyLong_AsUnsignedLongMask(op);
774 }
775
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200776 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 if (lo == NULL)
778 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200779
780 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
781 Py_DECREF(lo);
782 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000783}
784
Tim Peters5b8132f2003-01-31 15:52:05 +0000785int
786_PyLong_Sign(PyObject *vv)
787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 assert(v != NULL);
791 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000794}
795
Tim Petersbaefd9e2003-01-28 20:37:45 +0000796size_t
797_PyLong_NumBits(PyObject *vv)
798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 PyLongObject *v = (PyLongObject *)vv;
800 size_t result = 0;
801 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200802 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 assert(v != NULL);
805 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200806 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
808 if (ndigits > 0) {
809 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700810 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100812 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Niklas Fiekasc5b79002020-01-16 15:09:19 +0100813 msd_bits = _Py_bit_length(msd);
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200814 if (SIZE_MAX - msd_bits < result)
815 goto Overflow;
816 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 }
818 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000819
Mark Dickinson22b20182010-05-10 21:27:53 +0000820 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
822 "to express in a platform size_t");
823 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000824}
825
Tim Peters2a9b3672001-06-11 21:23:58 +0000826PyObject *
827_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000829{
Mark Dickinson22b20182010-05-10 21:27:53 +0000830 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 int incr; /* direction to move pstartbyte */
832 const unsigned char* pendbyte; /* MSB of bytes */
833 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300834 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyLongObject* v; /* result */
836 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (n == 0)
839 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (little_endian) {
842 pstartbyte = bytes;
843 pendbyte = bytes + n - 1;
844 incr = 1;
845 }
846 else {
847 pstartbyte = bytes + n - 1;
848 pendbyte = bytes;
849 incr = -1;
850 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (is_signed)
853 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200856 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 is positive, and leading 0xff bytes if negative. */
858 {
859 size_t i;
860 const unsigned char* p = pendbyte;
861 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000862 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000865 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 break;
867 }
868 numsignificantbytes = n - i;
869 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
870 actually has 2 significant bytes. OTOH, 0xff0001 ==
871 -0x00ffff, so we wouldn't *need* to bump it there; but we
872 do for 0xffff = -0x0001. To be safe without bothering to
873 check every case, bump it regardless. */
874 if (is_signed && numsignificantbytes < n)
875 ++numsignificantbytes;
876 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000877
Serhiy Storchaka95949422013-08-27 19:40:23 +0300878 /* How many Python int digits do we need? We have
879 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
881 /* catch overflow before it happens */
882 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
883 PyErr_SetString(PyExc_OverflowError,
884 "byte array too long to convert to int");
885 return NULL;
886 }
887 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
888 v = _PyLong_New(ndigits);
889 if (v == NULL)
890 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 /* Copy the bits over. The tricky parts are computing 2's-comp on
893 the fly for signed numbers, and dealing with the mismatch between
894 8-bit bytes and (probably) 15-bit Python digits.*/
895 {
896 size_t i;
897 twodigits carry = 1; /* for 2's-comp calculation */
898 twodigits accum = 0; /* sliding register */
899 unsigned int accumbits = 0; /* number of bits in accum */
900 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
903 twodigits thisbyte = *p;
904 /* Compute correction for 2's comp, if needed. */
905 if (is_signed) {
906 thisbyte = (0xff ^ thisbyte) + carry;
907 carry = thisbyte >> 8;
908 thisbyte &= 0xff;
909 }
910 /* Because we're going LSB to MSB, thisbyte is
911 more significant than what's already in accum,
912 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200913 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 accumbits += 8;
915 if (accumbits >= PyLong_SHIFT) {
916 /* There's enough to fill a Python digit. */
917 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000918 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 ++idigit;
920 accum >>= PyLong_SHIFT;
921 accumbits -= PyLong_SHIFT;
922 assert(accumbits < PyLong_SHIFT);
923 }
924 }
925 assert(accumbits < PyLong_SHIFT);
926 if (accumbits) {
927 assert(idigit < ndigits);
928 v->ob_digit[idigit] = (digit)accum;
929 ++idigit;
930 }
931 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 Py_SIZE(v) = is_signed ? -idigit : idigit;
934 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000935}
936
937int
938_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 unsigned char* bytes, size_t n,
940 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000943 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000945 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
947 digit carry; /* for computing 2's-comp */
948 size_t j; /* # bytes filled */
949 unsigned char* p; /* pointer to next byte in bytes */
950 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (Py_SIZE(v) < 0) {
955 ndigits = -(Py_SIZE(v));
956 if (!is_signed) {
957 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000958 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 return -1;
960 }
961 do_twos_comp = 1;
962 }
963 else {
964 ndigits = Py_SIZE(v);
965 do_twos_comp = 0;
966 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 if (little_endian) {
969 p = bytes;
970 pincr = 1;
971 }
972 else {
973 p = bytes + n - 1;
974 pincr = -1;
975 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 /* Copy over all the Python digits.
978 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300979 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 normalized. */
981 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
982 j = 0;
983 accum = 0;
984 accumbits = 0;
985 carry = do_twos_comp ? 1 : 0;
986 for (i = 0; i < ndigits; ++i) {
987 digit thisdigit = v->ob_digit[i];
988 if (do_twos_comp) {
989 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
990 carry = thisdigit >> PyLong_SHIFT;
991 thisdigit &= PyLong_MASK;
992 }
993 /* Because we're going LSB to MSB, thisdigit is more
994 significant than what's already in accum, so needs to be
995 prepended to accum. */
996 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 /* The most-significant digit may be (probably is) at least
999 partly empty. */
1000 if (i == ndigits - 1) {
1001 /* Count # of sign bits -- they needn't be stored,
1002 * although for signed conversion we need later to
1003 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +00001004 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 while (s != 0) {
1006 s >>= 1;
1007 accumbits++;
1008 }
1009 }
1010 else
1011 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 /* Store as many bytes as possible. */
1014 while (accumbits >= 8) {
1015 if (j >= n)
1016 goto Overflow;
1017 ++j;
1018 *p = (unsigned char)(accum & 0xff);
1019 p += pincr;
1020 accumbits -= 8;
1021 accum >>= 8;
1022 }
1023 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 /* Store the straggler (if any). */
1026 assert(accumbits < 8);
1027 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1028 if (accumbits > 0) {
1029 if (j >= n)
1030 goto Overflow;
1031 ++j;
1032 if (do_twos_comp) {
1033 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +03001034 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 infinite supply of sign bits). */
1036 accum |= (~(twodigits)0) << accumbits;
1037 }
1038 *p = (unsigned char)(accum & 0xff);
1039 p += pincr;
1040 }
1041 else if (j == n && n > 0 && is_signed) {
1042 /* The main loop filled the byte array exactly, so the code
1043 just above didn't get to ensure there's a sign bit, and the
1044 loop below wouldn't add one either. Make sure a sign bit
1045 exists. */
1046 unsigned char msb = *(p - pincr);
1047 int sign_bit_set = msb >= 0x80;
1048 assert(accumbits == 0);
1049 if (sign_bit_set == do_twos_comp)
1050 return 0;
1051 else
1052 goto Overflow;
1053 }
Tim Peters05607ad2001-06-13 21:01:27 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 /* Fill remaining bytes with copies of the sign bit. */
1056 {
1057 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1058 for ( ; j < n; ++j, p += pincr)
1059 *p = signbyte;
1060 }
Tim Peters05607ad2001-06-13 21:01:27 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001063
Mark Dickinson22b20182010-05-10 21:27:53 +00001064 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1066 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001067
Tim Peters2a9b3672001-06-11 21:23:58 +00001068}
1069
Serhiy Storchaka95949422013-08-27 19:40:23 +03001070/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001071
1072PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001073PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001074{
Mark Dickinson91044792012-10-18 19:21:43 +01001075#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001076 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001077#else
1078
Tim Peters70128a12001-06-16 08:48:40 +00001079#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001080# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001081#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001082 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001083#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001084
Guido van Rossum78694d91998-09-18 14:14:13 +00001085}
1086
Serhiy Storchaka95949422013-08-27 19:40:23 +03001087/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001088
1089void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001090PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001091{
Tim Peters70128a12001-06-16 08:48:40 +00001092#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1096 x = PyLong_AsLong(vv);
1097 else
1098 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001099#else
Tim Peters70128a12001-06-16 08:48:40 +00001100
Tim Peters70128a12001-06-16 08:48:40 +00001101#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001102# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001103#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001104 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1107 x = PyLong_AsLongLong(vv);
1108 else
1109 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001110
1111#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 if (x == -1 && PyErr_Occurred())
1114 return NULL;
1115 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001116}
1117
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001118/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001119 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001120 */
1121
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001122#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001123
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001124/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001125
1126PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001127PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001130 unsigned long long abs_ival;
1131 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 int ndigits = 0;
1133 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001134
animalize6b519982019-09-06 14:00:56 +08001135 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001136 return get_small_int((sdigit)ival);
1137 }
1138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 if (ival < 0) {
1140 /* avoid signed overflow on negation; see comments
1141 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001142 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 negative = 1;
1144 }
1145 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001146 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 /* Count the number of Python digits.
1150 We used to pick 5 ("big enough for anything"), but that's a
1151 waste of time and space given that 5*15 = 75 bits are rarely
1152 needed. */
1153 t = abs_ival;
1154 while (t) {
1155 ++ndigits;
1156 t >>= PyLong_SHIFT;
1157 }
1158 v = _PyLong_New(ndigits);
1159 if (v != NULL) {
1160 digit *p = v->ob_digit;
1161 Py_SIZE(v) = negative ? -ndigits : ndigits;
1162 t = abs_ival;
1163 while (t) {
1164 *p++ = (digit)(t & PyLong_MASK);
1165 t >>= PyLong_SHIFT;
1166 }
1167 }
1168 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001169}
1170
Serhiy Storchaka95949422013-08-27 19:40:23 +03001171/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001172
1173PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001174PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 PyLongObject *v;
1177 size_t abs_ival;
1178 size_t t; /* unsigned so >> doesn't propagate sign bit */
1179 int ndigits = 0;
1180 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001181
animalize6b519982019-09-06 14:00:56 +08001182 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001183 return get_small_int((sdigit)ival);
1184 }
1185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (ival < 0) {
1187 /* avoid signed overflow when ival = SIZE_T_MIN */
1188 abs_ival = (size_t)(-1-ival)+1;
1189 negative = 1;
1190 }
1191 else {
1192 abs_ival = (size_t)ival;
1193 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 /* Count the number of Python digits. */
1196 t = abs_ival;
1197 while (t) {
1198 ++ndigits;
1199 t >>= PyLong_SHIFT;
1200 }
1201 v = _PyLong_New(ndigits);
1202 if (v != NULL) {
1203 digit *p = v->ob_digit;
1204 Py_SIZE(v) = negative ? -ndigits : ndigits;
1205 t = abs_ival;
1206 while (t) {
1207 *p++ = (digit)(t & PyLong_MASK);
1208 t >>= PyLong_SHIFT;
1209 }
1210 }
1211 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001212}
1213
Serhiy Storchaka95949422013-08-27 19:40:23 +03001214/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001215 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001216
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001217long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001218PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001221 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001223 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 if (vv == NULL) {
1226 PyErr_BadInternalCall();
1227 return -1;
1228 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001229
1230 if (PyLong_Check(vv)) {
1231 v = (PyLongObject *)vv;
1232 }
1233 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001234 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001235 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001237 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001240 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001242 case -1:
1243 bytes = -(sdigit)v->ob_digit[0];
1244 break;
1245 case 0:
1246 bytes = 0;
1247 break;
1248 case 1:
1249 bytes = v->ob_digit[0];
1250 break;
1251 default:
1252 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001253 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001255 if (do_decref) {
1256 Py_DECREF(v);
1257 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001258
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001259 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001261 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 else
1263 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001264}
1265
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001266/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001267 Return -1 and set an error if overflow occurs. */
1268
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001269unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001270PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001273 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001275
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001276 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001278 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001280 if (!PyLong_Check(vv)) {
1281 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001282 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001283 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 v = (PyLongObject*)vv;
1286 switch(Py_SIZE(v)) {
1287 case 0: return 0;
1288 case 1: return v->ob_digit[0];
1289 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001290
Mark Dickinson22b20182010-05-10 21:27:53 +00001291 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001292 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001293
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001294 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001296 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 else
1298 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001299}
Tim Petersd1a7da62001-06-13 00:35:57 +00001300
Serhiy Storchaka95949422013-08-27 19:40:23 +03001301/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001302 Returns -1 and sets an error condition if an error occurs. */
1303
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001304static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001305_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001306{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001307 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001308 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 Py_ssize_t i;
1310 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (vv == NULL || !PyLong_Check(vv)) {
1313 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001314 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 }
1316 v = (PyLongObject *)vv;
1317 switch(Py_SIZE(v)) {
1318 case 0: return 0;
1319 case 1: return v->ob_digit[0];
1320 }
1321 i = Py_SIZE(v);
1322 sign = 1;
1323 x = 0;
1324 if (i < 0) {
1325 sign = -1;
1326 i = -i;
1327 }
1328 while (--i >= 0) {
1329 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1330 }
1331 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001332}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001333
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001334unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001335PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001338 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001339
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001340 if (op == NULL) {
1341 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001342 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001344
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001345 if (PyLong_Check(op)) {
1346 return _PyLong_AsUnsignedLongLongMask(op);
1347 }
1348
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001349 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001351 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001352
1353 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1354 Py_DECREF(lo);
1355 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001356}
Tim Petersd1a7da62001-06-13 00:35:57 +00001357
Serhiy Storchaka95949422013-08-27 19:40:23 +03001358/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001359 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001360
Mark Dickinson8d48b432011-10-23 20:47:14 +01001361 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1362 the result. Otherwise *overflow is 0.
1363
1364 For other errors (e.g., TypeError), return -1 and set an error condition.
1365 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001366*/
1367
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001368long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001369PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001372 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001373 unsigned long long x, prev;
1374 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 Py_ssize_t i;
1376 int sign;
1377 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 *overflow = 0;
1380 if (vv == NULL) {
1381 PyErr_BadInternalCall();
1382 return -1;
1383 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001384
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001385 if (PyLong_Check(vv)) {
1386 v = (PyLongObject *)vv;
1387 }
1388 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001389 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001390 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 return -1;
1392 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 switch (i) {
1399 case -1:
1400 res = -(sdigit)v->ob_digit[0];
1401 break;
1402 case 0:
1403 res = 0;
1404 break;
1405 case 1:
1406 res = v->ob_digit[0];
1407 break;
1408 default:
1409 sign = 1;
1410 x = 0;
1411 if (i < 0) {
1412 sign = -1;
1413 i = -(i);
1414 }
1415 while (--i >= 0) {
1416 prev = x;
1417 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1418 if ((x >> PyLong_SHIFT) != prev) {
1419 *overflow = sign;
1420 goto exit;
1421 }
1422 }
1423 /* Haven't lost any bits, but casting to long requires extra
1424 * care (see comment above).
1425 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001426 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001427 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 }
1429 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001430 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 }
1432 else {
1433 *overflow = sign;
1434 /* res is already set to -1 */
1435 }
1436 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001437 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001439 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 }
1441 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001442}
1443
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001444int
1445_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1446{
1447 unsigned long uval;
1448
1449 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1450 PyErr_SetString(PyExc_ValueError, "value must be positive");
1451 return 0;
1452 }
1453 uval = PyLong_AsUnsignedLong(obj);
1454 if (uval == (unsigned long)-1 && PyErr_Occurred())
1455 return 0;
1456 if (uval > USHRT_MAX) {
1457 PyErr_SetString(PyExc_OverflowError,
1458 "Python int too large for C unsigned short");
1459 return 0;
1460 }
1461
1462 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1463 return 1;
1464}
1465
1466int
1467_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1468{
1469 unsigned long uval;
1470
1471 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1472 PyErr_SetString(PyExc_ValueError, "value must be positive");
1473 return 0;
1474 }
1475 uval = PyLong_AsUnsignedLong(obj);
1476 if (uval == (unsigned long)-1 && PyErr_Occurred())
1477 return 0;
1478 if (uval > UINT_MAX) {
1479 PyErr_SetString(PyExc_OverflowError,
1480 "Python int too large for C unsigned int");
1481 return 0;
1482 }
1483
1484 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1485 return 1;
1486}
1487
1488int
1489_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1490{
1491 unsigned long uval;
1492
1493 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1494 PyErr_SetString(PyExc_ValueError, "value must be positive");
1495 return 0;
1496 }
1497 uval = PyLong_AsUnsignedLong(obj);
1498 if (uval == (unsigned long)-1 && PyErr_Occurred())
1499 return 0;
1500
1501 *(unsigned long *)ptr = uval;
1502 return 1;
1503}
1504
1505int
1506_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1507{
1508 unsigned long long uval;
1509
1510 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1511 PyErr_SetString(PyExc_ValueError, "value must be positive");
1512 return 0;
1513 }
1514 uval = PyLong_AsUnsignedLongLong(obj);
1515 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1516 return 0;
1517
1518 *(unsigned long long *)ptr = uval;
1519 return 1;
1520}
1521
1522int
1523_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1524{
1525 size_t uval;
1526
1527 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1528 PyErr_SetString(PyExc_ValueError, "value must be positive");
1529 return 0;
1530 }
1531 uval = PyLong_AsSize_t(obj);
1532 if (uval == (size_t)-1 && PyErr_Occurred())
1533 return 0;
1534
1535 *(size_t *)ptr = uval;
1536 return 1;
1537}
1538
1539
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001540#define CHECK_BINOP(v,w) \
1541 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001542 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1543 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001544 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001545
Tim Peters877a2122002-08-12 05:09:36 +00001546/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1547 * is modified in place, by adding y to it. Carries are propagated as far as
1548 * x[m-1], and the remaining carry (0 or 1) is returned.
1549 */
1550static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001551v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 Py_ssize_t i;
1554 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 assert(m >= n);
1557 for (i = 0; i < n; ++i) {
1558 carry += x[i] + y[i];
1559 x[i] = carry & PyLong_MASK;
1560 carry >>= PyLong_SHIFT;
1561 assert((carry & 1) == carry);
1562 }
1563 for (; carry && i < m; ++i) {
1564 carry += x[i];
1565 x[i] = carry & PyLong_MASK;
1566 carry >>= PyLong_SHIFT;
1567 assert((carry & 1) == carry);
1568 }
1569 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001570}
1571
1572/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1573 * is modified in place, by subtracting y from it. Borrows are propagated as
1574 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1575 */
1576static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001577v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 Py_ssize_t i;
1580 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 assert(m >= n);
1583 for (i = 0; i < n; ++i) {
1584 borrow = x[i] - y[i] - borrow;
1585 x[i] = borrow & PyLong_MASK;
1586 borrow >>= PyLong_SHIFT;
1587 borrow &= 1; /* keep only 1 sign bit */
1588 }
1589 for (; borrow && i < m; ++i) {
1590 borrow = x[i] - borrow;
1591 x[i] = borrow & PyLong_MASK;
1592 borrow >>= PyLong_SHIFT;
1593 borrow &= 1;
1594 }
1595 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001596}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001597
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001598/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1599 * result in z[0:m], and return the d bits shifted out of the top.
1600 */
1601static digit
1602v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 Py_ssize_t i;
1605 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 assert(0 <= d && d < PyLong_SHIFT);
1608 for (i=0; i < m; i++) {
1609 twodigits acc = (twodigits)a[i] << d | carry;
1610 z[i] = (digit)acc & PyLong_MASK;
1611 carry = (digit)(acc >> PyLong_SHIFT);
1612 }
1613 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001614}
1615
1616/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1617 * result in z[0:m], and return the d bits shifted out of the bottom.
1618 */
1619static digit
1620v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 Py_ssize_t i;
1623 digit carry = 0;
1624 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 assert(0 <= d && d < PyLong_SHIFT);
1627 for (i=m; i-- > 0;) {
1628 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1629 carry = (digit)acc & mask;
1630 z[i] = (digit)(acc >> d);
1631 }
1632 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001633}
1634
Tim Peters212e6142001-07-14 12:23:19 +00001635/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1636 in pout, and returning the remainder. pin and pout point at the LSD.
1637 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001638 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001639 immutable. */
1640
1641static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001642inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 assert(n > 0 && n <= PyLong_MASK);
1647 pin += size;
1648 pout += size;
1649 while (--size >= 0) {
1650 digit hi;
1651 rem = (rem << PyLong_SHIFT) | *--pin;
1652 *--pout = hi = (digit)(rem / n);
1653 rem -= (twodigits)hi * n;
1654 }
1655 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001656}
1657
Serhiy Storchaka95949422013-08-27 19:40:23 +03001658/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001659 (as function result) and the remainder (through *prem).
1660 The sign of a is ignored; n should not be zero. */
1661
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001662static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001663divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001664{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001665 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 assert(n > 0 && n <= PyLong_MASK);
1669 z = _PyLong_New(size);
1670 if (z == NULL)
1671 return NULL;
1672 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1673 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001674}
1675
Serhiy Storchaka95949422013-08-27 19:40:23 +03001676/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001677 string. (Return value is non-shared so that callers can modify the
1678 returned value if necessary.) */
1679
Victor Stinnerd3f08822012-05-29 12:57:52 +02001680static int
1681long_to_decimal_string_internal(PyObject *aa,
1682 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001683 _PyUnicodeWriter *writer,
1684 _PyBytesWriter *bytes_writer,
1685 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001688 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 Py_ssize_t size, strlen, size_a, i, j;
1690 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001692 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001693 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 a = (PyLongObject *)aa;
1696 if (a == NULL || !PyLong_Check(a)) {
1697 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001698 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001700 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 /* quick and dirty upper bound for the number of digits
1704 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 But log2(a) < size_a * PyLong_SHIFT, and
1709 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001710 > 3.3 * _PyLong_DECIMAL_SHIFT
1711
1712 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1713 size_a + size_a / d < size_a + size_a / floor(d),
1714 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1715 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001717 d = (33 * _PyLong_DECIMAL_SHIFT) /
1718 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1719 assert(size_a < PY_SSIZE_T_MAX/2);
1720 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 scratch = _PyLong_New(size);
1722 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001723 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 /* convert array of base _PyLong_BASE digits in pin to an array of
1726 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1727 Volume 2 (3rd edn), section 4.4, Method 1b). */
1728 pin = a->ob_digit;
1729 pout = scratch->ob_digit;
1730 size = 0;
1731 for (i = size_a; --i >= 0; ) {
1732 digit hi = pin[i];
1733 for (j = 0; j < size; j++) {
1734 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1735 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1736 pout[j] = (digit)(z - (twodigits)hi *
1737 _PyLong_DECIMAL_BASE);
1738 }
1739 while (hi) {
1740 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1741 hi /= _PyLong_DECIMAL_BASE;
1742 }
1743 /* check for keyboard interrupt */
1744 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001745 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001746 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001747 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 }
1749 /* pout should have at least one digit, so that the case when a = 0
1750 works correctly */
1751 if (size == 0)
1752 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 /* calculate exact length of output string, and allocate */
1755 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1756 tenpow = 10;
1757 rem = pout[size-1];
1758 while (rem >= tenpow) {
1759 tenpow *= 10;
1760 strlen++;
1761 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001762 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001763 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1764 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001765 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001766 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001767 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001769 else if (bytes_writer) {
1770 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1771 if (*bytes_str == NULL) {
1772 Py_DECREF(scratch);
1773 return -1;
1774 }
1775 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001776 else {
1777 str = PyUnicode_New(strlen, '9');
1778 if (str == NULL) {
1779 Py_DECREF(scratch);
1780 return -1;
1781 }
1782 kind = PyUnicode_KIND(str);
1783 }
1784
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001785#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001786 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001787 /* pout[0] through pout[size-2] contribute exactly \
1788 _PyLong_DECIMAL_SHIFT digits each */ \
1789 for (i=0; i < size - 1; i++) { \
1790 rem = pout[i]; \
1791 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1792 *--p = '0' + rem % 10; \
1793 rem /= 10; \
1794 } \
1795 } \
1796 /* pout[size-1]: always produce at least one decimal digit */ \
1797 rem = pout[i]; \
1798 do { \
1799 *--p = '0' + rem % 10; \
1800 rem /= 10; \
1801 } while (rem != 0); \
1802 \
1803 /* and sign */ \
1804 if (negative) \
1805 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001806 } while (0)
1807
1808#define WRITE_UNICODE_DIGITS(TYPE) \
1809 do { \
1810 if (writer) \
1811 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1812 else \
1813 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1814 \
1815 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001816 \
1817 /* check we've counted correctly */ \
1818 if (writer) \
1819 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1820 else \
1821 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1822 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001825 if (bytes_writer) {
1826 char *p = *bytes_str + strlen;
1827 WRITE_DIGITS(p);
1828 assert(p == *bytes_str);
1829 }
1830 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001831 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001832 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001834 else if (kind == PyUnicode_2BYTE_KIND) {
1835 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001836 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001837 }
1838 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001839 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001840 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001841 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001842 }
1843#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001844#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001847 if (writer) {
1848 writer->pos += strlen;
1849 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001850 else if (bytes_writer) {
1851 (*bytes_str) += strlen;
1852 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001853 else {
1854 assert(_PyUnicode_CheckConsistency(str, 1));
1855 *p_output = (PyObject *)str;
1856 }
1857 return 0;
1858}
1859
1860static PyObject *
1861long_to_decimal_string(PyObject *aa)
1862{
1863 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001864 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001865 return NULL;
1866 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001867}
1868
Serhiy Storchaka95949422013-08-27 19:40:23 +03001869/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001870 which should be one of 2, 8 or 16. Return a string object.
1871 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1872 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001873
Victor Stinnerd3f08822012-05-29 12:57:52 +02001874static int
1875long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001876 PyObject **p_output, _PyUnicodeWriter *writer,
1877 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001878{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001879 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001880 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001881 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001883 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001884 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001886
Victor Stinnerd3f08822012-05-29 12:57:52 +02001887 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (a == NULL || !PyLong_Check(a)) {
1889 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001890 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001892 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001893 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 /* Compute a rough upper bound for the length of the string */
1896 switch (base) {
1897 case 16:
1898 bits = 4;
1899 break;
1900 case 8:
1901 bits = 3;
1902 break;
1903 case 2:
1904 bits = 1;
1905 break;
1906 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001907 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001909
Mark Dickinsone2846542012-04-20 21:21:24 +01001910 /* Compute exact length 'sz' of output string. */
1911 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001912 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001913 }
1914 else {
1915 Py_ssize_t size_a_in_bits;
1916 /* Ensure overflow doesn't occur during computation of sz. */
1917 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1918 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001919 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001921 }
1922 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001923 _Py_bit_length(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001924 /* Allow 1 character for a '-' sign. */
1925 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1926 }
1927 if (alternate) {
1928 /* 2 characters for prefix */
1929 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001930 }
1931
Victor Stinnerd3f08822012-05-29 12:57:52 +02001932 if (writer) {
1933 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1934 return -1;
1935 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001937 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001938 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1939 if (*bytes_str == NULL)
1940 return -1;
1941 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001943 v = PyUnicode_New(sz, 'x');
1944 if (v == NULL)
1945 return -1;
1946 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001948
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001949#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001950 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001951 if (size_a == 0) { \
1952 *--p = '0'; \
1953 } \
1954 else { \
1955 /* JRH: special case for power-of-2 bases */ \
1956 twodigits accum = 0; \
1957 int accumbits = 0; /* # of bits in accum */ \
1958 Py_ssize_t i; \
1959 for (i = 0; i < size_a; ++i) { \
1960 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1961 accumbits += PyLong_SHIFT; \
1962 assert(accumbits >= bits); \
1963 do { \
1964 char cdigit; \
1965 cdigit = (char)(accum & (base - 1)); \
1966 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1967 *--p = cdigit; \
1968 accumbits -= bits; \
1969 accum >>= bits; \
1970 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1971 } \
1972 } \
1973 \
1974 if (alternate) { \
1975 if (base == 16) \
1976 *--p = 'x'; \
1977 else if (base == 8) \
1978 *--p = 'o'; \
1979 else /* (base == 2) */ \
1980 *--p = 'b'; \
1981 *--p = '0'; \
1982 } \
1983 if (negative) \
1984 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001985 } while (0)
1986
1987#define WRITE_UNICODE_DIGITS(TYPE) \
1988 do { \
1989 if (writer) \
1990 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1991 else \
1992 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1993 \
1994 WRITE_DIGITS(p); \
1995 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001996 if (writer) \
1997 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1998 else \
1999 assert(p == (TYPE*)PyUnicode_DATA(v)); \
2000 } while (0)
2001
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002002 if (bytes_writer) {
2003 char *p = *bytes_str + sz;
2004 WRITE_DIGITS(p);
2005 assert(p == *bytes_str);
2006 }
2007 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002008 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002009 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002010 }
2011 else if (kind == PyUnicode_2BYTE_KIND) {
2012 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002013 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002014 }
2015 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002016 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002017 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002018 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002019 }
2020#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002021#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002022
2023 if (writer) {
2024 writer->pos += sz;
2025 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002026 else if (bytes_writer) {
2027 (*bytes_str) += sz;
2028 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002029 else {
2030 assert(_PyUnicode_CheckConsistency(v, 1));
2031 *p_output = v;
2032 }
2033 return 0;
2034}
2035
2036PyObject *
2037_PyLong_Format(PyObject *obj, int base)
2038{
2039 PyObject *str;
2040 int err;
2041 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002042 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002043 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002044 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002045 if (err == -1)
2046 return NULL;
2047 return str;
2048}
2049
2050int
2051_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2052 PyObject *obj,
2053 int base, int alternate)
2054{
2055 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002056 return long_to_decimal_string_internal(obj, NULL, writer,
2057 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002058 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002059 return long_format_binary(obj, base, alternate, NULL, writer,
2060 NULL, NULL);
2061}
2062
2063char*
2064_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2065 PyObject *obj,
2066 int base, int alternate)
2067{
2068 char *str2;
2069 int res;
2070 str2 = str;
2071 if (base == 10)
2072 res = long_to_decimal_string_internal(obj, NULL, NULL,
2073 writer, &str2);
2074 else
2075 res = long_format_binary(obj, base, alternate, NULL, NULL,
2076 writer, &str2);
2077 if (res < 0)
2078 return NULL;
2079 assert(str2 != NULL);
2080 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002081}
2082
Thomas Wouters477c8d52006-05-27 19:21:47 +00002083/* Table of digit values for 8-bit string -> integer conversion.
2084 * '0' maps to 0, ..., '9' maps to 9.
2085 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2086 * All other indices map to 37.
2087 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002088 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002089 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002090unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2092 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2093 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2094 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2095 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2096 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2097 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2098 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2099 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2100 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2101 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2102 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2103 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2104 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2105 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2106 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002107};
2108
2109/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002110 * 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 +03002111 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002112 * The point to this routine is that it takes time linear in the number of
2113 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002114 *
2115 * Return values:
2116 * -1 on syntax error (exception needs to be set, *res is untouched)
2117 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002118 */
Brett Cannona721aba2016-09-09 14:57:09 -07002119static int
2120long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002121{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002122 const char *p = *str;
2123 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002124 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002125 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 int bits_per_char;
2127 Py_ssize_t n;
2128 PyLongObject *z;
2129 twodigits accum;
2130 int bits_in_accum;
2131 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2134 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002135 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002137 }
2138 /* count digits and set p to end-of-string */
2139 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2140 if (*p == '_') {
2141 if (prev == '_') {
2142 *str = p - 1;
2143 return -1;
2144 }
2145 } else {
2146 ++digits;
2147 }
2148 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002150 }
2151 if (prev == '_') {
2152 /* Trailing underscore not allowed. */
2153 *str = p - 1;
2154 return -1;
2155 }
2156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002158 /* n <- the number of Python digits needed,
2159 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2160 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 PyErr_SetString(PyExc_ValueError,
2162 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002163 *res = NULL;
2164 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002166 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002168 if (z == NULL) {
2169 *res = NULL;
2170 return 0;
2171 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002172 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 * from least to most significant in both.
2174 */
2175 accum = 0;
2176 bits_in_accum = 0;
2177 pdigit = z->ob_digit;
2178 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002179 int k;
2180 if (*p == '_') {
2181 continue;
2182 }
2183 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 assert(k >= 0 && k < base);
2185 accum |= (twodigits)k << bits_in_accum;
2186 bits_in_accum += bits_per_char;
2187 if (bits_in_accum >= PyLong_SHIFT) {
2188 *pdigit++ = (digit)(accum & PyLong_MASK);
2189 assert(pdigit - z->ob_digit <= n);
2190 accum >>= PyLong_SHIFT;
2191 bits_in_accum -= PyLong_SHIFT;
2192 assert(bits_in_accum < PyLong_SHIFT);
2193 }
2194 }
2195 if (bits_in_accum) {
2196 assert(bits_in_accum <= PyLong_SHIFT);
2197 *pdigit++ = (digit)accum;
2198 assert(pdigit - z->ob_digit <= n);
2199 }
2200 while (pdigit - z->ob_digit < n)
2201 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002202 *res = long_normalize(z);
2203 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002204}
2205
Serhiy Storchaka95949422013-08-27 19:40:23 +03002206/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002207 * ignored.
2208 *
2209 * If successful, a PyLong object will be returned and 'pend' will be pointing
2210 * to the first unused byte unless it's NULL.
2211 *
2212 * If unsuccessful, NULL will be returned.
2213 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002214PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002215PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002218 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 PyLongObject *z = NULL;
2220 PyObject *strobj;
2221 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 if ((base != 0 && base < 2) || base > 36) {
2224 PyErr_SetString(PyExc_ValueError,
2225 "int() arg 2 must be >= 2 and <= 36");
2226 return NULL;
2227 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002228 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002230 }
2231 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002233 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 else if (*str == '-') {
2235 ++str;
2236 sign = -1;
2237 }
2238 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002239 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002241 }
2242 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002244 }
2245 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002247 }
2248 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002250 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 else {
2252 /* "old" (C-style) octal literal, now invalid.
2253 it might still be zero though */
2254 error_if_nonzero = 1;
2255 base = 10;
2256 }
2257 }
2258 if (str[0] == '0' &&
2259 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2260 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002261 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002263 /* One underscore allowed here. */
2264 if (*str == '_') {
2265 ++str;
2266 }
2267 }
2268 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002269 /* May not start with underscores. */
2270 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002271 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002274 if ((base & (base - 1)) == 0) {
2275 int res = long_from_binary_base(&str, base, &z);
2276 if (res < 0) {
2277 /* Syntax error. */
2278 goto onError;
2279 }
2280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002282/***
2283Binary bases can be converted in time linear in the number of digits, because
2284Python's representation base is binary. Other bases (including decimal!) use
2285the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002286
Thomas Wouters477c8d52006-05-27 19:21:47 +00002287First some math: the largest integer that can be expressed in N base-B digits
2288is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2289case number of Python digits needed to hold it is the smallest integer n s.t.
2290
2291 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2292 BASE**n >= B**N [taking logs to base BASE]
2293 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2294
2295The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002296this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002297and the result is computed into it.
2298
2299The input string is actually treated as being in base base**i (i.e., i digits
2300are processed at a time), where two more static arrays hold:
2301
2302 convwidth_base[base] = the largest integer i such that base**i <= BASE
2303 convmultmax_base[base] = base ** convwidth_base[base]
2304
2305The first of these is the largest i such that i consecutive input digits
2306must fit in a single Python digit. The second is effectively the input
2307base we're really using.
2308
2309Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2310convmultmax_base[base], the result is "simply"
2311
2312 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2313
2314where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002315
2316Error analysis: as above, the number of Python digits `n` needed is worst-
2317case
2318
2319 n >= N * log(B)/log(BASE)
2320
2321where `N` is the number of input digits in base `B`. This is computed via
2322
2323 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2324
2325below. Two numeric concerns are how much space this can waste, and whether
2326the computed result can be too small. To be concrete, assume BASE = 2**15,
2327which is the default (and it's unlikely anyone changes that).
2328
2329Waste isn't a problem: provided the first input digit isn't 0, the difference
2330between the worst-case input with N digits and the smallest input with N
2331digits is about a factor of B, but B is small compared to BASE so at most
2332one allocated Python digit can remain unused on that count. If
2333N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2334and adding 1 returns a result 1 larger than necessary. However, that can't
2335happen: whenever B is a power of 2, long_from_binary_base() is called
2336instead, and it's impossible for B**i to be an integer power of 2**15 when
2337B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2338an exact integer when B is not a power of 2, since B**i has a prime factor
2339other than 2 in that case, but (2**15)**j's only prime factor is 2).
2340
2341The computed result can be too small if the true value of N*log(B)/log(BASE)
2342is a little bit larger than an exact integer, but due to roundoff errors (in
2343computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2344yields a numeric result a little less than that integer. Unfortunately, "how
2345close can a transcendental function get to an integer over some range?"
2346questions are generally theoretically intractable. Computer analysis via
2347continued fractions is practical: expand log(B)/log(BASE) via continued
2348fractions, giving a sequence i/j of "the best" rational approximations. Then
2349j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2350we can get very close to being in trouble, but very rarely. For example,
235176573 is a denominator in one of the continued-fraction approximations to
2352log(10)/log(2**15), and indeed:
2353
2354 >>> log(10)/log(2**15)*76573
2355 16958.000000654003
2356
2357is very close to an integer. If we were working with IEEE single-precision,
2358rounding errors could kill us. Finding worst cases in IEEE double-precision
2359requires better-than-double-precision log() functions, and Tim didn't bother.
2360Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002361new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002362This should happen extremely rarely, and in fact I don't have a test case
2363that triggers it(!). Instead the code was tested by artificially allocating
2364just 1 digit at the start, so that the copying code was exercised for every
2365digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002366***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002367 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002369 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 int i;
2371 int convwidth;
2372 twodigits convmultmax, convmult;
2373 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002374 const char *scan, *lastdigit;
2375 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 static double log_base_BASE[37] = {0.0e0,};
2378 static int convwidth_base[37] = {0,};
2379 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 if (log_base_BASE[base] == 0.0) {
2382 twodigits convmax = base;
2383 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002384
Mark Dickinson22b20182010-05-10 21:27:53 +00002385 log_base_BASE[base] = (log((double)base) /
2386 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 for (;;) {
2388 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002389 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002391 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 convmax = next;
2393 ++i;
2394 }
2395 convmultmax_base[base] = convmax;
2396 assert(i > 0);
2397 convwidth_base[base] = i;
2398 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* Find length of the string of numeric characters. */
2401 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002402 lastdigit = str;
2403
2404 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2405 if (*scan == '_') {
2406 if (prev == '_') {
2407 /* Only one underscore allowed. */
2408 str = lastdigit + 1;
2409 goto onError;
2410 }
2411 }
2412 else {
2413 ++digits;
2414 lastdigit = scan;
2415 }
2416 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002418 }
2419 if (prev == '_') {
2420 /* Trailing underscore not allowed. */
2421 /* Set error pointer to first underscore. */
2422 str = lastdigit + 1;
2423 goto onError;
2424 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002425
Serhiy Storchaka95949422013-08-27 19:40:23 +03002426 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 * integer with this base and length. Note that there's no
2428 * need to initialize z->ob_digit -- no slot is read up before
2429 * being stored into.
2430 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002431 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2432 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002433 /* The same exception as in _PyLong_New(). */
2434 PyErr_SetString(PyExc_OverflowError,
2435 "too many digits in integer");
2436 return NULL;
2437 }
2438 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 /* Uncomment next line to test exceedingly rare copy code */
2440 /* size_z = 1; */
2441 assert(size_z > 0);
2442 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002443 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002445 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 /* `convwidth` consecutive input digits are treated as a single
2449 * digit in base `convmultmax`.
2450 */
2451 convwidth = convwidth_base[base];
2452 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 /* Work ;-) */
2455 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002456 if (*str == '_') {
2457 str++;
2458 continue;
2459 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 /* grab up to convwidth digits from the input string */
2461 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002462 for (i = 1; i < convwidth && str != scan; ++str) {
2463 if (*str == '_') {
2464 continue;
2465 }
2466 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002468 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 assert(c < PyLong_BASE);
2470 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 convmult = convmultmax;
2473 /* Calculate the shift only if we couldn't get
2474 * convwidth digits.
2475 */
2476 if (i != convwidth) {
2477 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002478 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002480 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 /* Multiply z by convmult, and add c. */
2484 pz = z->ob_digit;
2485 pzstop = pz + Py_SIZE(z);
2486 for (; pz < pzstop; ++pz) {
2487 c += (twodigits)*pz * convmult;
2488 *pz = (digit)(c & PyLong_MASK);
2489 c >>= PyLong_SHIFT;
2490 }
2491 /* carry off the current end? */
2492 if (c) {
2493 assert(c < PyLong_BASE);
2494 if (Py_SIZE(z) < size_z) {
2495 *pz = (digit)c;
2496 ++Py_SIZE(z);
2497 }
2498 else {
2499 PyLongObject *tmp;
2500 /* Extremely rare. Get more space. */
2501 assert(Py_SIZE(z) == size_z);
2502 tmp = _PyLong_New(size_z + 1);
2503 if (tmp == NULL) {
2504 Py_DECREF(z);
2505 return NULL;
2506 }
2507 memcpy(tmp->ob_digit,
2508 z->ob_digit,
2509 sizeof(digit) * size_z);
2510 Py_DECREF(z);
2511 z = tmp;
2512 z->ob_digit[size_z] = (digit)c;
2513 ++size_z;
2514 }
2515 }
2516 }
2517 }
Brett Cannona721aba2016-09-09 14:57:09 -07002518 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002520 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 if (error_if_nonzero) {
2522 /* reset the base to 0, else the exception message
2523 doesn't make too much sense */
2524 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002525 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002527 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 /* there might still be other problems, therefore base
2529 remains zero here for the same reason */
2530 }
Brett Cannona721aba2016-09-09 14:57:09 -07002531 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002533 }
2534 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002536 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002537 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002539 }
2540 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002542 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002544 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002545 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002546 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002547 }
2548 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002549 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002550 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002551 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002552
Mark Dickinson22b20182010-05-10 21:27:53 +00002553 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002554 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002555 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002556 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 Py_XDECREF(z);
2558 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2559 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002560 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002562 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002564 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 base, strobj);
2566 Py_DECREF(strobj);
2567 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002568}
2569
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002570/* Since PyLong_FromString doesn't have a length parameter,
2571 * check here for possible NULs in the string.
2572 *
2573 * Reports an invalid literal as a bytes object.
2574 */
2575PyObject *
2576_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2577{
2578 PyObject *result, *strobj;
2579 char *end = NULL;
2580
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002581 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002582 if (end == NULL || (result != NULL && end == s + len))
2583 return result;
2584 Py_XDECREF(result);
2585 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2586 if (strobj != NULL) {
2587 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002588 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002589 base, strobj);
2590 Py_DECREF(strobj);
2591 }
2592 return NULL;
2593}
2594
Guido van Rossum9e896b32000-04-05 20:11:21 +00002595PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002596PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002597{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002598 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002599 if (unicode == NULL)
2600 return NULL;
2601 v = PyLong_FromUnicodeObject(unicode, base);
2602 Py_DECREF(unicode);
2603 return v;
2604}
2605
2606PyObject *
2607PyLong_FromUnicodeObject(PyObject *u, int base)
2608{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002609 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002610 const char *buffer;
2611 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002612 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002613
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002614 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002615 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002617 assert(PyUnicode_IS_ASCII(asciidig));
2618 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002620 assert(buffer != NULL);
2621
2622 result = PyLong_FromString(buffer, &end, base);
2623 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002624 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002625 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002627 Py_DECREF(asciidig);
2628 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002629 PyErr_Format(PyExc_ValueError,
2630 "invalid literal for int() with base %d: %.200R",
2631 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002632 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002633}
2634
Tim Peters9f688bf2000-07-07 15:53:28 +00002635/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002636static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002638static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002639
Serhiy Storchaka95949422013-08-27 19:40:23 +03002640/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002641
Guido van Rossume32e0141992-01-19 16:31:05 +00002642static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002643long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002645{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002646 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 if (size_b == 0) {
2650 PyErr_SetString(PyExc_ZeroDivisionError,
2651 "integer division or modulo by zero");
2652 return -1;
2653 }
2654 if (size_a < size_b ||
2655 (size_a == size_b &&
2656 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2657 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002658 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002659 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002660 return -1;
2661 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002662 Py_INCREF(_PyLong_Zero);
2663 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 return 0;
2665 }
2666 if (size_b == 1) {
2667 digit rem = 0;
2668 z = divrem1(a, b->ob_digit[0], &rem);
2669 if (z == NULL)
2670 return -1;
2671 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2672 if (*prem == NULL) {
2673 Py_DECREF(z);
2674 return -1;
2675 }
2676 }
2677 else {
2678 z = x_divrem(a, b, prem);
2679 if (z == NULL)
2680 return -1;
2681 }
2682 /* Set the signs.
2683 The quotient z has the sign of a*b;
2684 the remainder r has the sign of a,
2685 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002686 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2687 _PyLong_Negate(&z);
2688 if (z == NULL) {
2689 Py_CLEAR(*prem);
2690 return -1;
2691 }
2692 }
2693 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2694 _PyLong_Negate(prem);
2695 if (*prem == NULL) {
2696 Py_DECREF(z);
2697 Py_CLEAR(*prem);
2698 return -1;
2699 }
2700 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 *pdiv = maybe_small_long(z);
2702 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002703}
2704
Serhiy Storchaka95949422013-08-27 19:40:23 +03002705/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002706 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002707
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002708static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002709x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 PyLongObject *v, *w, *a;
2712 Py_ssize_t i, k, size_v, size_w;
2713 int d;
2714 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2715 twodigits vv;
2716 sdigit zhi;
2717 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2720 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2721 handle the special case when the initial estimate q for a quotient
2722 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2723 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002726 size_v = Py_ABS(Py_SIZE(v1));
2727 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2729 v = _PyLong_New(size_v+1);
2730 if (v == NULL) {
2731 *prem = NULL;
2732 return NULL;
2733 }
2734 w = _PyLong_New(size_w);
2735 if (w == NULL) {
2736 Py_DECREF(v);
2737 *prem = NULL;
2738 return NULL;
2739 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2742 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002743 d = PyLong_SHIFT - _Py_bit_length(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2745 assert(carry == 0);
2746 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2747 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2748 v->ob_digit[size_v] = carry;
2749 size_v++;
2750 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2753 at most (and usually exactly) k = size_v - size_w digits. */
2754 k = size_v - size_w;
2755 assert(k >= 0);
2756 a = _PyLong_New(k);
2757 if (a == NULL) {
2758 Py_DECREF(w);
2759 Py_DECREF(v);
2760 *prem = NULL;
2761 return NULL;
2762 }
2763 v0 = v->ob_digit;
2764 w0 = w->ob_digit;
2765 wm1 = w0[size_w-1];
2766 wm2 = w0[size_w-2];
2767 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2768 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2769 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002772 Py_DECREF(a);
2773 Py_DECREF(w);
2774 Py_DECREF(v);
2775 *prem = NULL;
2776 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002777 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 /* estimate quotient digit q; may overestimate by 1 (rare) */
2780 vtop = vk[size_w];
2781 assert(vtop <= wm1);
2782 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2783 q = (digit)(vv / wm1);
2784 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2785 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2786 | vk[size_w-2])) {
2787 --q;
2788 r += wm1;
2789 if (r >= PyLong_BASE)
2790 break;
2791 }
2792 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2795 zhi = 0;
2796 for (i = 0; i < size_w; ++i) {
2797 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2798 -PyLong_BASE * q <= z < PyLong_BASE */
2799 z = (sdigit)vk[i] + zhi -
2800 (stwodigits)q * (stwodigits)w0[i];
2801 vk[i] = (digit)z & PyLong_MASK;
2802 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002803 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 /* add w back if q was too large (this branch taken rarely) */
2807 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2808 if ((sdigit)vtop + zhi < 0) {
2809 carry = 0;
2810 for (i = 0; i < size_w; ++i) {
2811 carry += vk[i] + w0[i];
2812 vk[i] = carry & PyLong_MASK;
2813 carry >>= PyLong_SHIFT;
2814 }
2815 --q;
2816 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 /* store quotient digit */
2819 assert(q < PyLong_BASE);
2820 *--ak = q;
2821 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 /* unshift remainder; we reuse w to store the result */
2824 carry = v_rshift(w0, v0, size_w, d);
2825 assert(carry==0);
2826 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 *prem = long_normalize(w);
2829 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002830}
2831
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002832/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2833 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2834 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2835 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2836 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2837 -1.0. */
2838
2839/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2840#if DBL_MANT_DIG == 53
2841#define EXP2_DBL_MANT_DIG 9007199254740992.0
2842#else
2843#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2844#endif
2845
2846double
2847_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2850 /* See below for why x_digits is always large enough. */
2851 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2852 double dx;
2853 /* Correction term for round-half-to-even rounding. For a digit x,
2854 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2855 multiple of 4, rounding ties to a multiple of 8. */
2856 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002857
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002858 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 if (a_size == 0) {
2860 /* Special case for 0: significand 0.0, exponent 0. */
2861 *e = 0;
2862 return 0.0;
2863 }
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002864 a_bits = _Py_bit_length(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 /* The following is an overflow-free version of the check
2866 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2867 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2868 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2869 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002870 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2874 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 Number of digits needed for result: write // for floor division.
2877 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2886 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2889 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2890 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 in both cases.
2897 */
2898 if (a_bits <= DBL_MANT_DIG + 2) {
2899 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2900 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2901 x_size = 0;
2902 while (x_size < shift_digits)
2903 x_digits[x_size++] = 0;
2904 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2905 (int)shift_bits);
2906 x_size += a_size;
2907 x_digits[x_size++] = rem;
2908 }
2909 else {
2910 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2911 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2912 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2913 a_size - shift_digits, (int)shift_bits);
2914 x_size = a_size - shift_digits;
2915 /* For correct rounding below, we need the least significant
2916 bit of x to be 'sticky' for this shift: if any of the bits
2917 shifted out was nonzero, we set the least significant bit
2918 of x. */
2919 if (rem)
2920 x_digits[0] |= 1;
2921 else
2922 while (shift_digits > 0)
2923 if (a->ob_digit[--shift_digits]) {
2924 x_digits[0] |= 1;
2925 break;
2926 }
2927 }
Victor Stinner63941882011-09-29 00:42:28 +02002928 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 /* Round, and convert to double. */
2931 x_digits[0] += half_even_correction[x_digits[0] & 7];
2932 dx = x_digits[--x_size];
2933 while (x_size > 0)
2934 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 /* Rescale; make correction if result is 1.0. */
2937 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2938 if (dx == 1.0) {
2939 if (a_bits == PY_SSIZE_T_MAX)
2940 goto overflow;
2941 dx = 0.5;
2942 a_bits += 1;
2943 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 *e = a_bits;
2946 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002947
2948 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 /* exponent > PY_SSIZE_T_MAX */
2950 PyErr_SetString(PyExc_OverflowError,
2951 "huge integer: number of bits overflows a Py_ssize_t");
2952 *e = 0;
2953 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002954}
2955
Serhiy Storchaka95949422013-08-27 19:40:23 +03002956/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002957 using the round-half-to-even rule in the case of a tie. */
2958
2959double
2960PyLong_AsDouble(PyObject *v)
2961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 Py_ssize_t exponent;
2963 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002964
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002965 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 PyErr_BadInternalCall();
2967 return -1.0;
2968 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002969 if (!PyLong_Check(v)) {
2970 PyErr_SetString(PyExc_TypeError, "an integer is required");
2971 return -1.0;
2972 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002973 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002974 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002975 to double. This improves performance of FP/long operations
2976 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002977 */
2978 return (double)MEDIUM_VALUE((PyLongObject *)v);
2979 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2981 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2982 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002983 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 return -1.0;
2985 }
2986 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002987}
2988
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002989/* Methods */
2990
HongWeipeng42acb7b2019-09-18 23:10:15 +08002991/* if a < b, return a negative number
2992 if a == b, return 0
2993 if a > b, return a positive number */
2994
2995static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002996long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002997{
HongWeipeng42acb7b2019-09-18 23:10:15 +08002998 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
2999 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003000 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08003001 sdigit diff = 0;
3002 while (--i >= 0) {
3003 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
3004 if (diff) {
3005 break;
3006 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003008 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003010 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003011}
3012
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003013static PyObject *
3014long_richcompare(PyObject *self, PyObject *other, int op)
3015{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003016 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 CHECK_BINOP(self, other);
3018 if (self == other)
3019 result = 0;
3020 else
3021 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003022 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003023}
3024
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003025static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003026long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003027{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003028 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 Py_ssize_t i;
3030 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 i = Py_SIZE(v);
3033 switch(i) {
3034 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3035 case 0: return 0;
3036 case 1: return v->ob_digit[0];
3037 }
3038 sign = 1;
3039 x = 0;
3040 if (i < 0) {
3041 sign = -1;
3042 i = -(i);
3043 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003045 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3046 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3047 _PyHASH_MODULUS.
3048
3049 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3050 amounts to a rotation of the bits of x. To see this, write
3051
3052 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3053
3054 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3055 PyLong_SHIFT bits of x (those that are shifted out of the
3056 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3057 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3058 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3059 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3060 congruent to y modulo _PyHASH_MODULUS. So
3061
3062 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3063
3064 The right-hand side is just the result of rotating the
3065 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3066 not all _PyHASH_BITS bits of x are 1s, the same is true
3067 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3068 the reduction of x*2**PyLong_SHIFT modulo
3069 _PyHASH_MODULUS. */
3070 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3071 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003073 if (x >= _PyHASH_MODULUS)
3074 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 }
3076 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003077 if (x == (Py_uhash_t)-1)
3078 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003079 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003080}
3081
3082
Serhiy Storchaka95949422013-08-27 19:40:23 +03003083/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003085static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003086x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003087{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003088 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 PyLongObject *z;
3090 Py_ssize_t i;
3091 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 /* Ensure a is the larger of the two: */
3094 if (size_a < size_b) {
3095 { PyLongObject *temp = a; a = b; b = temp; }
3096 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003097 size_a = size_b;
3098 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 }
3100 z = _PyLong_New(size_a+1);
3101 if (z == NULL)
3102 return NULL;
3103 for (i = 0; i < size_b; ++i) {
3104 carry += a->ob_digit[i] + b->ob_digit[i];
3105 z->ob_digit[i] = carry & PyLong_MASK;
3106 carry >>= PyLong_SHIFT;
3107 }
3108 for (; i < size_a; ++i) {
3109 carry += a->ob_digit[i];
3110 z->ob_digit[i] = carry & PyLong_MASK;
3111 carry >>= PyLong_SHIFT;
3112 }
3113 z->ob_digit[i] = carry;
3114 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003115}
3116
3117/* Subtract the absolute values of two integers. */
3118
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003119static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003120x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003121{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003122 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 PyLongObject *z;
3124 Py_ssize_t i;
3125 int sign = 1;
3126 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 /* Ensure a is the larger of the two: */
3129 if (size_a < size_b) {
3130 sign = -1;
3131 { PyLongObject *temp = a; a = b; b = temp; }
3132 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003133 size_a = size_b;
3134 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 }
3136 else if (size_a == size_b) {
3137 /* Find highest digit where a and b differ: */
3138 i = size_a;
3139 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3140 ;
3141 if (i < 0)
3142 return (PyLongObject *)PyLong_FromLong(0);
3143 if (a->ob_digit[i] < b->ob_digit[i]) {
3144 sign = -1;
3145 { PyLongObject *temp = a; a = b; b = temp; }
3146 }
3147 size_a = size_b = i+1;
3148 }
3149 z = _PyLong_New(size_a);
3150 if (z == NULL)
3151 return NULL;
3152 for (i = 0; i < size_b; ++i) {
3153 /* The following assumes unsigned arithmetic
3154 works module 2**N for some N>PyLong_SHIFT. */
3155 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3156 z->ob_digit[i] = borrow & PyLong_MASK;
3157 borrow >>= PyLong_SHIFT;
3158 borrow &= 1; /* Keep only one sign bit */
3159 }
3160 for (; i < size_a; ++i) {
3161 borrow = a->ob_digit[i] - borrow;
3162 z->ob_digit[i] = borrow & PyLong_MASK;
3163 borrow >>= PyLong_SHIFT;
3164 borrow &= 1; /* Keep only one sign bit */
3165 }
3166 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003167 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003168 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003169 }
HongWeipeng036fe852019-11-26 15:54:49 +08003170 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003171}
3172
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003173static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003174long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003179
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003180 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003181 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 }
3183 if (Py_SIZE(a) < 0) {
3184 if (Py_SIZE(b) < 0) {
3185 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003186 if (z != NULL) {
3187 /* x_add received at least one multiple-digit int,
3188 and thus z must be a multiple-digit int.
3189 That also means z is not an element of
3190 small_ints, so negating it in-place is safe. */
3191 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003193 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 }
3195 else
3196 z = x_sub(b, a);
3197 }
3198 else {
3199 if (Py_SIZE(b) < 0)
3200 z = x_sub(a, b);
3201 else
3202 z = x_add(a, b);
3203 }
3204 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003205}
3206
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003207static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003208long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003213
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003214 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003215 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 }
3217 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003218 if (Py_SIZE(b) < 0) {
3219 z = x_sub(b, a);
3220 }
3221 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003223 if (z != NULL) {
3224 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
3225 Py_SIZE(z) = -(Py_SIZE(z));
3226 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003227 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 }
3229 else {
3230 if (Py_SIZE(b) < 0)
3231 z = x_add(a, b);
3232 else
3233 z = x_sub(a, b);
3234 }
3235 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003236}
3237
Tim Peters5af4e6c2002-08-12 02:31:19 +00003238/* Grade school multiplication, ignoring the signs.
3239 * Returns the absolute value of the product, or NULL if error.
3240 */
3241static PyLongObject *
3242x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003245 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3246 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 z = _PyLong_New(size_a + size_b);
3250 if (z == NULL)
3251 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3254 if (a == b) {
3255 /* Efficient squaring per HAC, Algorithm 14.16:
3256 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3257 * Gives slightly less than a 2x speedup when a == b,
3258 * via exploiting that each entry in the multiplication
3259 * pyramid appears twice (except for the size_a squares).
3260 */
3261 for (i = 0; i < size_a; ++i) {
3262 twodigits carry;
3263 twodigits f = a->ob_digit[i];
3264 digit *pz = z->ob_digit + (i << 1);
3265 digit *pa = a->ob_digit + i + 1;
3266 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003269 Py_DECREF(z);
3270 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003271 });
Tim Peters0973b992004-08-29 22:16:50 +00003272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 carry = *pz + f * f;
3274 *pz++ = (digit)(carry & PyLong_MASK);
3275 carry >>= PyLong_SHIFT;
3276 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 /* Now f is added in twice in each column of the
3279 * pyramid it appears. Same as adding f<<1 once.
3280 */
3281 f <<= 1;
3282 while (pa < paend) {
3283 carry += *pz + *pa++ * f;
3284 *pz++ = (digit)(carry & PyLong_MASK);
3285 carry >>= PyLong_SHIFT;
3286 assert(carry <= (PyLong_MASK << 1));
3287 }
3288 if (carry) {
3289 carry += *pz;
3290 *pz++ = (digit)(carry & PyLong_MASK);
3291 carry >>= PyLong_SHIFT;
3292 }
3293 if (carry)
3294 *pz += (digit)(carry & PyLong_MASK);
3295 assert((carry >> PyLong_SHIFT) == 0);
3296 }
3297 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003298 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 for (i = 0; i < size_a; ++i) {
3300 twodigits carry = 0;
3301 twodigits f = a->ob_digit[i];
3302 digit *pz = z->ob_digit + i;
3303 digit *pb = b->ob_digit;
3304 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003307 Py_DECREF(z);
3308 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003309 });
Tim Peters0973b992004-08-29 22:16:50 +00003310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 while (pb < pbend) {
3312 carry += *pz + *pb++ * f;
3313 *pz++ = (digit)(carry & PyLong_MASK);
3314 carry >>= PyLong_SHIFT;
3315 assert(carry <= PyLong_MASK);
3316 }
3317 if (carry)
3318 *pz += (digit)(carry & PyLong_MASK);
3319 assert((carry >> PyLong_SHIFT) == 0);
3320 }
3321 }
3322 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003323}
3324
3325/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003326 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003327 split, and sets low and high such that abs(n) == (high << size) + low,
3328 viewing the shift as being by digits. The sign bit is ignored, and
3329 the return values are >= 0.
3330 Returns 0 on success, -1 on failure.
3331*/
3332static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003333kmul_split(PyLongObject *n,
3334 Py_ssize_t size,
3335 PyLongObject **high,
3336 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 PyLongObject *hi, *lo;
3339 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003340 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341
Victor Stinner640c35c2013-06-04 23:14:37 +02003342 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 if ((hi = _PyLong_New(size_hi)) == NULL)
3346 return -1;
3347 if ((lo = _PyLong_New(size_lo)) == NULL) {
3348 Py_DECREF(hi);
3349 return -1;
3350 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3353 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 *high = long_normalize(hi);
3356 *low = long_normalize(lo);
3357 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003358}
3359
Tim Peters60004642002-08-12 22:01:34 +00003360static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3361
Tim Peters5af4e6c2002-08-12 02:31:19 +00003362/* Karatsuba multiplication. Ignores the input signs, and returns the
3363 * absolute value of the product (or NULL if error).
3364 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3365 */
3366static PyLongObject *
3367k_mul(PyLongObject *a, PyLongObject *b)
3368{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003369 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3370 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 PyLongObject *ah = NULL;
3372 PyLongObject *al = NULL;
3373 PyLongObject *bh = NULL;
3374 PyLongObject *bl = NULL;
3375 PyLongObject *ret = NULL;
3376 PyLongObject *t1, *t2, *t3;
3377 Py_ssize_t shift; /* the number of digits we split off */
3378 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3381 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3382 * Then the original product is
3383 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3384 * By picking X to be a power of 2, "*X" is just shifting, and it's
3385 * been reduced to 3 multiplies on numbers half the size.
3386 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 /* We want to split based on the larger number; fiddle so that b
3389 * is largest.
3390 */
3391 if (asize > bsize) {
3392 t1 = a;
3393 a = b;
3394 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 i = asize;
3397 asize = bsize;
3398 bsize = i;
3399 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 /* Use gradeschool math when either number is too small. */
3402 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3403 if (asize <= i) {
3404 if (asize == 0)
3405 return (PyLongObject *)PyLong_FromLong(0);
3406 else
3407 return x_mul(a, b);
3408 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 /* If a is small compared to b, splitting on b gives a degenerate
3411 * case with ah==0, and Karatsuba may be (even much) less efficient
3412 * than "grade school" then. However, we can still win, by viewing
3413 * b as a string of "big digits", each of width a->ob_size. That
3414 * leads to a sequence of balanced calls to k_mul.
3415 */
3416 if (2 * asize <= bsize)
3417 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 /* Split a & b into hi & lo pieces. */
3420 shift = bsize >> 1;
3421 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3422 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 if (a == b) {
3425 bh = ah;
3426 bl = al;
3427 Py_INCREF(bh);
3428 Py_INCREF(bl);
3429 }
3430 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 /* The plan:
3433 * 1. Allocate result space (asize + bsize digits: that's always
3434 * enough).
3435 * 2. Compute ah*bh, and copy into result at 2*shift.
3436 * 3. Compute al*bl, and copy into result at 0. Note that this
3437 * can't overlap with #2.
3438 * 4. Subtract al*bl from the result, starting at shift. This may
3439 * underflow (borrow out of the high digit), but we don't care:
3440 * we're effectively doing unsigned arithmetic mod
3441 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3442 * borrows and carries out of the high digit can be ignored.
3443 * 5. Subtract ah*bh from the result, starting at shift.
3444 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3445 * at shift.
3446 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 /* 1. Allocate result space. */
3449 ret = _PyLong_New(asize + bsize);
3450 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003451#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 /* Fill with trash, to catch reference to uninitialized digits. */
3453 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003454#endif
Tim Peters44121a62002-08-12 06:17:58 +00003455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3457 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3458 assert(Py_SIZE(t1) >= 0);
3459 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3460 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3461 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 /* Zero-out the digits higher than the ah*bh copy. */
3464 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3465 if (i)
3466 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3467 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 /* 3. t2 <- al*bl, and copy into the low digits. */
3470 if ((t2 = k_mul(al, bl)) == NULL) {
3471 Py_DECREF(t1);
3472 goto fail;
3473 }
3474 assert(Py_SIZE(t2) >= 0);
3475 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3476 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 /* Zero out remaining digits. */
3479 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3480 if (i)
3481 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3484 * because it's fresher in cache.
3485 */
3486 i = Py_SIZE(ret) - shift; /* # digits after shift */
3487 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3488 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3491 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3494 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3495 Py_DECREF(ah);
3496 Py_DECREF(al);
3497 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 if (a == b) {
3500 t2 = t1;
3501 Py_INCREF(t2);
3502 }
3503 else if ((t2 = x_add(bh, bl)) == NULL) {
3504 Py_DECREF(t1);
3505 goto fail;
3506 }
3507 Py_DECREF(bh);
3508 Py_DECREF(bl);
3509 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 t3 = k_mul(t1, t2);
3512 Py_DECREF(t1);
3513 Py_DECREF(t2);
3514 if (t3 == NULL) goto fail;
3515 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 /* Add t3. It's not obvious why we can't run out of room here.
3518 * See the (*) comment after this function.
3519 */
3520 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3521 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003524
Mark Dickinson22b20182010-05-10 21:27:53 +00003525 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 Py_XDECREF(ret);
3527 Py_XDECREF(ah);
3528 Py_XDECREF(al);
3529 Py_XDECREF(bh);
3530 Py_XDECREF(bl);
3531 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003532}
3533
Tim Petersd6974a52002-08-13 20:37:51 +00003534/* (*) Why adding t3 can't "run out of room" above.
3535
Tim Petersab86c2b2002-08-15 20:06:00 +00003536Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3537to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003538
Tim Petersab86c2b2002-08-15 20:06:00 +000035391. For any integer i, i = c(i/2) + f(i/2). In particular,
3540 bsize = c(bsize/2) + f(bsize/2).
35412. shift = f(bsize/2)
35423. asize <= bsize
35434. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3544 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003545
Tim Petersab86c2b2002-08-15 20:06:00 +00003546We allocated asize + bsize result digits, and add t3 into them at an offset
3547of shift. This leaves asize+bsize-shift allocated digit positions for t3
3548to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3549asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003550
Tim Petersab86c2b2002-08-15 20:06:00 +00003551bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3552at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003553
Tim Petersab86c2b2002-08-15 20:06:00 +00003554If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3555digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3556most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003557
Tim Petersab86c2b2002-08-15 20:06:00 +00003558The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003559
Tim Petersab86c2b2002-08-15 20:06:00 +00003560 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003561
Tim Petersab86c2b2002-08-15 20:06:00 +00003562and we have asize + c(bsize/2) available digit positions. We need to show
3563this is always enough. An instance of c(bsize/2) cancels out in both, so
3564the question reduces to whether asize digits is enough to hold
3565(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3566then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3567asize 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 +00003568digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003569asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003570c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3571is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3572bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003573
Tim Peters48d52c02002-08-14 17:07:32 +00003574Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3575clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3576ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003577*/
3578
Tim Peters60004642002-08-12 22:01:34 +00003579/* b has at least twice the digits of a, and a is big enough that Karatsuba
3580 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3581 * of slices, each with a->ob_size digits, and multiply the slices by a,
3582 * one at a time. This gives k_mul balanced inputs to work with, and is
3583 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003584 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003585 * single-width slice overlap between successive partial sums).
3586 */
3587static PyLongObject *
3588k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3589{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003590 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3591 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 Py_ssize_t nbdone; /* # of b digits already multiplied */
3593 PyLongObject *ret;
3594 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 assert(asize > KARATSUBA_CUTOFF);
3597 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 /* Allocate result space, and zero it out. */
3600 ret = _PyLong_New(asize + bsize);
3601 if (ret == NULL)
3602 return NULL;
3603 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 /* Successive slices of b are copied into bslice. */
3606 bslice = _PyLong_New(asize);
3607 if (bslice == NULL)
3608 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 nbdone = 0;
3611 while (bsize > 0) {
3612 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003613 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 /* Multiply the next slice of b by a. */
3616 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3617 nbtouse * sizeof(digit));
3618 Py_SIZE(bslice) = nbtouse;
3619 product = k_mul(a, bslice);
3620 if (product == NULL)
3621 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 /* Add into result. */
3624 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3625 product->ob_digit, Py_SIZE(product));
3626 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 bsize -= nbtouse;
3629 nbdone += nbtouse;
3630 }
Tim Peters60004642002-08-12 22:01:34 +00003631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 Py_DECREF(bslice);
3633 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003634
Mark Dickinson22b20182010-05-10 21:27:53 +00003635 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 Py_DECREF(ret);
3637 Py_XDECREF(bslice);
3638 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003639}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003640
3641static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003642long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003649 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003651 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 z = k_mul(a, b);
3655 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003656 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3657 _PyLong_Negate(&z);
3658 if (z == NULL)
3659 return NULL;
3660 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003662}
3663
Yury Selivanove0b23092016-02-11 10:26:27 -05003664/* Fast modulo division for single-digit longs. */
3665static PyObject *
3666fast_mod(PyLongObject *a, PyLongObject *b)
3667{
3668 sdigit left = a->ob_digit[0];
3669 sdigit right = b->ob_digit[0];
3670 sdigit mod;
3671
3672 assert(Py_ABS(Py_SIZE(a)) == 1);
3673 assert(Py_ABS(Py_SIZE(b)) == 1);
3674
3675 if (Py_SIZE(a) == Py_SIZE(b)) {
3676 /* 'a' and 'b' have the same sign. */
3677 mod = left % right;
3678 }
3679 else {
3680 /* Either 'a' or 'b' is negative. */
3681 mod = right - 1 - (left - 1) % right;
3682 }
3683
Victor Stinnerf963c132016-03-23 18:36:54 +01003684 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003685}
3686
3687/* Fast floor division for single-digit longs. */
3688static PyObject *
3689fast_floor_div(PyLongObject *a, PyLongObject *b)
3690{
3691 sdigit left = a->ob_digit[0];
3692 sdigit right = b->ob_digit[0];
3693 sdigit div;
3694
3695 assert(Py_ABS(Py_SIZE(a)) == 1);
3696 assert(Py_ABS(Py_SIZE(b)) == 1);
3697
3698 if (Py_SIZE(a) == Py_SIZE(b)) {
3699 /* 'a' and 'b' have the same sign. */
3700 div = left / right;
3701 }
3702 else {
3703 /* Either 'a' or 'b' is negative. */
3704 div = -1 - (left - 1) / right;
3705 }
3706
3707 return PyLong_FromLong(div);
3708}
3709
Guido van Rossume32e0141992-01-19 16:31:05 +00003710/* The / and % operators are now defined in terms of divmod().
3711 The expression a mod b has the value a - b*floor(a/b).
3712 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003713 |a| by |b|, with the sign of a. This is also expressed
3714 as a - b*trunc(a/b), if trunc truncates towards zero.
3715 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 a b a rem b a mod b
3717 13 10 3 3
3718 -13 10 -3 7
3719 13 -10 3 -7
3720 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003721 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003722 have different signs. We then subtract one from the 'div'
3723 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003724
Tim Peters47e52ee2004-08-30 02:44:38 +00003725/* Compute
3726 * *pdiv, *pmod = divmod(v, w)
3727 * NULL can be passed for pdiv or pmod, in which case that part of
3728 * the result is simply thrown away. The caller owns a reference to
3729 * each of these it requests (does not pass NULL for).
3730 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003731static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003732l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003736
Yury Selivanove0b23092016-02-11 10:26:27 -05003737 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3738 /* Fast path for single-digit longs */
3739 div = NULL;
3740 if (pdiv != NULL) {
3741 div = (PyLongObject *)fast_floor_div(v, w);
3742 if (div == NULL) {
3743 return -1;
3744 }
3745 }
3746 if (pmod != NULL) {
3747 mod = (PyLongObject *)fast_mod(v, w);
3748 if (mod == NULL) {
3749 Py_XDECREF(div);
3750 return -1;
3751 }
3752 *pmod = mod;
3753 }
3754 if (pdiv != NULL) {
3755 /* We only want to set `*pdiv` when `*pmod` is
3756 set successfully. */
3757 *pdiv = div;
3758 }
3759 return 0;
3760 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 if (long_divrem(v, w, &div, &mod) < 0)
3762 return -1;
3763 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3764 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3765 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 temp = (PyLongObject *) long_add(mod, w);
3767 Py_DECREF(mod);
3768 mod = temp;
3769 if (mod == NULL) {
3770 Py_DECREF(div);
3771 return -1;
3772 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003773 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3774 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 Py_DECREF(mod);
3776 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 return -1;
3778 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 Py_DECREF(div);
3780 div = temp;
3781 }
3782 if (pdiv != NULL)
3783 *pdiv = div;
3784 else
3785 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 if (pmod != NULL)
3788 *pmod = mod;
3789 else
3790 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003793}
3794
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003795static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003796long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003801
3802 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3803 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3804 }
3805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3807 div = NULL;
3808 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003809}
3810
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003811/* PyLong/PyLong -> float, with correctly rounded result. */
3812
3813#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3814#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3815
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003816static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003817long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 PyLongObject *a, *b, *x;
3820 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3821 digit mask, low;
3822 int inexact, negate, a_is_small, b_is_small;
3823 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 CHECK_BINOP(v, w);
3826 a = (PyLongObject *)v;
3827 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 /*
3830 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3833 1. choose a suitable integer 'shift'
3834 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3835 3. adjust x for correct rounding
3836 4. convert x to a double dx with the same value
3837 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003841 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3842 returns either 0.0 or -0.0, depending on the sign of b. For a and
3843 b both nonzero, ignore signs of a and b, and add the sign back in
3844 at the end. Now write a_bits and b_bits for the bit lengths of a
3845 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3846 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3851 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3852 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3853 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 1. The integer 'shift' is chosen so that x has the right number of
3858 bits for a double, plus two or three extra bits that will be used
3859 in the rounding decisions. Writing a_bits and b_bits for the
3860 number of significant bits in a and b respectively, a
3861 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 This is fine in the usual case, but if a/b is smaller than the
3866 smallest normal float then it can lead to double rounding on an
3867 IEEE 754 platform, giving incorrectly rounded results. So we
3868 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 2. The quantity x is computed by first shifting a (left -shift bits
3873 if shift <= 0, right shift bits if shift > 0) and then dividing by
3874 b. For both the shift and the division, we keep track of whether
3875 the result is inexact, in a flag 'inexact'; this information is
3876 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 With the choice of shift above, together with our assumption that
3879 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3880 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3883 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 For float representability, we need x/2**extra_bits <
3888 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3889 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 To round, we just modify the bottom digit of x in-place; this can
3894 end up giving a digit with value > PyLONG_MASK, but that's not a
3895 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 With the original choices for shift above, extra_bits will always
3898 be 2 or 3. Then rounding under the round-half-to-even rule, we
3899 round up iff the most significant of the extra bits is 1, and
3900 either: (a) the computation of x in step 2 had an inexact result,
3901 or (b) at least one other of the extra bits is 1, or (c) the least
3902 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 4. Conversion to a double is straightforward; all floating-point
3905 operations involved in the conversion are exact, so there's no
3906 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3909 The result will always be exactly representable as a double, except
3910 in the case that it overflows. To avoid dependence on the exact
3911 behaviour of ldexp on overflow, we check for overflow before
3912 applying ldexp. The result of ldexp is adjusted for sign before
3913 returning.
3914 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003917 a_size = Py_ABS(Py_SIZE(a));
3918 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3920 if (b_size == 0) {
3921 PyErr_SetString(PyExc_ZeroDivisionError,
3922 "division by zero");
3923 goto error;
3924 }
3925 if (a_size == 0)
3926 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 /* Fast path for a and b small (exactly representable in a double).
3929 Relies on floating-point division being correctly rounded; results
3930 may be subject to double rounding on x86 machines that operate with
3931 the x87 FPU set to 64-bit precision. */
3932 a_is_small = a_size <= MANT_DIG_DIGITS ||
3933 (a_size == MANT_DIG_DIGITS+1 &&
3934 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3935 b_is_small = b_size <= MANT_DIG_DIGITS ||
3936 (b_size == MANT_DIG_DIGITS+1 &&
3937 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3938 if (a_is_small && b_is_small) {
3939 double da, db;
3940 da = a->ob_digit[--a_size];
3941 while (a_size > 0)
3942 da = da * PyLong_BASE + a->ob_digit[--a_size];
3943 db = b->ob_digit[--b_size];
3944 while (b_size > 0)
3945 db = db * PyLong_BASE + b->ob_digit[--b_size];
3946 result = da / db;
3947 goto success;
3948 }
Tim Peterse2a60002001-09-04 06:17:36 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 /* Catch obvious cases of underflow and overflow */
3951 diff = a_size - b_size;
3952 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3953 /* Extreme overflow */
3954 goto overflow;
3955 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3956 /* Extreme underflow */
3957 goto underflow_or_zero;
3958 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01003959 diff = diff * PyLong_SHIFT + _Py_bit_length(a->ob_digit[a_size - 1]) -
3960 _Py_bit_length(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 /* Now diff = a_bits - b_bits. */
3962 if (diff > DBL_MAX_EXP)
3963 goto overflow;
3964 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3965 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003968 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 /* x = abs(a * 2**-shift) */
3973 if (shift <= 0) {
3974 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3975 digit rem;
3976 /* x = a << -shift */
3977 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3978 /* In practice, it's probably impossible to end up
3979 here. Both a and b would have to be enormous,
3980 using close to SIZE_T_MAX bytes of memory each. */
3981 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003982 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 goto error;
3984 }
3985 x = _PyLong_New(a_size + shift_digits + 1);
3986 if (x == NULL)
3987 goto error;
3988 for (i = 0; i < shift_digits; i++)
3989 x->ob_digit[i] = 0;
3990 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3991 a_size, -shift % PyLong_SHIFT);
3992 x->ob_digit[a_size + shift_digits] = rem;
3993 }
3994 else {
3995 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3996 digit rem;
3997 /* x = a >> shift */
3998 assert(a_size >= shift_digits);
3999 x = _PyLong_New(a_size - shift_digits);
4000 if (x == NULL)
4001 goto error;
4002 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4003 a_size - shift_digits, shift % PyLong_SHIFT);
4004 /* set inexact if any of the bits shifted out is nonzero */
4005 if (rem)
4006 inexact = 1;
4007 while (!inexact && shift_digits > 0)
4008 if (a->ob_digit[--shift_digits])
4009 inexact = 1;
4010 }
4011 long_normalize(x);
4012 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4015 reference to x, so it's safe to modify it in-place. */
4016 if (b_size == 1) {
4017 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4018 b->ob_digit[0]);
4019 long_normalize(x);
4020 if (rem)
4021 inexact = 1;
4022 }
4023 else {
4024 PyLongObject *div, *rem;
4025 div = x_divrem(x, b, &rem);
4026 Py_DECREF(x);
4027 x = div;
4028 if (x == NULL)
4029 goto error;
4030 if (Py_SIZE(rem))
4031 inexact = 1;
4032 Py_DECREF(rem);
4033 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004034 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004036 x_bits = (x_size-1)*PyLong_SHIFT+_Py_bit_length(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004039 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 /* Round by directly modifying the low digit of x. */
4043 mask = (digit)1 << (extra_bits - 1);
4044 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004045 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004047 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 /* Convert x to a double dx; the conversion is exact. */
4050 dx = x->ob_digit[--x_size];
4051 while (x_size > 0)
4052 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4053 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 /* Check whether ldexp result will overflow a double. */
4056 if (shift + x_bits >= DBL_MAX_EXP &&
4057 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4058 goto overflow;
4059 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004060
4061 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004063
4064 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004066
4067 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 PyErr_SetString(PyExc_OverflowError,
4069 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004070 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004072}
4073
4074static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004075long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 CHECK_BINOP(a, b);
4080
Yury Selivanove0b23092016-02-11 10:26:27 -05004081 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4082 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4083 }
4084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4086 mod = NULL;
4087 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004088}
4089
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004090static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004091long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 PyLongObject *div, *mod;
4094 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4099 return NULL;
4100 }
4101 z = PyTuple_New(2);
4102 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004103 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4104 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 }
4106 else {
4107 Py_DECREF(div);
4108 Py_DECREF(mod);
4109 }
4110 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004111}
4112
Mark Dickinsonc5299672019-06-02 10:24:06 +01004113
4114/* Compute an inverse to a modulo n, or raise ValueError if a is not
4115 invertible modulo n. Assumes n is positive. The inverse returned
4116 is whatever falls out of the extended Euclidean algorithm: it may
4117 be either positive or negative, but will be smaller than n in
4118 absolute value.
4119
4120 Pure Python equivalent for long_invmod:
4121
4122 def invmod(a, n):
4123 b, c = 1, 0
4124 while n:
4125 q, r = divmod(a, n)
4126 a, b, c, n = n, c, b - q*c, r
4127
4128 # at this point a is the gcd of the original inputs
4129 if a == 1:
4130 return b
4131 raise ValueError("Not invertible")
4132*/
4133
4134static PyLongObject *
4135long_invmod(PyLongObject *a, PyLongObject *n)
4136{
4137 PyLongObject *b, *c;
4138
4139 /* Should only ever be called for positive n */
4140 assert(Py_SIZE(n) > 0);
4141
4142 b = (PyLongObject *)PyLong_FromLong(1L);
4143 if (b == NULL) {
4144 return NULL;
4145 }
4146 c = (PyLongObject *)PyLong_FromLong(0L);
4147 if (c == NULL) {
4148 Py_DECREF(b);
4149 return NULL;
4150 }
4151 Py_INCREF(a);
4152 Py_INCREF(n);
4153
4154 /* references now owned: a, b, c, n */
4155 while (Py_SIZE(n) != 0) {
4156 PyLongObject *q, *r, *s, *t;
4157
4158 if (l_divmod(a, n, &q, &r) == -1) {
4159 goto Error;
4160 }
4161 Py_DECREF(a);
4162 a = n;
4163 n = r;
4164 t = (PyLongObject *)long_mul(q, c);
4165 Py_DECREF(q);
4166 if (t == NULL) {
4167 goto Error;
4168 }
4169 s = (PyLongObject *)long_sub(b, t);
4170 Py_DECREF(t);
4171 if (s == NULL) {
4172 goto Error;
4173 }
4174 Py_DECREF(b);
4175 b = c;
4176 c = s;
4177 }
4178 /* references now owned: a, b, c, n */
4179
4180 Py_DECREF(c);
4181 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004182 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004183 /* a != 1; we don't have an inverse. */
4184 Py_DECREF(a);
4185 Py_DECREF(b);
4186 PyErr_SetString(PyExc_ValueError,
4187 "base is not invertible for the given modulus");
4188 return NULL;
4189 }
4190 else {
4191 /* a == 1; b gives an inverse modulo n */
4192 Py_DECREF(a);
4193 return b;
4194 }
4195
4196 Error:
4197 Py_DECREF(a);
4198 Py_DECREF(b);
4199 Py_DECREF(c);
4200 Py_DECREF(n);
4201 return NULL;
4202}
4203
4204
Tim Peters47e52ee2004-08-30 02:44:38 +00004205/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004206static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004207long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4210 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 PyLongObject *z = NULL; /* accumulated result */
4213 Py_ssize_t i, j, k; /* counters */
4214 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 /* 5-ary values. If the exponent is large enough, table is
4217 * precomputed so that table[i] == a**i % c for i in range(32).
4218 */
4219 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4220 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 /* a, b, c = v, w, x */
4223 CHECK_BINOP(v, w);
4224 a = (PyLongObject*)v; Py_INCREF(a);
4225 b = (PyLongObject*)w; Py_INCREF(b);
4226 if (PyLong_Check(x)) {
4227 c = (PyLongObject *)x;
4228 Py_INCREF(x);
4229 }
4230 else if (x == Py_None)
4231 c = NULL;
4232 else {
4233 Py_DECREF(a);
4234 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004235 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 }
Tim Peters4c483c42001-09-05 06:24:58 +00004237
Mark Dickinsonc5299672019-06-02 10:24:06 +01004238 if (Py_SIZE(b) < 0 && c == NULL) {
4239 /* if exponent is negative and there's no modulus:
4240 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 that this calls float_pow() which converts its
4242 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004243 Py_DECREF(a);
4244 Py_DECREF(b);
4245 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 if (c) {
4249 /* if modulus == 0:
4250 raise ValueError() */
4251 if (Py_SIZE(c) == 0) {
4252 PyErr_SetString(PyExc_ValueError,
4253 "pow() 3rd argument cannot be 0");
4254 goto Error;
4255 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 /* if modulus < 0:
4258 negativeOutput = True
4259 modulus = -modulus */
4260 if (Py_SIZE(c) < 0) {
4261 negativeOutput = 1;
4262 temp = (PyLongObject *)_PyLong_Copy(c);
4263 if (temp == NULL)
4264 goto Error;
4265 Py_DECREF(c);
4266 c = temp;
4267 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004268 _PyLong_Negate(&c);
4269 if (c == NULL)
4270 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004273 /* if modulus == 1:
4274 return 0 */
4275 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4276 z = (PyLongObject *)PyLong_FromLong(0L);
4277 goto Done;
4278 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004279
Mark Dickinsonc5299672019-06-02 10:24:06 +01004280 /* if exponent is negative, negate the exponent and
4281 replace the base with a modular inverse */
4282 if (Py_SIZE(b) < 0) {
4283 temp = (PyLongObject *)_PyLong_Copy(b);
4284 if (temp == NULL)
4285 goto Error;
4286 Py_DECREF(b);
4287 b = temp;
4288 temp = NULL;
4289 _PyLong_Negate(&b);
4290 if (b == NULL)
4291 goto Error;
4292
4293 temp = long_invmod(a, c);
4294 if (temp == NULL)
4295 goto Error;
4296 Py_DECREF(a);
4297 a = temp;
4298 }
4299
Tim Peters81a93152013-10-05 16:53:52 -05004300 /* Reduce base by modulus in some cases:
4301 1. If base < 0. Forcing the base non-negative makes things easier.
4302 2. If base is obviously larger than the modulus. The "small
4303 exponent" case later can multiply directly by base repeatedly,
4304 while the "large exponent" case multiplies directly by base 31
4305 times. It can be unboundedly faster to multiply by
4306 base % modulus instead.
4307 We could _always_ do this reduction, but l_divmod() isn't cheap,
4308 so we only do it when it buys something. */
4309 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 if (l_divmod(a, c, NULL, &temp) < 0)
4311 goto Error;
4312 Py_DECREF(a);
4313 a = temp;
4314 temp = NULL;
4315 }
4316 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 /* At this point a, b, and c are guaranteed non-negative UNLESS
4319 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 z = (PyLongObject *)PyLong_FromLong(1L);
4322 if (z == NULL)
4323 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 /* Perform a modular reduction, X = X % c, but leave X alone if c
4326 * is NULL.
4327 */
4328#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004329 do { \
4330 if (c != NULL) { \
4331 if (l_divmod(X, c, NULL, &temp) < 0) \
4332 goto Error; \
4333 Py_XDECREF(X); \
4334 X = temp; \
4335 temp = NULL; \
4336 } \
4337 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 /* Multiply two values, then reduce the result:
4340 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004341#define MULT(X, Y, result) \
4342 do { \
4343 temp = (PyLongObject *)long_mul(X, Y); \
4344 if (temp == NULL) \
4345 goto Error; \
4346 Py_XDECREF(result); \
4347 result = temp; \
4348 temp = NULL; \
4349 REDUCE(result); \
4350 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4353 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4354 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4355 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4356 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004359 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004361 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 }
4363 }
4364 }
4365 else {
4366 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4367 Py_INCREF(z); /* still holds 1L */
4368 table[0] = z;
4369 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004370 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4373 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4376 const int index = (bi >> j) & 0x1f;
4377 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004378 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004380 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 }
4382 }
4383 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 if (negativeOutput && (Py_SIZE(z) != 0)) {
4386 temp = (PyLongObject *)long_sub(z, c);
4387 if (temp == NULL)
4388 goto Error;
4389 Py_DECREF(z);
4390 z = temp;
4391 temp = NULL;
4392 }
4393 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004394
Mark Dickinson22b20182010-05-10 21:27:53 +00004395 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004396 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004398 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4400 for (i = 0; i < 32; ++i)
4401 Py_XDECREF(table[i]);
4402 }
4403 Py_DECREF(a);
4404 Py_DECREF(b);
4405 Py_XDECREF(c);
4406 Py_XDECREF(temp);
4407 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004408}
4409
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004410static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004411long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 /* Implement ~x as -(x+1) */
4414 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004415 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004417 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 if (x == NULL)
4419 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004420 _PyLong_Negate(&x);
4421 /* No need for maybe_small_long here, since any small
4422 longs will have been caught in the Py_SIZE <= 1 fast path. */
4423 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004424}
4425
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004426static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004427long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004430 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 return PyLong_FromLong(-MEDIUM_VALUE(v));
4432 z = (PyLongObject *)_PyLong_Copy(v);
4433 if (z != NULL)
4434 Py_SIZE(z) = -(Py_SIZE(v));
4435 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004436}
4437
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004438static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004439long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 if (Py_SIZE(v) < 0)
4442 return long_neg(v);
4443 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004444 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004445}
4446
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004447static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004448long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004451}
4452
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004453/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4454static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004455divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004456{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004457 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004458 assert(Py_SIZE(shiftby) >= 0);
4459 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4460 if (lshiftby >= 0) {
4461 *wordshift = lshiftby / PyLong_SHIFT;
4462 *remshift = lshiftby % PyLong_SHIFT;
4463 return 0;
4464 }
4465 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4466 be that PyLong_AsSsize_t raised an OverflowError. */
4467 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4468 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004469 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004470 if (wordshift_obj == NULL) {
4471 return -1;
4472 }
4473 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4474 Py_DECREF(wordshift_obj);
4475 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4476 return 0;
4477 }
4478 PyErr_Clear();
4479 /* Clip the value. With such large wordshift the right shift
4480 returns 0 and the left shift raises an error in _PyLong_New(). */
4481 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4482 *remshift = 0;
4483 return 0;
4484}
4485
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004486static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004487long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004490 Py_ssize_t newsize, hishift, i, j;
4491 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 if (Py_SIZE(a) < 0) {
4494 /* Right shifting negative numbers is harder */
4495 PyLongObject *a1, *a2;
4496 a1 = (PyLongObject *) long_invert(a);
4497 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004498 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004499 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 Py_DECREF(a1);
4501 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004502 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 z = (PyLongObject *) long_invert(a2);
4504 Py_DECREF(a2);
4505 }
4506 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004507 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 if (newsize <= 0)
4509 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004510 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 lomask = ((digit)1 << hishift) - 1;
4512 himask = PyLong_MASK ^ lomask;
4513 z = _PyLong_New(newsize);
4514 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004515 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004517 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004519 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004521 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004523 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004524}
4525
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004526static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004527long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004528{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004529 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004530 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004533
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004534 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004536 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004538 if (Py_SIZE(a) == 0) {
4539 return PyLong_FromLong(0);
4540 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004541 if (divmod_shift(b, &wordshift, &remshift) < 0)
4542 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004543 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4544}
4545
4546/* Return a >> shiftby. */
4547PyObject *
4548_PyLong_Rshift(PyObject *a, size_t shiftby)
4549{
4550 Py_ssize_t wordshift;
4551 digit remshift;
4552
4553 assert(PyLong_Check(a));
4554 if (Py_SIZE(a) == 0) {
4555 return PyLong_FromLong(0);
4556 }
4557 wordshift = shiftby / PyLong_SHIFT;
4558 remshift = shiftby % PyLong_SHIFT;
4559 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4560}
4561
4562static PyObject *
4563long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4564{
4565 /* This version due to Tim Peters */
4566 PyLongObject *z = NULL;
4567 Py_ssize_t oldsize, newsize, i, j;
4568 twodigits accum;
4569
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004570 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 newsize = oldsize + wordshift;
4572 if (remshift)
4573 ++newsize;
4574 z = _PyLong_New(newsize);
4575 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004576 return NULL;
4577 if (Py_SIZE(a) < 0) {
4578 assert(Py_REFCNT(z) == 1);
4579 Py_SIZE(z) = -Py_SIZE(z);
4580 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 for (i = 0; i < wordshift; i++)
4582 z->ob_digit[i] = 0;
4583 accum = 0;
4584 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4585 accum |= (twodigits)a->ob_digit[j] << remshift;
4586 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4587 accum >>= PyLong_SHIFT;
4588 }
4589 if (remshift)
4590 z->ob_digit[newsize-1] = (digit)accum;
4591 else
4592 assert(!accum);
4593 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004595}
4596
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004597static PyObject *
4598long_lshift(PyObject *a, PyObject *b)
4599{
4600 Py_ssize_t wordshift;
4601 digit remshift;
4602
4603 CHECK_BINOP(a, b);
4604
4605 if (Py_SIZE(b) < 0) {
4606 PyErr_SetString(PyExc_ValueError, "negative shift count");
4607 return NULL;
4608 }
4609 if (Py_SIZE(a) == 0) {
4610 return PyLong_FromLong(0);
4611 }
4612 if (divmod_shift(b, &wordshift, &remshift) < 0)
4613 return NULL;
4614 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4615}
4616
4617/* Return a << shiftby. */
4618PyObject *
4619_PyLong_Lshift(PyObject *a, size_t shiftby)
4620{
4621 Py_ssize_t wordshift;
4622 digit remshift;
4623
4624 assert(PyLong_Check(a));
4625 if (Py_SIZE(a) == 0) {
4626 return PyLong_FromLong(0);
4627 }
4628 wordshift = shiftby / PyLong_SHIFT;
4629 remshift = shiftby % PyLong_SHIFT;
4630 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4631}
4632
Mark Dickinson27a87a22009-10-25 20:43:34 +00004633/* Compute two's complement of digit vector a[0:m], writing result to
4634 z[0:m]. The digit vector a need not be normalized, but should not
4635 be entirely zero. a and z may point to the same digit vector. */
4636
4637static void
4638v_complement(digit *z, digit *a, Py_ssize_t m)
4639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 Py_ssize_t i;
4641 digit carry = 1;
4642 for (i = 0; i < m; ++i) {
4643 carry += a[i] ^ PyLong_MASK;
4644 z[i] = carry & PyLong_MASK;
4645 carry >>= PyLong_SHIFT;
4646 }
4647 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004648}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004649
4650/* Bitwise and/xor/or operations */
4651
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004652static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004653long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004654 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004655 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 int nega, negb, negz;
4658 Py_ssize_t size_a, size_b, size_z, i;
4659 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 /* Bitwise operations for negative numbers operate as though
4662 on a two's complement representation. So convert arguments
4663 from sign-magnitude to two's complement, and convert the
4664 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004667 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 nega = Py_SIZE(a) < 0;
4669 if (nega) {
4670 z = _PyLong_New(size_a);
4671 if (z == NULL)
4672 return NULL;
4673 v_complement(z->ob_digit, a->ob_digit, size_a);
4674 a = z;
4675 }
4676 else
4677 /* Keep reference count consistent. */
4678 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004681 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 negb = Py_SIZE(b) < 0;
4683 if (negb) {
4684 z = _PyLong_New(size_b);
4685 if (z == NULL) {
4686 Py_DECREF(a);
4687 return NULL;
4688 }
4689 v_complement(z->ob_digit, b->ob_digit, size_b);
4690 b = z;
4691 }
4692 else
4693 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 /* Swap a and b if necessary to ensure size_a >= size_b. */
4696 if (size_a < size_b) {
4697 z = a; a = b; b = z;
4698 size_z = size_a; size_a = size_b; size_b = size_z;
4699 negz = nega; nega = negb; negb = negz;
4700 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 /* JRH: The original logic here was to allocate the result value (z)
4703 as the longer of the two operands. However, there are some cases
4704 where the result is guaranteed to be shorter than that: AND of two
4705 positives, OR of two negatives: use the shorter number. AND with
4706 mixed signs: use the positive number. OR with mixed signs: use the
4707 negative number.
4708 */
4709 switch (op) {
4710 case '^':
4711 negz = nega ^ negb;
4712 size_z = size_a;
4713 break;
4714 case '&':
4715 negz = nega & negb;
4716 size_z = negb ? size_a : size_b;
4717 break;
4718 case '|':
4719 negz = nega | negb;
4720 size_z = negb ? size_b : size_a;
4721 break;
4722 default:
stratakisa10d4262019-03-18 18:59:20 +01004723 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 /* We allow an extra digit if z is negative, to make sure that
4727 the final two's complement of z doesn't overflow. */
4728 z = _PyLong_New(size_z + negz);
4729 if (z == NULL) {
4730 Py_DECREF(a);
4731 Py_DECREF(b);
4732 return NULL;
4733 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 /* Compute digits for overlap of a and b. */
4736 switch(op) {
4737 case '&':
4738 for (i = 0; i < size_b; ++i)
4739 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4740 break;
4741 case '|':
4742 for (i = 0; i < size_b; ++i)
4743 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4744 break;
4745 case '^':
4746 for (i = 0; i < size_b; ++i)
4747 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4748 break;
4749 default:
stratakisa10d4262019-03-18 18:59:20 +01004750 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004753 /* Copy any remaining digits of a, inverting if necessary. */
4754 if (op == '^' && negb)
4755 for (; i < size_z; ++i)
4756 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4757 else if (i < size_z)
4758 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4759 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004761 /* Complement result if negative. */
4762 if (negz) {
4763 Py_SIZE(z) = -(Py_SIZE(z));
4764 z->ob_digit[size_z] = PyLong_MASK;
4765 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4766 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 Py_DECREF(a);
4769 Py_DECREF(b);
4770 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004771}
4772
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004773static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004774long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 PyObject *c;
4777 CHECK_BINOP(a, b);
4778 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4779 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004780}
4781
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004782static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004783long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 PyObject *c;
4786 CHECK_BINOP(a, b);
4787 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4788 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004789}
4790
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004791static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004792long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004794 PyObject *c;
4795 CHECK_BINOP(a, b);
4796 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4797 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004798}
4799
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004800static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004801long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 if (PyLong_CheckExact(v))
4804 Py_INCREF(v);
4805 else
4806 v = _PyLong_Copy((PyLongObject *)v);
4807 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004808}
4809
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004810PyObject *
4811_PyLong_GCD(PyObject *aarg, PyObject *barg)
4812{
4813 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4814 stwodigits x, y, q, s, t, c_carry, d_carry;
4815 stwodigits A, B, C, D, T;
4816 int nbits, k;
4817 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4818 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4819
4820 a = (PyLongObject *)aarg;
4821 b = (PyLongObject *)barg;
4822 size_a = Py_SIZE(a);
4823 size_b = Py_SIZE(b);
4824 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4825 Py_INCREF(a);
4826 Py_INCREF(b);
4827 goto simple;
4828 }
4829
4830 /* Initial reduction: make sure that 0 <= b <= a. */
4831 a = (PyLongObject *)long_abs(a);
4832 if (a == NULL)
4833 return NULL;
4834 b = (PyLongObject *)long_abs(b);
4835 if (b == NULL) {
4836 Py_DECREF(a);
4837 return NULL;
4838 }
4839 if (long_compare(a, b) < 0) {
4840 r = a;
4841 a = b;
4842 b = r;
4843 }
4844 /* We now own references to a and b */
4845
4846 alloc_a = Py_SIZE(a);
4847 alloc_b = Py_SIZE(b);
4848 /* reduce until a fits into 2 digits */
4849 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004850 nbits = _Py_bit_length(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004851 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4852 corresponding bits of b into y */
4853 size_b = Py_SIZE(b);
4854 assert(size_b <= size_a);
4855 if (size_b == 0) {
4856 if (size_a < alloc_a) {
4857 r = (PyLongObject *)_PyLong_Copy(a);
4858 Py_DECREF(a);
4859 }
4860 else
4861 r = a;
4862 Py_DECREF(b);
4863 Py_XDECREF(c);
4864 Py_XDECREF(d);
4865 return (PyObject *)r;
4866 }
4867 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4868 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4869 (a->ob_digit[size_a-3] >> nbits));
4870
4871 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4872 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4873 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4874
4875 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4876 larger than PyLong_MASK during the algorithm. */
4877 A = 1; B = 0; C = 0; D = 1;
4878 for (k=0;; k++) {
4879 if (y-C == 0)
4880 break;
4881 q = (x+(A-1))/(y-C);
4882 s = B+q*D;
4883 t = x-q*y;
4884 if (s > t)
4885 break;
4886 x = y; y = t;
4887 t = A+q*C; A = D; B = C; C = s; D = t;
4888 }
4889
4890 if (k == 0) {
4891 /* no progress; do a Euclidean step */
4892 if (l_divmod(a, b, NULL, &r) < 0)
4893 goto error;
4894 Py_DECREF(a);
4895 a = b;
4896 b = r;
4897 alloc_a = alloc_b;
4898 alloc_b = Py_SIZE(b);
4899 continue;
4900 }
4901
4902 /*
4903 a, b = A*b-B*a, D*a-C*b if k is odd
4904 a, b = A*a-B*b, D*b-C*a if k is even
4905 */
4906 if (k&1) {
4907 T = -A; A = -B; B = T;
4908 T = -C; C = -D; D = T;
4909 }
4910 if (c != NULL)
4911 Py_SIZE(c) = size_a;
4912 else if (Py_REFCNT(a) == 1) {
4913 Py_INCREF(a);
4914 c = a;
4915 }
4916 else {
4917 alloc_a = size_a;
4918 c = _PyLong_New(size_a);
4919 if (c == NULL)
4920 goto error;
4921 }
4922
4923 if (d != NULL)
4924 Py_SIZE(d) = size_a;
4925 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4926 Py_INCREF(b);
4927 d = b;
4928 Py_SIZE(d) = size_a;
4929 }
4930 else {
4931 alloc_b = size_a;
4932 d = _PyLong_New(size_a);
4933 if (d == NULL)
4934 goto error;
4935 }
4936 a_end = a->ob_digit + size_a;
4937 b_end = b->ob_digit + size_b;
4938
4939 /* compute new a and new b in parallel */
4940 a_digit = a->ob_digit;
4941 b_digit = b->ob_digit;
4942 c_digit = c->ob_digit;
4943 d_digit = d->ob_digit;
4944 c_carry = 0;
4945 d_carry = 0;
4946 while (b_digit < b_end) {
4947 c_carry += (A * *a_digit) - (B * *b_digit);
4948 d_carry += (D * *b_digit++) - (C * *a_digit++);
4949 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4950 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4951 c_carry >>= PyLong_SHIFT;
4952 d_carry >>= PyLong_SHIFT;
4953 }
4954 while (a_digit < a_end) {
4955 c_carry += A * *a_digit;
4956 d_carry -= C * *a_digit++;
4957 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4958 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4959 c_carry >>= PyLong_SHIFT;
4960 d_carry >>= PyLong_SHIFT;
4961 }
4962 assert(c_carry == 0);
4963 assert(d_carry == 0);
4964
4965 Py_INCREF(c);
4966 Py_INCREF(d);
4967 Py_DECREF(a);
4968 Py_DECREF(b);
4969 a = long_normalize(c);
4970 b = long_normalize(d);
4971 }
4972 Py_XDECREF(c);
4973 Py_XDECREF(d);
4974
4975simple:
4976 assert(Py_REFCNT(a) > 0);
4977 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004978/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4979 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4980#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004981 /* a fits into a long, so b must too */
4982 x = PyLong_AsLong((PyObject *)a);
4983 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004984#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004985 x = PyLong_AsLongLong((PyObject *)a);
4986 y = PyLong_AsLongLong((PyObject *)b);
4987#else
4988# error "_PyLong_GCD"
4989#endif
4990 x = Py_ABS(x);
4991 y = Py_ABS(y);
4992 Py_DECREF(a);
4993 Py_DECREF(b);
4994
4995 /* usual Euclidean algorithm for longs */
4996 while (y != 0) {
4997 t = y;
4998 y = x % y;
4999 x = t;
5000 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005001#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005002 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05005003#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005004 return PyLong_FromLongLong(x);
5005#else
5006# error "_PyLong_GCD"
5007#endif
5008
5009error:
5010 Py_DECREF(a);
5011 Py_DECREF(b);
5012 Py_XDECREF(c);
5013 Py_XDECREF(d);
5014 return NULL;
5015}
5016
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005017static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005018long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 double result;
5021 result = PyLong_AsDouble(v);
5022 if (result == -1.0 && PyErr_Occurred())
5023 return NULL;
5024 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005025}
5026
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005027static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005028long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5029
5030/*[clinic input]
5031@classmethod
5032int.__new__ as long_new
5033 x: object(c_default="NULL") = 0
5034 /
5035 base as obase: object(c_default="NULL") = 10
5036[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005037
Tim Peters6d6c1a32001-08-02 04:15:00 +00005038static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005039long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5040/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005041{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005042 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005045 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005046 if (x == NULL) {
5047 if (obase != NULL) {
5048 PyErr_SetString(PyExc_TypeError,
5049 "int() missing string argument");
5050 return NULL;
5051 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005053 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005054 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005056
Gregory P. Smitha689e522012-12-25 22:38:32 -08005057 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005058 if (base == -1 && PyErr_Occurred())
5059 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005060 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005061 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305062 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005063 return NULL;
5064 }
5065
5066 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005067 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 if (PyByteArray_Check(x))
5071 string = PyByteArray_AS_STRING(x);
5072 else
5073 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005074 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 }
5076 else {
5077 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005078 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 return NULL;
5080 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005081}
5082
Serhiy Storchaka95949422013-08-27 19:40:23 +03005083/* Wimpy, slow approach to tp_new calls for subtypes of int:
5084 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005085 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005086 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005087*/
5088static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005089long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 PyLongObject *tmp, *newobj;
5092 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005095 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 if (tmp == NULL)
5097 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005098 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 n = Py_SIZE(tmp);
5100 if (n < 0)
5101 n = -n;
5102 newobj = (PyLongObject *)type->tp_alloc(type, n);
5103 if (newobj == NULL) {
5104 Py_DECREF(tmp);
5105 return NULL;
5106 }
5107 assert(PyLong_Check(newobj));
5108 Py_SIZE(newobj) = Py_SIZE(tmp);
5109 for (i = 0; i < n; i++)
5110 newobj->ob_digit[i] = tmp->ob_digit[i];
5111 Py_DECREF(tmp);
5112 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005113}
5114
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005115/*[clinic input]
5116int.__getnewargs__
5117[clinic start generated code]*/
5118
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005119static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005120int___getnewargs___impl(PyObject *self)
5121/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005122{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005123 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005124}
5125
Guido van Rossumb43daf72007-08-01 18:08:08 +00005126static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005127long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005130}
5131
5132static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005133long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005136}
5137
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005138/*[clinic input]
5139int.__format__
5140
5141 format_spec: unicode
5142 /
5143[clinic start generated code]*/
5144
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005145static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005146int___format___impl(PyObject *self, PyObject *format_spec)
5147/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005148{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005149 _PyUnicodeWriter writer;
5150 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005151
Victor Stinner8f674cc2013-04-17 23:02:17 +02005152 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005153 ret = _PyLong_FormatAdvancedWriter(
5154 &writer,
5155 self,
5156 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5157 if (ret == -1) {
5158 _PyUnicodeWriter_Dealloc(&writer);
5159 return NULL;
5160 }
5161 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005162}
5163
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005164/* Return a pair (q, r) such that a = b * q + r, and
5165 abs(r) <= abs(b)/2, with equality possible only if q is even.
5166 In other words, q == a / b, rounded to the nearest integer using
5167 round-half-to-even. */
5168
5169PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005170_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005171{
5172 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005173 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005174 int quo_is_odd, quo_is_neg;
5175 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005176
5177 /* Equivalent Python code:
5178
5179 def divmod_near(a, b):
5180 q, r = divmod(a, b)
5181 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5182 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5183 # positive, 2 * r < b if b negative.
5184 greater_than_half = 2*r > b if b > 0 else 2*r < b
5185 exactly_half = 2*r == b
5186 if greater_than_half or exactly_half and q % 2 == 1:
5187 q += 1
5188 r -= b
5189 return q, r
5190
5191 */
5192 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5193 PyErr_SetString(PyExc_TypeError,
5194 "non-integer arguments in division");
5195 return NULL;
5196 }
5197
5198 /* Do a and b have different signs? If so, quotient is negative. */
5199 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5200
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005201 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5202 goto error;
5203
5204 /* compare twice the remainder with the divisor, to see
5205 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005206 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005207 if (twice_rem == NULL)
5208 goto error;
5209 if (quo_is_neg) {
5210 temp = long_neg((PyLongObject*)twice_rem);
5211 Py_DECREF(twice_rem);
5212 twice_rem = temp;
5213 if (twice_rem == NULL)
5214 goto error;
5215 }
5216 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5217 Py_DECREF(twice_rem);
5218
5219 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5220 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5221 /* fix up quotient */
5222 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005223 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005224 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005225 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005226 Py_DECREF(quo);
5227 quo = (PyLongObject *)temp;
5228 if (quo == NULL)
5229 goto error;
5230 /* and remainder */
5231 if (quo_is_neg)
5232 temp = long_add(rem, (PyLongObject *)b);
5233 else
5234 temp = long_sub(rem, (PyLongObject *)b);
5235 Py_DECREF(rem);
5236 rem = (PyLongObject *)temp;
5237 if (rem == NULL)
5238 goto error;
5239 }
5240
5241 result = PyTuple_New(2);
5242 if (result == NULL)
5243 goto error;
5244
5245 /* PyTuple_SET_ITEM steals references */
5246 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5247 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005248 return result;
5249
5250 error:
5251 Py_XDECREF(quo);
5252 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005253 return NULL;
5254}
5255
Eric Smith8c663262007-08-25 02:26:07 +00005256static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005257long_round(PyObject *self, PyObject *args)
5258{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005259 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005260
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005261 /* To round an integer m to the nearest 10**n (n positive), we make use of
5262 * the divmod_near operation, defined by:
5263 *
5264 * divmod_near(a, b) = (q, r)
5265 *
5266 * where q is the nearest integer to the quotient a / b (the
5267 * nearest even integer in the case of a tie) and r == a - q * b.
5268 * Hence q * b = a - r is the nearest multiple of b to a,
5269 * preferring even multiples in the case of a tie.
5270 *
5271 * So the nearest multiple of 10**n to m is:
5272 *
5273 * m - divmod_near(m, 10**n)[1].
5274 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5276 return NULL;
5277 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005278 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005279
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005280 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 if (ndigits == NULL)
5282 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005283
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005284 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 if (Py_SIZE(ndigits) >= 0) {
5286 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005287 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005289
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005290 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5291 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005293 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005295 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005296
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005297 result = PyLong_FromLong(10L);
5298 if (result == NULL) {
5299 Py_DECREF(ndigits);
5300 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005302
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005303 temp = long_pow(result, ndigits, Py_None);
5304 Py_DECREF(ndigits);
5305 Py_DECREF(result);
5306 result = temp;
5307 if (result == NULL)
5308 return NULL;
5309
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005310 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005311 Py_DECREF(result);
5312 result = temp;
5313 if (result == NULL)
5314 return NULL;
5315
5316 temp = long_sub((PyLongObject *)self,
5317 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5318 Py_DECREF(result);
5319 result = temp;
5320
5321 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005322}
5323
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005324/*[clinic input]
5325int.__sizeof__ -> Py_ssize_t
5326
5327Returns size in memory, in bytes.
5328[clinic start generated code]*/
5329
5330static Py_ssize_t
5331int___sizeof___impl(PyObject *self)
5332/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005335
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005336 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5337 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005338}
5339
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005340/*[clinic input]
5341int.bit_length
5342
5343Number of bits necessary to represent self in binary.
5344
5345>>> bin(37)
5346'0b100101'
5347>>> (37).bit_length()
53486
5349[clinic start generated code]*/
5350
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005351static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005352int_bit_length_impl(PyObject *self)
5353/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005356 Py_ssize_t ndigits;
5357 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005359
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005360 assert(self != NULL);
5361 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005362
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005363 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 if (ndigits == 0)
5365 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005366
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005367 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekasc5b79002020-01-16 15:09:19 +01005368 msd_bits = _Py_bit_length(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5371 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 /* expression above may overflow; use Python integers instead */
5374 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5375 if (result == NULL)
5376 return NULL;
5377 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5378 if (x == NULL)
5379 goto error;
5380 y = (PyLongObject *)long_mul(result, x);
5381 Py_DECREF(x);
5382 if (y == NULL)
5383 goto error;
5384 Py_DECREF(result);
5385 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5388 if (x == NULL)
5389 goto error;
5390 y = (PyLongObject *)long_add(result, x);
5391 Py_DECREF(x);
5392 if (y == NULL)
5393 goto error;
5394 Py_DECREF(result);
5395 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005398
Mark Dickinson22b20182010-05-10 21:27:53 +00005399 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 Py_DECREF(result);
5401 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005402}
5403
Christian Heimes53876d92008-04-19 00:31:39 +00005404
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005405/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005406int.as_integer_ratio
5407
5408Return integer ratio.
5409
5410Return a pair of integers, whose ratio is exactly equal to the original int
5411and with a positive denominator.
5412
5413>>> (10).as_integer_ratio()
5414(10, 1)
5415>>> (-10).as_integer_ratio()
5416(-10, 1)
5417>>> (0).as_integer_ratio()
5418(0, 1)
5419[clinic start generated code]*/
5420
5421static PyObject *
5422int_as_integer_ratio_impl(PyObject *self)
5423/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5424{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005425 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005426 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005427 if (numerator == NULL) {
5428 return NULL;
5429 }
5430 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5431 Py_DECREF(numerator);
5432 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005433}
5434
5435/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005436int.to_bytes
5437
5438 length: Py_ssize_t
5439 Length of bytes object to use. An OverflowError is raised if the
5440 integer is not representable with the given number of bytes.
5441 byteorder: unicode
5442 The byte order used to represent the integer. If byteorder is 'big',
5443 the most significant byte is at the beginning of the byte array. If
5444 byteorder is 'little', the most significant byte is at the end of the
5445 byte array. To request the native byte order of the host system, use
5446 `sys.byteorder' as the byte order value.
5447 *
5448 signed as is_signed: bool = False
5449 Determines whether two's complement is used to represent the integer.
5450 If signed is False and a negative integer is given, an OverflowError
5451 is raised.
5452
5453Return an array of bytes representing an integer.
5454[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005455
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005456static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005457int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5458 int is_signed)
5459/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005463
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005464 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005466 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 little_endian = 0;
5468 else {
5469 PyErr_SetString(PyExc_ValueError,
5470 "byteorder must be either 'little' or 'big'");
5471 return NULL;
5472 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005474 if (length < 0) {
5475 PyErr_SetString(PyExc_ValueError,
5476 "length argument must be non-negative");
5477 return NULL;
5478 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 bytes = PyBytes_FromStringAndSize(NULL, length);
5481 if (bytes == NULL)
5482 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005483
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005484 if (_PyLong_AsByteArray((PyLongObject *)self,
5485 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005486 length, little_endian, is_signed) < 0) {
5487 Py_DECREF(bytes);
5488 return NULL;
5489 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005492}
5493
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005494/*[clinic input]
5495@classmethod
5496int.from_bytes
5497
5498 bytes as bytes_obj: object
5499 Holds the array of bytes to convert. The argument must either
5500 support the buffer protocol or be an iterable object producing bytes.
5501 Bytes and bytearray are examples of built-in objects that support the
5502 buffer protocol.
5503 byteorder: unicode
5504 The byte order used to represent the integer. If byteorder is 'big',
5505 the most significant byte is at the beginning of the byte array. If
5506 byteorder is 'little', the most significant byte is at the end of the
5507 byte array. To request the native byte order of the host system, use
5508 `sys.byteorder' as the byte order value.
5509 *
5510 signed as is_signed: bool = False
5511 Indicates whether two's complement is used to represent the integer.
5512
5513Return the integer represented by the given array of bytes.
5514[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005515
5516static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005517int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5518 PyObject *byteorder, int is_signed)
5519/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005522 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005523
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005524 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005526 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 little_endian = 0;
5528 else {
5529 PyErr_SetString(PyExc_ValueError,
5530 "byteorder must be either 'little' or 'big'");
5531 return NULL;
5532 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005533
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005534 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 if (bytes == NULL)
5536 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 long_obj = _PyLong_FromByteArray(
5539 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5540 little_endian, is_signed);
5541 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005542
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005543 if (long_obj != NULL && type != &PyLong_Type) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02005544 Py_SETREF(long_obj, _PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005548}
5549
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005550static PyObject *
5551long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5552{
5553 return long_long(self);
5554}
5555
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005556static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005557 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005559 INT_BIT_LENGTH_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005560 INT_TO_BYTES_METHODDEF
5561 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005562 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005563 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005565 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005567 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 "Ceiling of an Integral returns itself."},
5569 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5570 "Rounding an Integral returns itself.\n"
5571 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005572 INT___GETNEWARGS___METHODDEF
5573 INT___FORMAT___METHODDEF
5574 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005576};
5577
Guido van Rossumb43daf72007-08-01 18:08:08 +00005578static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005579 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005580 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005581 "the real part of a complex number",
5582 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005583 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005584 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005585 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005586 NULL},
5587 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005588 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005589 "the numerator of a rational number in lowest terms",
5590 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005591 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005592 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005593 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005594 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005595 {NULL} /* Sentinel */
5596};
5597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005598PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005599"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005600int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005601\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005602Convert a number or string to an integer, or return 0 if no arguments\n\
5603are given. If x is a number, return x.__int__(). For floating point\n\
5604numbers, this truncates towards zero.\n\
5605\n\
5606If x is not a number or if base is given, then x must be a string,\n\
5607bytes, or bytearray instance representing an integer literal in the\n\
5608given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5609by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5610Base 0 means to interpret the base from the string as an integer literal.\n\
5611>>> int('0b100', base=0)\n\
56124");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005613
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005614static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005615 (binaryfunc)long_add, /*nb_add*/
5616 (binaryfunc)long_sub, /*nb_subtract*/
5617 (binaryfunc)long_mul, /*nb_multiply*/
5618 long_mod, /*nb_remainder*/
5619 long_divmod, /*nb_divmod*/
5620 long_pow, /*nb_power*/
5621 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005622 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005623 (unaryfunc)long_abs, /*tp_absolute*/
5624 (inquiry)long_bool, /*tp_bool*/
5625 (unaryfunc)long_invert, /*nb_invert*/
5626 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005627 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005628 long_and, /*nb_and*/
5629 long_xor, /*nb_xor*/
5630 long_or, /*nb_or*/
5631 long_long, /*nb_int*/
5632 0, /*nb_reserved*/
5633 long_float, /*nb_float*/
5634 0, /* nb_inplace_add */
5635 0, /* nb_inplace_subtract */
5636 0, /* nb_inplace_multiply */
5637 0, /* nb_inplace_remainder */
5638 0, /* nb_inplace_power */
5639 0, /* nb_inplace_lshift */
5640 0, /* nb_inplace_rshift */
5641 0, /* nb_inplace_and */
5642 0, /* nb_inplace_xor */
5643 0, /* nb_inplace_or */
5644 long_div, /* nb_floor_divide */
5645 long_true_divide, /* nb_true_divide */
5646 0, /* nb_inplace_floor_divide */
5647 0, /* nb_inplace_true_divide */
5648 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005649};
5650
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005651PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5653 "int", /* tp_name */
5654 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5655 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005656 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005657 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 0, /* tp_getattr */
5659 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005660 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005661 long_to_decimal_string, /* tp_repr */
5662 &long_as_number, /* tp_as_number */
5663 0, /* tp_as_sequence */
5664 0, /* tp_as_mapping */
5665 (hashfunc)long_hash, /* tp_hash */
5666 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005667 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 PyObject_GenericGetAttr, /* tp_getattro */
5669 0, /* tp_setattro */
5670 0, /* tp_as_buffer */
5671 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5672 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5673 long_doc, /* tp_doc */
5674 0, /* tp_traverse */
5675 0, /* tp_clear */
5676 long_richcompare, /* tp_richcompare */
5677 0, /* tp_weaklistoffset */
5678 0, /* tp_iter */
5679 0, /* tp_iternext */
5680 long_methods, /* tp_methods */
5681 0, /* tp_members */
5682 long_getset, /* tp_getset */
5683 0, /* tp_base */
5684 0, /* tp_dict */
5685 0, /* tp_descr_get */
5686 0, /* tp_descr_set */
5687 0, /* tp_dictoffset */
5688 0, /* tp_init */
5689 0, /* tp_alloc */
5690 long_new, /* tp_new */
5691 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005692};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005693
Mark Dickinsonbd792642009-03-18 20:06:12 +00005694static PyTypeObject Int_InfoType;
5695
5696PyDoc_STRVAR(int_info__doc__,
5697"sys.int_info\n\
5698\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005699A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005700internal representation of integers. The attributes are read only.");
5701
5702static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005703 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005704 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005706};
5707
5708static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 "sys.int_info", /* name */
5710 int_info__doc__, /* doc */
5711 int_info_fields, /* fields */
5712 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005713};
5714
5715PyObject *
5716PyLong_GetInfo(void)
5717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 PyObject* int_info;
5719 int field = 0;
5720 int_info = PyStructSequence_New(&Int_InfoType);
5721 if (int_info == NULL)
5722 return NULL;
5723 PyStructSequence_SET_ITEM(int_info, field++,
5724 PyLong_FromLong(PyLong_SHIFT));
5725 PyStructSequence_SET_ITEM(int_info, field++,
5726 PyLong_FromLong(sizeof(digit)));
5727 if (PyErr_Occurred()) {
5728 Py_CLEAR(int_info);
5729 return NULL;
5730 }
5731 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005732}
5733
Guido van Rossumddefaf32007-01-14 03:31:43 +00005734int
Victor Stinner630c8df2019-12-17 13:02:18 +01005735_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005736{
5737#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005738 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5739 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5740 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005741
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005742 PyLongObject *v = _PyLong_New(1);
5743 if (!v) {
5744 return -1;
5745 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005747 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005748 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005749
Victor Stinner630c8df2019-12-17 13:02:18 +01005750 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005751 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005752#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005753
Victor Stinner630c8df2019-12-17 13:02:18 +01005754 if (_Py_IsMainInterpreter(tstate)) {
5755 _PyLong_Zero = PyLong_FromLong(0);
5756 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005757 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005758 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005759
5760 _PyLong_One = PyLong_FromLong(1);
5761 if (_PyLong_One == NULL) {
5762 return 0;
5763 }
5764
5765 /* initialize int_info */
5766 if (Int_InfoType.tp_name == NULL) {
5767 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5768 return 0;
5769 }
5770 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005771 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005774}
5775
5776void
Victor Stinner630c8df2019-12-17 13:02:18 +01005777_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005778{
Victor Stinner630c8df2019-12-17 13:02:18 +01005779 if (_Py_IsMainInterpreter(tstate)) {
5780 Py_CLEAR(_PyLong_One);
5781 Py_CLEAR(_PyLong_Zero);
5782 }
5783
Guido van Rossumddefaf32007-01-14 03:31:43 +00005784#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005785 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005786 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005787 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005788#endif
5789}