blob: b672ae420189109d1a4a11190952bd0080de2aa2 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Victor Stinner630c8df2019-12-17 13:02:18 +01006#include "pycore_pystate.h" /* _Py_IsMainInterpreter() */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00007#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Mark Dickinsonc6300392009-04-20 21:38:00 +00009#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000011#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000012
Serhiy Storchaka495e8802017-02-01 23:12:20 +020013#include "clinic/longobject.c.h"
14/*[clinic input]
15class int "PyObject *" "&PyLong_Type"
16[clinic start generated code]*/
17/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
18
Victor Stinner630c8df2019-12-17 13:02:18 +010019#define NSMALLPOSINTS _PY_NSMALLPOSINTS
20#define NSMALLNEGINTS _PY_NSMALLNEGINTS
Facundo Batista6e6f59b2008-07-24 18:57:11 +000021
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020022_Py_IDENTIFIER(little);
23_Py_IDENTIFIER(big);
24
Mark Dickinsone4416742009-02-15 15:14:57 +000025/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020026#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
27 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 (Py_SIZE(x) == 0 ? (sdigit)0 : \
29 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000030
Serhiy Storchakaba85d692017-03-30 09:09:41 +030031PyObject *_PyLong_Zero = NULL;
32PyObject *_PyLong_One = NULL;
33
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#if NSMALLNEGINTS + NSMALLPOSINTS > 0
animalize6b519982019-09-06 14:00:56 +080035#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050036#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070037
Guido van Rossumddefaf32007-01-14 03:31:43 +000038#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +000039Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000040#endif
41
Guido van Rossum7eaf8222007-06-18 17:58:50 +000042static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000043get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000044{
animalize6b519982019-09-06 14:00:56 +080045 assert(IS_SMALL_INT(ival));
Victor Stinner630c8df2019-12-17 13:02:18 +010046 PyThreadState *tstate = _PyThreadState_GET();
47 PyObject *v = (PyObject*)tstate->interp->small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000049#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 if (ival >= 0)
Pablo Galindo49c75a82018-10-28 15:02:17 +000051 _Py_quick_int_allocs++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 else
Pablo Galindo49c75a82018-10-28 15:02:17 +000053 _Py_quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000054#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000056}
Guido van Rossumddefaf32007-01-14 03:31:43 +000057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000059maybe_small_long(PyLongObject *v)
60{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020061 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080063 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 Py_DECREF(v);
65 return (PyLongObject *)get_small_int(ival);
66 }
67 }
68 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069}
Guido van Rossumddefaf32007-01-14 03:31:43 +000070#else
animalize6b519982019-09-06 14:00:56 +080071#define IS_SMALL_INT(ival) 0
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050072#define IS_SMALL_UINT(ival) 0
animalize6b519982019-09-06 14:00:56 +080073#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000074#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000075#endif
76
Serhiy Storchaka95949422013-08-27 19:40:23 +030077/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000078 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020079Py_LOCAL_INLINE(void)
80_PyLong_Negate(PyLongObject **x_p)
81{
82 PyLongObject *x;
83
84 x = (PyLongObject *)*x_p;
85 if (Py_REFCNT(x) == 1) {
86 Py_SIZE(x) = -Py_SIZE(x);
87 return;
88 }
89
90 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
91 Py_DECREF(x);
92}
93
Serhiy Storchaka95949422013-08-27 19:40:23 +030094/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000095 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030096 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000097 */
Tim Peters0973b992004-08-29 22:16:50 +000098#define KARATSUBA_CUTOFF 70
99#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +0000100
Tim Peters47e52ee2004-08-30 02:44:38 +0000101/* For exponentiation, use the binary left-to-right algorithm
102 * unless the exponent contains more than FIVEARY_CUTOFF digits.
103 * In that case, do 5 bits at a time. The potential drawback is that
104 * a table of 2**5 intermediate results is computed.
105 */
106#define FIVEARY_CUTOFF 8
107
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000108#define SIGCHECK(PyTryBlock) \
109 do { \
110 if (PyErr_CheckSignals()) PyTryBlock \
111 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000112
Serhiy Storchaka95949422013-08-27 19:40:23 +0300113/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000114 Doesn't attempt to free the storage--in most cases, due to the nature
115 of the algorithms used, this could save at most be one word anyway. */
116
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000117static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200118long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000119{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200120 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 while (i > 0 && v->ob_digit[i-1] == 0)
124 --i;
125 if (i != j)
126 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
127 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128}
129
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200130/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
131 using the nb_int slot, if available. Raise TypeError if either the
132 nb_int slot is not available or the result of the call to nb_int
133 returns something not of type int.
134*/
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200135PyObject *
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200136_PyLong_FromNbInt(PyObject *integral)
137{
138 PyNumberMethods *nb;
139 PyObject *result;
140
141 /* Fast path for the case that we already have an int. */
142 if (PyLong_CheckExact(integral)) {
143 Py_INCREF(integral);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200144 return integral;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200145 }
146
147 nb = Py_TYPE(integral)->tp_as_number;
148 if (nb == NULL || nb->nb_int == NULL) {
149 PyErr_Format(PyExc_TypeError,
150 "an integer is required (got type %.200s)",
151 Py_TYPE(integral)->tp_name);
152 return NULL;
153 }
154
155 /* Convert using the nb_int slot, which should return something
156 of exact type int. */
157 result = nb->nb_int(integral);
158 if (!result || PyLong_CheckExact(result))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200159 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200160 if (!PyLong_Check(result)) {
161 PyErr_Format(PyExc_TypeError,
162 "__int__ returned non-int (type %.200s)",
163 result->ob_type->tp_name);
164 Py_DECREF(result);
165 return NULL;
166 }
167 /* Issue #17576: warn if 'result' not of exact type int. */
168 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
169 "__int__ returned non-int (type %.200s). "
170 "The ability to return an instance of a strict subclass of int "
171 "is deprecated, and may be removed in a future version of Python.",
172 result->ob_type->tp_name)) {
173 Py_DECREF(result);
174 return NULL;
175 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200176 return result;
177}
178
179/* Convert the given object to a PyLongObject using the nb_index or
180 nb_int slots, if available (the latter is deprecated).
181 Raise TypeError if either nb_index and nb_int slots are not
182 available or the result of the call to nb_index or nb_int
183 returns something not of type int.
184 Should be replaced with PyNumber_Index after the end of the
185 deprecation period.
186*/
187PyObject *
188_PyLong_FromNbIndexOrNbInt(PyObject *integral)
189{
190 PyNumberMethods *nb;
191 PyObject *result;
192
193 /* Fast path for the case that we already have an int. */
194 if (PyLong_CheckExact(integral)) {
195 Py_INCREF(integral);
196 return integral;
197 }
198
199 nb = Py_TYPE(integral)->tp_as_number;
200 if (nb == NULL || (nb->nb_index == NULL && nb->nb_int == NULL)) {
201 PyErr_Format(PyExc_TypeError,
202 "an integer is required (got type %.200s)",
203 Py_TYPE(integral)->tp_name);
204 return NULL;
205 }
206
207 if (nb->nb_index) {
208 /* Convert using the nb_index slot, which should return something
209 of exact type int. */
210 result = nb->nb_index(integral);
211 if (!result || PyLong_CheckExact(result))
212 return result;
213 if (!PyLong_Check(result)) {
214 PyErr_Format(PyExc_TypeError,
215 "__index__ returned non-int (type %.200s)",
216 result->ob_type->tp_name);
217 Py_DECREF(result);
218 return NULL;
219 }
220 /* Issue #17576: warn if 'result' not of exact type int. */
221 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
222 "__index__ returned non-int (type %.200s). "
223 "The ability to return an instance of a strict subclass of int "
224 "is deprecated, and may be removed in a future version of Python.",
225 result->ob_type->tp_name))
226 {
227 Py_DECREF(result);
228 return NULL;
229 }
230 return result;
231 }
232
233 result = _PyLong_FromNbInt(integral);
234 if (result && PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
235 "an integer is required (got type %.200s). "
236 "Implicit conversion to integers using __int__ is deprecated, "
237 "and may be removed in a future version of Python.",
238 Py_TYPE(integral)->tp_name))
239 {
240 Py_DECREF(result);
241 return NULL;
242 }
243 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200244}
245
246
Serhiy Storchaka95949422013-08-27 19:40:23 +0300247/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000248 Return NULL and set exception if we run out of memory. */
249
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000250#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000252
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000253PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000254_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 PyLongObject *result;
257 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
258 sizeof(digit)*size. Previous incarnations of this code used
259 sizeof(PyVarObject) instead of the offsetof, but this risks being
260 incorrect in the presence of padding between the PyVarObject header
261 and the digits. */
262 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
263 PyErr_SetString(PyExc_OverflowError,
264 "too many digits in integer");
265 return NULL;
266 }
267 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
268 size*sizeof(digit));
269 if (!result) {
270 PyErr_NoMemory();
271 return NULL;
272 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100273 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000274}
275
Tim Peters64b5ce32001-09-10 20:52:51 +0000276PyObject *
277_PyLong_Copy(PyLongObject *src)
278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 PyLongObject *result;
280 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 assert(src != NULL);
283 i = Py_SIZE(src);
284 if (i < 0)
285 i = -(i);
286 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100287 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800288 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700289 return get_small_int(ival);
290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 }
292 result = _PyLong_New(i);
293 if (result != NULL) {
294 Py_SIZE(result) = Py_SIZE(src);
295 while (--i >= 0)
296 result->ob_digit[i] = src->ob_digit[i];
297 }
298 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000299}
300
Serhiy Storchaka95949422013-08-27 19:40:23 +0300301/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000302
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000304PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 PyLongObject *v;
307 unsigned long abs_ival;
308 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
309 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100310 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000311
animalize6b519982019-09-06 14:00:56 +0800312 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700313 return get_small_int((sdigit)ival);
314 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (ival < 0) {
317 /* negate: can't write this as abs_ival = -ival since that
318 invokes undefined behaviour when ival is LONG_MIN */
319 abs_ival = 0U-(unsigned long)ival;
320 sign = -1;
321 }
322 else {
323 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100324 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 /* Fast path for single-digit ints */
328 if (!(abs_ival >> PyLong_SHIFT)) {
329 v = _PyLong_New(1);
330 if (v) {
331 Py_SIZE(v) = sign;
332 v->ob_digit[0] = Py_SAFE_DOWNCAST(
333 abs_ival, unsigned long, digit);
334 }
335 return (PyObject*)v;
336 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000337
Mark Dickinson249b8982009-04-27 19:41:00 +0000338#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* 2 digits */
340 if (!(abs_ival >> 2*PyLong_SHIFT)) {
341 v = _PyLong_New(2);
342 if (v) {
343 Py_SIZE(v) = 2*sign;
344 v->ob_digit[0] = Py_SAFE_DOWNCAST(
345 abs_ival & PyLong_MASK, unsigned long, digit);
346 v->ob_digit[1] = Py_SAFE_DOWNCAST(
347 abs_ival >> PyLong_SHIFT, unsigned long, digit);
348 }
349 return (PyObject*)v;
350 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000351#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 /* Larger numbers: loop to determine number of digits */
354 t = abs_ival;
355 while (t) {
356 ++ndigits;
357 t >>= PyLong_SHIFT;
358 }
359 v = _PyLong_New(ndigits);
360 if (v != NULL) {
361 digit *p = v->ob_digit;
362 Py_SIZE(v) = ndigits*sign;
363 t = abs_ival;
364 while (t) {
365 *p++ = Py_SAFE_DOWNCAST(
366 t & PyLong_MASK, unsigned long, digit);
367 t >>= PyLong_SHIFT;
368 }
369 }
370 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000371}
372
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500373#define PYLONG_FROM_UINT(INT_TYPE, ival) \
374 do { \
375 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200376 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500377 } \
378 /* Count the number of Python digits. */ \
379 Py_ssize_t ndigits = 0; \
380 INT_TYPE t = (ival); \
381 while (t) { \
382 ++ndigits; \
383 t >>= PyLong_SHIFT; \
384 } \
385 PyLongObject *v = _PyLong_New(ndigits); \
386 if (v == NULL) { \
387 return NULL; \
388 } \
389 digit *p = v->ob_digit; \
390 while ((ival)) { \
391 *p++ = (digit)((ival) & PyLong_MASK); \
392 (ival) >>= PyLong_SHIFT; \
393 } \
394 return (PyObject *)v; \
395 } while(0)
396
Serhiy Storchaka95949422013-08-27 19:40:23 +0300397/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000398
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000399PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000400PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000401{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500402 PYLONG_FROM_UINT(unsigned long, ival);
403}
Tim Petersce9de2f2001-06-14 04:56:19 +0000404
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500405/* Create a new int object from a C unsigned long long int. */
406
407PyObject *
408PyLong_FromUnsignedLongLong(unsigned long long ival)
409{
410 PYLONG_FROM_UINT(unsigned long long, ival);
411}
412
413/* Create a new int object from a C size_t. */
414
415PyObject *
416PyLong_FromSize_t(size_t ival)
417{
418 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000419}
420
Serhiy Storchaka95949422013-08-27 19:40:23 +0300421/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000422
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000423PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 PyLongObject *v;
427 double frac;
428 int i, ndig, expo, neg;
429 neg = 0;
430 if (Py_IS_INFINITY(dval)) {
431 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000432 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 return NULL;
434 }
435 if (Py_IS_NAN(dval)) {
436 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000437 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 return NULL;
439 }
440 if (dval < 0.0) {
441 neg = 1;
442 dval = -dval;
443 }
444 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
445 if (expo <= 0)
446 return PyLong_FromLong(0L);
447 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
448 v = _PyLong_New(ndig);
449 if (v == NULL)
450 return NULL;
451 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
452 for (i = ndig; --i >= 0; ) {
453 digit bits = (digit)frac;
454 v->ob_digit[i] = bits;
455 frac = frac - (double)bits;
456 frac = ldexp(frac, PyLong_SHIFT);
457 }
458 if (neg)
459 Py_SIZE(v) = -(Py_SIZE(v));
460 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000461}
462
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
464 * anything about what happens when a signed integer operation overflows,
465 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700466 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000467 * (unsigned long)LONG_MAX, and for the smallest negative signed long
468 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
469 * However, some other compilers warn about applying unary minus to an
470 * unsigned operand. Hence the weird "0-".
471 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
473#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000474
Serhiy Storchaka95949422013-08-27 19:40:23 +0300475/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100476 method.
477
478 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
479 the result. Otherwise *overflow is 0.
480
481 For other errors (e.g., TypeError), return -1 and set an error condition.
482 In this case *overflow will be 0.
483*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000484
485long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000486PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200489 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 unsigned long x, prev;
491 long res;
492 Py_ssize_t i;
493 int sign;
494 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 *overflow = 0;
497 if (vv == NULL) {
498 PyErr_BadInternalCall();
499 return -1;
500 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000501
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200502 if (PyLong_Check(vv)) {
503 v = (PyLongObject *)vv;
504 }
505 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200506 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200507 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return -1;
509 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 switch (i) {
516 case -1:
517 res = -(sdigit)v->ob_digit[0];
518 break;
519 case 0:
520 res = 0;
521 break;
522 case 1:
523 res = v->ob_digit[0];
524 break;
525 default:
526 sign = 1;
527 x = 0;
528 if (i < 0) {
529 sign = -1;
530 i = -(i);
531 }
532 while (--i >= 0) {
533 prev = x;
534 x = (x << PyLong_SHIFT) | v->ob_digit[i];
535 if ((x >> PyLong_SHIFT) != prev) {
536 *overflow = sign;
537 goto exit;
538 }
539 }
540 /* Haven't lost any bits, but casting to long requires extra
541 * care (see comment above).
542 */
543 if (x <= (unsigned long)LONG_MAX) {
544 res = (long)x * sign;
545 }
546 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
547 res = LONG_MIN;
548 }
549 else {
550 *overflow = sign;
551 /* res is already set to -1 */
552 }
553 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000554 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200556 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 }
558 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000559}
560
Serhiy Storchaka95949422013-08-27 19:40:23 +0300561/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100562 method. Return -1 and set an error if overflow occurs. */
563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000565PyLong_AsLong(PyObject *obj)
566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 int overflow;
568 long result = PyLong_AsLongAndOverflow(obj, &overflow);
569 if (overflow) {
570 /* XXX: could be cute and give a different
571 message for overflow == -1 */
572 PyErr_SetString(PyExc_OverflowError,
573 "Python int too large to convert to C long");
574 }
575 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000576}
577
Serhiy Storchaka95949422013-08-27 19:40:23 +0300578/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200579 method. Return -1 and set an error if overflow occurs. */
580
581int
582_PyLong_AsInt(PyObject *obj)
583{
584 int overflow;
585 long result = PyLong_AsLongAndOverflow(obj, &overflow);
586 if (overflow || result > INT_MAX || result < INT_MIN) {
587 /* XXX: could be cute and give a different
588 message for overflow == -1 */
589 PyErr_SetString(PyExc_OverflowError,
590 "Python int too large to convert to C int");
591 return -1;
592 }
593 return (int)result;
594}
595
Serhiy Storchaka95949422013-08-27 19:40:23 +0300596/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000597 Returns -1 and sets an error condition if overflow occurs. */
598
599Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000600PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200601 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 size_t x, prev;
603 Py_ssize_t i;
604 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (vv == NULL) {
607 PyErr_BadInternalCall();
608 return -1;
609 }
610 if (!PyLong_Check(vv)) {
611 PyErr_SetString(PyExc_TypeError, "an integer is required");
612 return -1;
613 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 v = (PyLongObject *)vv;
616 i = Py_SIZE(v);
617 switch (i) {
618 case -1: return -(sdigit)v->ob_digit[0];
619 case 0: return 0;
620 case 1: return v->ob_digit[0];
621 }
622 sign = 1;
623 x = 0;
624 if (i < 0) {
625 sign = -1;
626 i = -(i);
627 }
628 while (--i >= 0) {
629 prev = x;
630 x = (x << PyLong_SHIFT) | v->ob_digit[i];
631 if ((x >> PyLong_SHIFT) != prev)
632 goto overflow;
633 }
634 /* Haven't lost any bits, but casting to a signed type requires
635 * extra care (see comment above).
636 */
637 if (x <= (size_t)PY_SSIZE_T_MAX) {
638 return (Py_ssize_t)x * sign;
639 }
640 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
641 return PY_SSIZE_T_MIN;
642 }
643 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000644
Mark Dickinson22b20182010-05-10 21:27:53 +0000645 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyErr_SetString(PyExc_OverflowError,
647 "Python int too large to convert to C ssize_t");
648 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000649}
650
Serhiy Storchaka95949422013-08-27 19:40:23 +0300651/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000652 Returns -1 and sets an error condition if overflow occurs. */
653
654unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000655PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000656{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200657 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 unsigned long x, prev;
659 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (vv == NULL) {
662 PyErr_BadInternalCall();
663 return (unsigned long)-1;
664 }
665 if (!PyLong_Check(vv)) {
666 PyErr_SetString(PyExc_TypeError, "an integer is required");
667 return (unsigned long)-1;
668 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 v = (PyLongObject *)vv;
671 i = Py_SIZE(v);
672 x = 0;
673 if (i < 0) {
674 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000675 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return (unsigned long) -1;
677 }
678 switch (i) {
679 case 0: return 0;
680 case 1: return v->ob_digit[0];
681 }
682 while (--i >= 0) {
683 prev = x;
684 x = (x << PyLong_SHIFT) | v->ob_digit[i];
685 if ((x >> PyLong_SHIFT) != prev) {
686 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100687 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000688 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 return (unsigned long) -1;
690 }
691 }
692 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000693}
694
Serhiy Storchaka95949422013-08-27 19:40:23 +0300695/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200696 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000697
698size_t
699PyLong_AsSize_t(PyObject *vv)
700{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200701 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 size_t x, prev;
703 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (vv == NULL) {
706 PyErr_BadInternalCall();
707 return (size_t) -1;
708 }
709 if (!PyLong_Check(vv)) {
710 PyErr_SetString(PyExc_TypeError, "an integer is required");
711 return (size_t)-1;
712 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 v = (PyLongObject *)vv;
715 i = Py_SIZE(v);
716 x = 0;
717 if (i < 0) {
718 PyErr_SetString(PyExc_OverflowError,
719 "can't convert negative value to size_t");
720 return (size_t) -1;
721 }
722 switch (i) {
723 case 0: return 0;
724 case 1: return v->ob_digit[0];
725 }
726 while (--i >= 0) {
727 prev = x;
728 x = (x << PyLong_SHIFT) | v->ob_digit[i];
729 if ((x >> PyLong_SHIFT) != prev) {
730 PyErr_SetString(PyExc_OverflowError,
731 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200732 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 }
734 }
735 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000736}
737
Serhiy Storchaka95949422013-08-27 19:40:23 +0300738/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000739 Returns -1 and sets an error condition if an error occurs. */
740
Guido van Rossumddefaf32007-01-14 03:31:43 +0000741static unsigned long
742_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000743{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200744 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 unsigned long x;
746 Py_ssize_t i;
747 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (vv == NULL || !PyLong_Check(vv)) {
750 PyErr_BadInternalCall();
751 return (unsigned long) -1;
752 }
753 v = (PyLongObject *)vv;
754 i = Py_SIZE(v);
755 switch (i) {
756 case 0: return 0;
757 case 1: return v->ob_digit[0];
758 }
759 sign = 1;
760 x = 0;
761 if (i < 0) {
762 sign = -1;
763 i = -i;
764 }
765 while (--i >= 0) {
766 x = (x << PyLong_SHIFT) | v->ob_digit[i];
767 }
768 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000769}
770
Guido van Rossumddefaf32007-01-14 03:31:43 +0000771unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200772PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 PyLongObject *lo;
775 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000776
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200777 if (op == NULL) {
778 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 return (unsigned long)-1;
780 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000781
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200782 if (PyLong_Check(op)) {
783 return _PyLong_AsUnsignedLongMask(op);
784 }
785
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200786 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (lo == NULL)
788 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200789
790 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
791 Py_DECREF(lo);
792 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000793}
794
Tim Peters5b8132f2003-01-31 15:52:05 +0000795int
796_PyLong_Sign(PyObject *vv)
797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 assert(v != NULL);
801 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000804}
805
Tim Petersbaefd9e2003-01-28 20:37:45 +0000806size_t
807_PyLong_NumBits(PyObject *vv)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PyLongObject *v = (PyLongObject *)vv;
810 size_t result = 0;
811 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200812 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 assert(v != NULL);
815 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200816 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
818 if (ndigits > 0) {
819 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700820 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100822 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Niklas Fiekasc5b79002020-01-16 15:09:19 +0100823 msd_bits = _Py_bit_length(msd);
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200824 if (SIZE_MAX - msd_bits < result)
825 goto Overflow;
826 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 }
828 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000829
Mark Dickinson22b20182010-05-10 21:27:53 +0000830 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
832 "to express in a platform size_t");
833 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000834}
835
Tim Peters2a9b3672001-06-11 21:23:58 +0000836PyObject *
837_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000839{
Mark Dickinson22b20182010-05-10 21:27:53 +0000840 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 int incr; /* direction to move pstartbyte */
842 const unsigned char* pendbyte; /* MSB of bytes */
843 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300844 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyLongObject* v; /* result */
846 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (n == 0)
849 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 if (little_endian) {
852 pstartbyte = bytes;
853 pendbyte = bytes + n - 1;
854 incr = 1;
855 }
856 else {
857 pstartbyte = bytes + n - 1;
858 pendbyte = bytes;
859 incr = -1;
860 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (is_signed)
863 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200866 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 is positive, and leading 0xff bytes if negative. */
868 {
869 size_t i;
870 const unsigned char* p = pendbyte;
871 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000872 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000875 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 break;
877 }
878 numsignificantbytes = n - i;
879 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
880 actually has 2 significant bytes. OTOH, 0xff0001 ==
881 -0x00ffff, so we wouldn't *need* to bump it there; but we
882 do for 0xffff = -0x0001. To be safe without bothering to
883 check every case, bump it regardless. */
884 if (is_signed && numsignificantbytes < n)
885 ++numsignificantbytes;
886 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000887
Serhiy Storchaka95949422013-08-27 19:40:23 +0300888 /* How many Python int digits do we need? We have
889 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
891 /* catch overflow before it happens */
892 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
893 PyErr_SetString(PyExc_OverflowError,
894 "byte array too long to convert to int");
895 return NULL;
896 }
897 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
898 v = _PyLong_New(ndigits);
899 if (v == NULL)
900 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 /* Copy the bits over. The tricky parts are computing 2's-comp on
903 the fly for signed numbers, and dealing with the mismatch between
904 8-bit bytes and (probably) 15-bit Python digits.*/
905 {
906 size_t i;
907 twodigits carry = 1; /* for 2's-comp calculation */
908 twodigits accum = 0; /* sliding register */
909 unsigned int accumbits = 0; /* number of bits in accum */
910 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
913 twodigits thisbyte = *p;
914 /* Compute correction for 2's comp, if needed. */
915 if (is_signed) {
916 thisbyte = (0xff ^ thisbyte) + carry;
917 carry = thisbyte >> 8;
918 thisbyte &= 0xff;
919 }
920 /* Because we're going LSB to MSB, thisbyte is
921 more significant than what's already in accum,
922 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200923 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 accumbits += 8;
925 if (accumbits >= PyLong_SHIFT) {
926 /* There's enough to fill a Python digit. */
927 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000928 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 ++idigit;
930 accum >>= PyLong_SHIFT;
931 accumbits -= PyLong_SHIFT;
932 assert(accumbits < PyLong_SHIFT);
933 }
934 }
935 assert(accumbits < PyLong_SHIFT);
936 if (accumbits) {
937 assert(idigit < ndigits);
938 v->ob_digit[idigit] = (digit)accum;
939 ++idigit;
940 }
941 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 Py_SIZE(v) = is_signed ? -idigit : idigit;
944 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000945}
946
947int
948_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 unsigned char* bytes, size_t n,
950 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000953 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000955 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
957 digit carry; /* for computing 2's-comp */
958 size_t j; /* # bytes filled */
959 unsigned char* p; /* pointer to next byte in bytes */
960 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (Py_SIZE(v) < 0) {
965 ndigits = -(Py_SIZE(v));
966 if (!is_signed) {
967 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000968 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 return -1;
970 }
971 do_twos_comp = 1;
972 }
973 else {
974 ndigits = Py_SIZE(v);
975 do_twos_comp = 0;
976 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 if (little_endian) {
979 p = bytes;
980 pincr = 1;
981 }
982 else {
983 p = bytes + n - 1;
984 pincr = -1;
985 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 /* Copy over all the Python digits.
988 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300989 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 normalized. */
991 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
992 j = 0;
993 accum = 0;
994 accumbits = 0;
995 carry = do_twos_comp ? 1 : 0;
996 for (i = 0; i < ndigits; ++i) {
997 digit thisdigit = v->ob_digit[i];
998 if (do_twos_comp) {
999 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
1000 carry = thisdigit >> PyLong_SHIFT;
1001 thisdigit &= PyLong_MASK;
1002 }
1003 /* Because we're going LSB to MSB, thisdigit is more
1004 significant than what's already in accum, so needs to be
1005 prepended to accum. */
1006 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* The most-significant digit may be (probably is) at least
1009 partly empty. */
1010 if (i == ndigits - 1) {
1011 /* Count # of sign bits -- they needn't be stored,
1012 * although for signed conversion we need later to
1013 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +00001014 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 while (s != 0) {
1016 s >>= 1;
1017 accumbits++;
1018 }
1019 }
1020 else
1021 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 /* Store as many bytes as possible. */
1024 while (accumbits >= 8) {
1025 if (j >= n)
1026 goto Overflow;
1027 ++j;
1028 *p = (unsigned char)(accum & 0xff);
1029 p += pincr;
1030 accumbits -= 8;
1031 accum >>= 8;
1032 }
1033 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* Store the straggler (if any). */
1036 assert(accumbits < 8);
1037 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1038 if (accumbits > 0) {
1039 if (j >= n)
1040 goto Overflow;
1041 ++j;
1042 if (do_twos_comp) {
1043 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +03001044 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 infinite supply of sign bits). */
1046 accum |= (~(twodigits)0) << accumbits;
1047 }
1048 *p = (unsigned char)(accum & 0xff);
1049 p += pincr;
1050 }
1051 else if (j == n && n > 0 && is_signed) {
1052 /* The main loop filled the byte array exactly, so the code
1053 just above didn't get to ensure there's a sign bit, and the
1054 loop below wouldn't add one either. Make sure a sign bit
1055 exists. */
1056 unsigned char msb = *(p - pincr);
1057 int sign_bit_set = msb >= 0x80;
1058 assert(accumbits == 0);
1059 if (sign_bit_set == do_twos_comp)
1060 return 0;
1061 else
1062 goto Overflow;
1063 }
Tim Peters05607ad2001-06-13 21:01:27 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 /* Fill remaining bytes with copies of the sign bit. */
1066 {
1067 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1068 for ( ; j < n; ++j, p += pincr)
1069 *p = signbyte;
1070 }
Tim Peters05607ad2001-06-13 21:01:27 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001073
Mark Dickinson22b20182010-05-10 21:27:53 +00001074 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1076 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001077
Tim Peters2a9b3672001-06-11 21:23:58 +00001078}
1079
Serhiy Storchaka95949422013-08-27 19:40:23 +03001080/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001081
1082PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001083PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001084{
Mark Dickinson91044792012-10-18 19:21:43 +01001085#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001086 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001087#else
1088
Tim Peters70128a12001-06-16 08:48:40 +00001089#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001090# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001091#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001092 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001093#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001094
Guido van Rossum78694d91998-09-18 14:14:13 +00001095}
1096
Serhiy Storchaka95949422013-08-27 19:40:23 +03001097/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001098
1099void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001100PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001101{
Tim Peters70128a12001-06-16 08:48:40 +00001102#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1106 x = PyLong_AsLong(vv);
1107 else
1108 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001109#else
Tim Peters70128a12001-06-16 08:48:40 +00001110
Tim Peters70128a12001-06-16 08:48:40 +00001111#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001112# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001113#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001114 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1117 x = PyLong_AsLongLong(vv);
1118 else
1119 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001120
1121#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (x == -1 && PyErr_Occurred())
1124 return NULL;
1125 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001126}
1127
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001128/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001129 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001130 */
1131
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001132#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001133
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001134/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001135
1136PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001137PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001140 unsigned long long abs_ival;
1141 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 int ndigits = 0;
1143 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001144
animalize6b519982019-09-06 14:00:56 +08001145 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001146 return get_small_int((sdigit)ival);
1147 }
1148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 if (ival < 0) {
1150 /* avoid signed overflow on negation; see comments
1151 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001152 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 negative = 1;
1154 }
1155 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001156 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 /* Count the number of Python digits.
1160 We used to pick 5 ("big enough for anything"), but that's a
1161 waste of time and space given that 5*15 = 75 bits are rarely
1162 needed. */
1163 t = abs_ival;
1164 while (t) {
1165 ++ndigits;
1166 t >>= PyLong_SHIFT;
1167 }
1168 v = _PyLong_New(ndigits);
1169 if (v != NULL) {
1170 digit *p = v->ob_digit;
1171 Py_SIZE(v) = negative ? -ndigits : ndigits;
1172 t = abs_ival;
1173 while (t) {
1174 *p++ = (digit)(t & PyLong_MASK);
1175 t >>= PyLong_SHIFT;
1176 }
1177 }
1178 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001179}
1180
Serhiy Storchaka95949422013-08-27 19:40:23 +03001181/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001182
1183PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001184PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 PyLongObject *v;
1187 size_t abs_ival;
1188 size_t t; /* unsigned so >> doesn't propagate sign bit */
1189 int ndigits = 0;
1190 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001191
animalize6b519982019-09-06 14:00:56 +08001192 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001193 return get_small_int((sdigit)ival);
1194 }
1195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (ival < 0) {
1197 /* avoid signed overflow when ival = SIZE_T_MIN */
1198 abs_ival = (size_t)(-1-ival)+1;
1199 negative = 1;
1200 }
1201 else {
1202 abs_ival = (size_t)ival;
1203 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 /* Count the number of Python digits. */
1206 t = abs_ival;
1207 while (t) {
1208 ++ndigits;
1209 t >>= PyLong_SHIFT;
1210 }
1211 v = _PyLong_New(ndigits);
1212 if (v != NULL) {
1213 digit *p = v->ob_digit;
1214 Py_SIZE(v) = negative ? -ndigits : ndigits;
1215 t = abs_ival;
1216 while (t) {
1217 *p++ = (digit)(t & PyLong_MASK);
1218 t >>= PyLong_SHIFT;
1219 }
1220 }
1221 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001222}
1223
Serhiy Storchaka95949422013-08-27 19:40:23 +03001224/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001225 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001226
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001227long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001228PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001231 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001233 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (vv == NULL) {
1236 PyErr_BadInternalCall();
1237 return -1;
1238 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001239
1240 if (PyLong_Check(vv)) {
1241 v = (PyLongObject *)vv;
1242 }
1243 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001244 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001245 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001247 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001249
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001250 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001252 case -1:
1253 bytes = -(sdigit)v->ob_digit[0];
1254 break;
1255 case 0:
1256 bytes = 0;
1257 break;
1258 case 1:
1259 bytes = v->ob_digit[0];
1260 break;
1261 default:
1262 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001263 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001265 if (do_decref) {
1266 Py_DECREF(v);
1267 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001268
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001269 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001271 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 else
1273 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001274}
1275
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001276/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001277 Return -1 and set an error if overflow occurs. */
1278
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001279unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001280PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001283 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001285
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001286 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001288 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001290 if (!PyLong_Check(vv)) {
1291 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001292 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001293 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 v = (PyLongObject*)vv;
1296 switch(Py_SIZE(v)) {
1297 case 0: return 0;
1298 case 1: return v->ob_digit[0];
1299 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001300
Mark Dickinson22b20182010-05-10 21:27:53 +00001301 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001302 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001303
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001304 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001306 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 else
1308 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001309}
Tim Petersd1a7da62001-06-13 00:35:57 +00001310
Serhiy Storchaka95949422013-08-27 19:40:23 +03001311/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001312 Returns -1 and sets an error condition if an error occurs. */
1313
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001314static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001315_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001316{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001317 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001318 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 Py_ssize_t i;
1320 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (vv == NULL || !PyLong_Check(vv)) {
1323 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001324 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 }
1326 v = (PyLongObject *)vv;
1327 switch(Py_SIZE(v)) {
1328 case 0: return 0;
1329 case 1: return v->ob_digit[0];
1330 }
1331 i = Py_SIZE(v);
1332 sign = 1;
1333 x = 0;
1334 if (i < 0) {
1335 sign = -1;
1336 i = -i;
1337 }
1338 while (--i >= 0) {
1339 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1340 }
1341 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001342}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001343
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001344unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001345PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001348 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001349
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001350 if (op == NULL) {
1351 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001352 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001354
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001355 if (PyLong_Check(op)) {
1356 return _PyLong_AsUnsignedLongLongMask(op);
1357 }
1358
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001359 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001361 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001362
1363 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1364 Py_DECREF(lo);
1365 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001366}
Tim Petersd1a7da62001-06-13 00:35:57 +00001367
Serhiy Storchaka95949422013-08-27 19:40:23 +03001368/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001369 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001370
Mark Dickinson8d48b432011-10-23 20:47:14 +01001371 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1372 the result. Otherwise *overflow is 0.
1373
1374 For other errors (e.g., TypeError), return -1 and set an error condition.
1375 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001376*/
1377
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001378long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001379PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001382 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001383 unsigned long long x, prev;
1384 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 Py_ssize_t i;
1386 int sign;
1387 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 *overflow = 0;
1390 if (vv == NULL) {
1391 PyErr_BadInternalCall();
1392 return -1;
1393 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001394
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001395 if (PyLong_Check(vv)) {
1396 v = (PyLongObject *)vv;
1397 }
1398 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001399 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001400 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 return -1;
1402 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 switch (i) {
1409 case -1:
1410 res = -(sdigit)v->ob_digit[0];
1411 break;
1412 case 0:
1413 res = 0;
1414 break;
1415 case 1:
1416 res = v->ob_digit[0];
1417 break;
1418 default:
1419 sign = 1;
1420 x = 0;
1421 if (i < 0) {
1422 sign = -1;
1423 i = -(i);
1424 }
1425 while (--i >= 0) {
1426 prev = x;
1427 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1428 if ((x >> PyLong_SHIFT) != prev) {
1429 *overflow = sign;
1430 goto exit;
1431 }
1432 }
1433 /* Haven't lost any bits, but casting to long requires extra
1434 * care (see comment above).
1435 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001436 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001437 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 }
1439 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001440 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 }
1442 else {
1443 *overflow = sign;
1444 /* res is already set to -1 */
1445 }
1446 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001447 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001449 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 }
1451 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001452}
1453
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001454int
1455_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1456{
1457 unsigned long uval;
1458
1459 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1460 PyErr_SetString(PyExc_ValueError, "value must be positive");
1461 return 0;
1462 }
1463 uval = PyLong_AsUnsignedLong(obj);
1464 if (uval == (unsigned long)-1 && PyErr_Occurred())
1465 return 0;
1466 if (uval > USHRT_MAX) {
1467 PyErr_SetString(PyExc_OverflowError,
1468 "Python int too large for C unsigned short");
1469 return 0;
1470 }
1471
1472 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1473 return 1;
1474}
1475
1476int
1477_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1478{
1479 unsigned long uval;
1480
1481 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1482 PyErr_SetString(PyExc_ValueError, "value must be positive");
1483 return 0;
1484 }
1485 uval = PyLong_AsUnsignedLong(obj);
1486 if (uval == (unsigned long)-1 && PyErr_Occurred())
1487 return 0;
1488 if (uval > UINT_MAX) {
1489 PyErr_SetString(PyExc_OverflowError,
1490 "Python int too large for C unsigned int");
1491 return 0;
1492 }
1493
1494 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1495 return 1;
1496}
1497
1498int
1499_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1500{
1501 unsigned long uval;
1502
1503 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1504 PyErr_SetString(PyExc_ValueError, "value must be positive");
1505 return 0;
1506 }
1507 uval = PyLong_AsUnsignedLong(obj);
1508 if (uval == (unsigned long)-1 && PyErr_Occurred())
1509 return 0;
1510
1511 *(unsigned long *)ptr = uval;
1512 return 1;
1513}
1514
1515int
1516_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1517{
1518 unsigned long long uval;
1519
1520 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1521 PyErr_SetString(PyExc_ValueError, "value must be positive");
1522 return 0;
1523 }
1524 uval = PyLong_AsUnsignedLongLong(obj);
1525 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1526 return 0;
1527
1528 *(unsigned long long *)ptr = uval;
1529 return 1;
1530}
1531
1532int
1533_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1534{
1535 size_t uval;
1536
1537 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1538 PyErr_SetString(PyExc_ValueError, "value must be positive");
1539 return 0;
1540 }
1541 uval = PyLong_AsSize_t(obj);
1542 if (uval == (size_t)-1 && PyErr_Occurred())
1543 return 0;
1544
1545 *(size_t *)ptr = uval;
1546 return 1;
1547}
1548
1549
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001550#define CHECK_BINOP(v,w) \
1551 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001552 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1553 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001554 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001555
Tim Peters877a2122002-08-12 05:09:36 +00001556/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1557 * is modified in place, by adding y to it. Carries are propagated as far as
1558 * x[m-1], and the remaining carry (0 or 1) is returned.
1559 */
1560static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001561v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 Py_ssize_t i;
1564 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 assert(m >= n);
1567 for (i = 0; i < n; ++i) {
1568 carry += x[i] + y[i];
1569 x[i] = carry & PyLong_MASK;
1570 carry >>= PyLong_SHIFT;
1571 assert((carry & 1) == carry);
1572 }
1573 for (; carry && i < m; ++i) {
1574 carry += x[i];
1575 x[i] = carry & PyLong_MASK;
1576 carry >>= PyLong_SHIFT;
1577 assert((carry & 1) == carry);
1578 }
1579 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001580}
1581
1582/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1583 * is modified in place, by subtracting y from it. Borrows are propagated as
1584 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1585 */
1586static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001587v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 Py_ssize_t i;
1590 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 assert(m >= n);
1593 for (i = 0; i < n; ++i) {
1594 borrow = x[i] - y[i] - borrow;
1595 x[i] = borrow & PyLong_MASK;
1596 borrow >>= PyLong_SHIFT;
1597 borrow &= 1; /* keep only 1 sign bit */
1598 }
1599 for (; borrow && i < m; ++i) {
1600 borrow = x[i] - borrow;
1601 x[i] = borrow & PyLong_MASK;
1602 borrow >>= PyLong_SHIFT;
1603 borrow &= 1;
1604 }
1605 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001606}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001607
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001608/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1609 * result in z[0:m], and return the d bits shifted out of the top.
1610 */
1611static digit
1612v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 Py_ssize_t i;
1615 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 assert(0 <= d && d < PyLong_SHIFT);
1618 for (i=0; i < m; i++) {
1619 twodigits acc = (twodigits)a[i] << d | carry;
1620 z[i] = (digit)acc & PyLong_MASK;
1621 carry = (digit)(acc >> PyLong_SHIFT);
1622 }
1623 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001624}
1625
1626/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1627 * result in z[0:m], and return the d bits shifted out of the bottom.
1628 */
1629static digit
1630v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 Py_ssize_t i;
1633 digit carry = 0;
1634 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 assert(0 <= d && d < PyLong_SHIFT);
1637 for (i=m; i-- > 0;) {
1638 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1639 carry = (digit)acc & mask;
1640 z[i] = (digit)(acc >> d);
1641 }
1642 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001643}
1644
Tim Peters212e6142001-07-14 12:23:19 +00001645/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1646 in pout, and returning the remainder. pin and pout point at the LSD.
1647 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001648 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001649 immutable. */
1650
1651static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001652inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 assert(n > 0 && n <= PyLong_MASK);
1657 pin += size;
1658 pout += size;
1659 while (--size >= 0) {
1660 digit hi;
1661 rem = (rem << PyLong_SHIFT) | *--pin;
1662 *--pout = hi = (digit)(rem / n);
1663 rem -= (twodigits)hi * n;
1664 }
1665 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001666}
1667
Serhiy Storchaka95949422013-08-27 19:40:23 +03001668/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001669 (as function result) and the remainder (through *prem).
1670 The sign of a is ignored; n should not be zero. */
1671
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001672static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001673divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001674{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001675 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 assert(n > 0 && n <= PyLong_MASK);
1679 z = _PyLong_New(size);
1680 if (z == NULL)
1681 return NULL;
1682 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1683 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001684}
1685
Serhiy Storchaka95949422013-08-27 19:40:23 +03001686/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001687 string. (Return value is non-shared so that callers can modify the
1688 returned value if necessary.) */
1689
Victor Stinnerd3f08822012-05-29 12:57:52 +02001690static int
1691long_to_decimal_string_internal(PyObject *aa,
1692 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001693 _PyUnicodeWriter *writer,
1694 _PyBytesWriter *bytes_writer,
1695 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001698 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 Py_ssize_t size, strlen, size_a, i, j;
1700 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001702 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001703 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 a = (PyLongObject *)aa;
1706 if (a == NULL || !PyLong_Check(a)) {
1707 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001708 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001710 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 /* quick and dirty upper bound for the number of digits
1714 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 But log2(a) < size_a * PyLong_SHIFT, and
1719 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001720 > 3.3 * _PyLong_DECIMAL_SHIFT
1721
1722 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1723 size_a + size_a / d < size_a + size_a / floor(d),
1724 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1725 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001727 d = (33 * _PyLong_DECIMAL_SHIFT) /
1728 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1729 assert(size_a < PY_SSIZE_T_MAX/2);
1730 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 scratch = _PyLong_New(size);
1732 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001733 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 /* convert array of base _PyLong_BASE digits in pin to an array of
1736 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1737 Volume 2 (3rd edn), section 4.4, Method 1b). */
1738 pin = a->ob_digit;
1739 pout = scratch->ob_digit;
1740 size = 0;
1741 for (i = size_a; --i >= 0; ) {
1742 digit hi = pin[i];
1743 for (j = 0; j < size; j++) {
1744 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1745 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1746 pout[j] = (digit)(z - (twodigits)hi *
1747 _PyLong_DECIMAL_BASE);
1748 }
1749 while (hi) {
1750 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1751 hi /= _PyLong_DECIMAL_BASE;
1752 }
1753 /* check for keyboard interrupt */
1754 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001755 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001756 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001757 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 }
1759 /* pout should have at least one digit, so that the case when a = 0
1760 works correctly */
1761 if (size == 0)
1762 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 /* calculate exact length of output string, and allocate */
1765 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1766 tenpow = 10;
1767 rem = pout[size-1];
1768 while (rem >= tenpow) {
1769 tenpow *= 10;
1770 strlen++;
1771 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001772 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001773 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1774 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001775 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001776 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001777 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001779 else if (bytes_writer) {
1780 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1781 if (*bytes_str == NULL) {
1782 Py_DECREF(scratch);
1783 return -1;
1784 }
1785 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001786 else {
1787 str = PyUnicode_New(strlen, '9');
1788 if (str == NULL) {
1789 Py_DECREF(scratch);
1790 return -1;
1791 }
1792 kind = PyUnicode_KIND(str);
1793 }
1794
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001795#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001796 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001797 /* pout[0] through pout[size-2] contribute exactly \
1798 _PyLong_DECIMAL_SHIFT digits each */ \
1799 for (i=0; i < size - 1; i++) { \
1800 rem = pout[i]; \
1801 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1802 *--p = '0' + rem % 10; \
1803 rem /= 10; \
1804 } \
1805 } \
1806 /* pout[size-1]: always produce at least one decimal digit */ \
1807 rem = pout[i]; \
1808 do { \
1809 *--p = '0' + rem % 10; \
1810 rem /= 10; \
1811 } while (rem != 0); \
1812 \
1813 /* and sign */ \
1814 if (negative) \
1815 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001816 } while (0)
1817
1818#define WRITE_UNICODE_DIGITS(TYPE) \
1819 do { \
1820 if (writer) \
1821 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1822 else \
1823 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1824 \
1825 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001826 \
1827 /* check we've counted correctly */ \
1828 if (writer) \
1829 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1830 else \
1831 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1832 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001835 if (bytes_writer) {
1836 char *p = *bytes_str + strlen;
1837 WRITE_DIGITS(p);
1838 assert(p == *bytes_str);
1839 }
1840 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001841 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001842 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001844 else if (kind == PyUnicode_2BYTE_KIND) {
1845 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001846 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001847 }
1848 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001849 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001850 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001851 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001852 }
1853#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001854#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001857 if (writer) {
1858 writer->pos += strlen;
1859 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001860 else if (bytes_writer) {
1861 (*bytes_str) += strlen;
1862 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001863 else {
1864 assert(_PyUnicode_CheckConsistency(str, 1));
1865 *p_output = (PyObject *)str;
1866 }
1867 return 0;
1868}
1869
1870static PyObject *
1871long_to_decimal_string(PyObject *aa)
1872{
1873 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001874 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001875 return NULL;
1876 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001877}
1878
Serhiy Storchaka95949422013-08-27 19:40:23 +03001879/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001880 which should be one of 2, 8 or 16. Return a string object.
1881 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1882 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001883
Victor Stinnerd3f08822012-05-29 12:57:52 +02001884static int
1885long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001886 PyObject **p_output, _PyUnicodeWriter *writer,
1887 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001888{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001889 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001890 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001891 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001893 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001894 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001896
Victor Stinnerd3f08822012-05-29 12:57:52 +02001897 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (a == NULL || !PyLong_Check(a)) {
1899 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001900 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001902 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001903 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* Compute a rough upper bound for the length of the string */
1906 switch (base) {
1907 case 16:
1908 bits = 4;
1909 break;
1910 case 8:
1911 bits = 3;
1912 break;
1913 case 2:
1914 bits = 1;
1915 break;
1916 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001917 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001919
Mark Dickinsone2846542012-04-20 21:21:24 +01001920 /* Compute exact length 'sz' of output string. */
1921 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001922 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001923 }
1924 else {
1925 Py_ssize_t size_a_in_bits;
1926 /* Ensure overflow doesn't occur during computation of sz. */
1927 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1928 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001929 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001930 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001931 }
1932 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001933 _Py_bit_length(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001934 /* Allow 1 character for a '-' sign. */
1935 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1936 }
1937 if (alternate) {
1938 /* 2 characters for prefix */
1939 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001940 }
1941
Victor Stinnerd3f08822012-05-29 12:57:52 +02001942 if (writer) {
1943 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1944 return -1;
1945 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001947 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001948 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1949 if (*bytes_str == NULL)
1950 return -1;
1951 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001953 v = PyUnicode_New(sz, 'x');
1954 if (v == NULL)
1955 return -1;
1956 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001958
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001959#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001960 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001961 if (size_a == 0) { \
1962 *--p = '0'; \
1963 } \
1964 else { \
1965 /* JRH: special case for power-of-2 bases */ \
1966 twodigits accum = 0; \
1967 int accumbits = 0; /* # of bits in accum */ \
1968 Py_ssize_t i; \
1969 for (i = 0; i < size_a; ++i) { \
1970 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1971 accumbits += PyLong_SHIFT; \
1972 assert(accumbits >= bits); \
1973 do { \
1974 char cdigit; \
1975 cdigit = (char)(accum & (base - 1)); \
1976 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1977 *--p = cdigit; \
1978 accumbits -= bits; \
1979 accum >>= bits; \
1980 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1981 } \
1982 } \
1983 \
1984 if (alternate) { \
1985 if (base == 16) \
1986 *--p = 'x'; \
1987 else if (base == 8) \
1988 *--p = 'o'; \
1989 else /* (base == 2) */ \
1990 *--p = 'b'; \
1991 *--p = '0'; \
1992 } \
1993 if (negative) \
1994 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001995 } while (0)
1996
1997#define WRITE_UNICODE_DIGITS(TYPE) \
1998 do { \
1999 if (writer) \
2000 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
2001 else \
2002 p = (TYPE*)PyUnicode_DATA(v) + sz; \
2003 \
2004 WRITE_DIGITS(p); \
2005 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002006 if (writer) \
2007 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2008 else \
2009 assert(p == (TYPE*)PyUnicode_DATA(v)); \
2010 } while (0)
2011
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002012 if (bytes_writer) {
2013 char *p = *bytes_str + sz;
2014 WRITE_DIGITS(p);
2015 assert(p == *bytes_str);
2016 }
2017 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002018 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002019 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002020 }
2021 else if (kind == PyUnicode_2BYTE_KIND) {
2022 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002023 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002024 }
2025 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002026 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002027 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002028 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002029 }
2030#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002031#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002032
2033 if (writer) {
2034 writer->pos += sz;
2035 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002036 else if (bytes_writer) {
2037 (*bytes_str) += sz;
2038 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002039 else {
2040 assert(_PyUnicode_CheckConsistency(v, 1));
2041 *p_output = v;
2042 }
2043 return 0;
2044}
2045
2046PyObject *
2047_PyLong_Format(PyObject *obj, int base)
2048{
2049 PyObject *str;
2050 int err;
2051 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002052 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002053 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002054 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002055 if (err == -1)
2056 return NULL;
2057 return str;
2058}
2059
2060int
2061_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2062 PyObject *obj,
2063 int base, int alternate)
2064{
2065 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002066 return long_to_decimal_string_internal(obj, NULL, writer,
2067 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002068 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002069 return long_format_binary(obj, base, alternate, NULL, writer,
2070 NULL, NULL);
2071}
2072
2073char*
2074_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2075 PyObject *obj,
2076 int base, int alternate)
2077{
2078 char *str2;
2079 int res;
2080 str2 = str;
2081 if (base == 10)
2082 res = long_to_decimal_string_internal(obj, NULL, NULL,
2083 writer, &str2);
2084 else
2085 res = long_format_binary(obj, base, alternate, NULL, NULL,
2086 writer, &str2);
2087 if (res < 0)
2088 return NULL;
2089 assert(str2 != NULL);
2090 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002091}
2092
Thomas Wouters477c8d52006-05-27 19:21:47 +00002093/* Table of digit values for 8-bit string -> integer conversion.
2094 * '0' maps to 0, ..., '9' maps to 9.
2095 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2096 * All other indices map to 37.
2097 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002098 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002099 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002100unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 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 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2105 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2106 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2107 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2108 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2109 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2110 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2111 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2112 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2113 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2114 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2115 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2116 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002117};
2118
2119/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002120 * 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 +03002121 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002122 * The point to this routine is that it takes time linear in the number of
2123 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002124 *
2125 * Return values:
2126 * -1 on syntax error (exception needs to be set, *res is untouched)
2127 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002128 */
Brett Cannona721aba2016-09-09 14:57:09 -07002129static int
2130long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002131{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002132 const char *p = *str;
2133 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002134 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002135 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 int bits_per_char;
2137 Py_ssize_t n;
2138 PyLongObject *z;
2139 twodigits accum;
2140 int bits_in_accum;
2141 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2144 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002145 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002147 }
2148 /* count digits and set p to end-of-string */
2149 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2150 if (*p == '_') {
2151 if (prev == '_') {
2152 *str = p - 1;
2153 return -1;
2154 }
2155 } else {
2156 ++digits;
2157 }
2158 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002160 }
2161 if (prev == '_') {
2162 /* Trailing underscore not allowed. */
2163 *str = p - 1;
2164 return -1;
2165 }
2166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002168 /* n <- the number of Python digits needed,
2169 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2170 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 PyErr_SetString(PyExc_ValueError,
2172 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002173 *res = NULL;
2174 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002176 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002178 if (z == NULL) {
2179 *res = NULL;
2180 return 0;
2181 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002182 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 * from least to most significant in both.
2184 */
2185 accum = 0;
2186 bits_in_accum = 0;
2187 pdigit = z->ob_digit;
2188 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002189 int k;
2190 if (*p == '_') {
2191 continue;
2192 }
2193 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 assert(k >= 0 && k < base);
2195 accum |= (twodigits)k << bits_in_accum;
2196 bits_in_accum += bits_per_char;
2197 if (bits_in_accum >= PyLong_SHIFT) {
2198 *pdigit++ = (digit)(accum & PyLong_MASK);
2199 assert(pdigit - z->ob_digit <= n);
2200 accum >>= PyLong_SHIFT;
2201 bits_in_accum -= PyLong_SHIFT;
2202 assert(bits_in_accum < PyLong_SHIFT);
2203 }
2204 }
2205 if (bits_in_accum) {
2206 assert(bits_in_accum <= PyLong_SHIFT);
2207 *pdigit++ = (digit)accum;
2208 assert(pdigit - z->ob_digit <= n);
2209 }
2210 while (pdigit - z->ob_digit < n)
2211 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002212 *res = long_normalize(z);
2213 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002214}
2215
Serhiy Storchaka95949422013-08-27 19:40:23 +03002216/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002217 * ignored.
2218 *
2219 * If successful, a PyLong object will be returned and 'pend' will be pointing
2220 * to the first unused byte unless it's NULL.
2221 *
2222 * If unsuccessful, NULL will be returned.
2223 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002224PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002225PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002228 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyLongObject *z = NULL;
2230 PyObject *strobj;
2231 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 if ((base != 0 && base < 2) || base > 36) {
2234 PyErr_SetString(PyExc_ValueError,
2235 "int() arg 2 must be >= 2 and <= 36");
2236 return NULL;
2237 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002238 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002240 }
2241 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002243 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 else if (*str == '-') {
2245 ++str;
2246 sign = -1;
2247 }
2248 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002249 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002251 }
2252 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002254 }
2255 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002257 }
2258 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002260 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 else {
2262 /* "old" (C-style) octal literal, now invalid.
2263 it might still be zero though */
2264 error_if_nonzero = 1;
2265 base = 10;
2266 }
2267 }
2268 if (str[0] == '0' &&
2269 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2270 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002271 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002273 /* One underscore allowed here. */
2274 if (*str == '_') {
2275 ++str;
2276 }
2277 }
2278 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002279 /* May not start with underscores. */
2280 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002281 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002284 if ((base & (base - 1)) == 0) {
2285 int res = long_from_binary_base(&str, base, &z);
2286 if (res < 0) {
2287 /* Syntax error. */
2288 goto onError;
2289 }
2290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002292/***
2293Binary bases can be converted in time linear in the number of digits, because
2294Python's representation base is binary. Other bases (including decimal!) use
2295the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002296
Thomas Wouters477c8d52006-05-27 19:21:47 +00002297First some math: the largest integer that can be expressed in N base-B digits
2298is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2299case number of Python digits needed to hold it is the smallest integer n s.t.
2300
2301 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2302 BASE**n >= B**N [taking logs to base BASE]
2303 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2304
2305The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002306this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002307and the result is computed into it.
2308
2309The input string is actually treated as being in base base**i (i.e., i digits
2310are processed at a time), where two more static arrays hold:
2311
2312 convwidth_base[base] = the largest integer i such that base**i <= BASE
2313 convmultmax_base[base] = base ** convwidth_base[base]
2314
2315The first of these is the largest i such that i consecutive input digits
2316must fit in a single Python digit. The second is effectively the input
2317base we're really using.
2318
2319Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2320convmultmax_base[base], the result is "simply"
2321
2322 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2323
2324where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002325
2326Error analysis: as above, the number of Python digits `n` needed is worst-
2327case
2328
2329 n >= N * log(B)/log(BASE)
2330
2331where `N` is the number of input digits in base `B`. This is computed via
2332
2333 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2334
2335below. Two numeric concerns are how much space this can waste, and whether
2336the computed result can be too small. To be concrete, assume BASE = 2**15,
2337which is the default (and it's unlikely anyone changes that).
2338
2339Waste isn't a problem: provided the first input digit isn't 0, the difference
2340between the worst-case input with N digits and the smallest input with N
2341digits is about a factor of B, but B is small compared to BASE so at most
2342one allocated Python digit can remain unused on that count. If
2343N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2344and adding 1 returns a result 1 larger than necessary. However, that can't
2345happen: whenever B is a power of 2, long_from_binary_base() is called
2346instead, and it's impossible for B**i to be an integer power of 2**15 when
2347B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2348an exact integer when B is not a power of 2, since B**i has a prime factor
2349other than 2 in that case, but (2**15)**j's only prime factor is 2).
2350
2351The computed result can be too small if the true value of N*log(B)/log(BASE)
2352is a little bit larger than an exact integer, but due to roundoff errors (in
2353computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2354yields a numeric result a little less than that integer. Unfortunately, "how
2355close can a transcendental function get to an integer over some range?"
2356questions are generally theoretically intractable. Computer analysis via
2357continued fractions is practical: expand log(B)/log(BASE) via continued
2358fractions, giving a sequence i/j of "the best" rational approximations. Then
2359j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2360we can get very close to being in trouble, but very rarely. For example,
236176573 is a denominator in one of the continued-fraction approximations to
2362log(10)/log(2**15), and indeed:
2363
2364 >>> log(10)/log(2**15)*76573
2365 16958.000000654003
2366
2367is very close to an integer. If we were working with IEEE single-precision,
2368rounding errors could kill us. Finding worst cases in IEEE double-precision
2369requires better-than-double-precision log() functions, and Tim didn't bother.
2370Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002371new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002372This should happen extremely rarely, and in fact I don't have a test case
2373that triggers it(!). Instead the code was tested by artificially allocating
2374just 1 digit at the start, so that the copying code was exercised for every
2375digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002376***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002377 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002379 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 int i;
2381 int convwidth;
2382 twodigits convmultmax, convmult;
2383 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002384 const char *scan, *lastdigit;
2385 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 static double log_base_BASE[37] = {0.0e0,};
2388 static int convwidth_base[37] = {0,};
2389 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 if (log_base_BASE[base] == 0.0) {
2392 twodigits convmax = base;
2393 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002394
Mark Dickinson22b20182010-05-10 21:27:53 +00002395 log_base_BASE[base] = (log((double)base) /
2396 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 for (;;) {
2398 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002399 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002401 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 convmax = next;
2403 ++i;
2404 }
2405 convmultmax_base[base] = convmax;
2406 assert(i > 0);
2407 convwidth_base[base] = i;
2408 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* Find length of the string of numeric characters. */
2411 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002412 lastdigit = str;
2413
2414 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2415 if (*scan == '_') {
2416 if (prev == '_') {
2417 /* Only one underscore allowed. */
2418 str = lastdigit + 1;
2419 goto onError;
2420 }
2421 }
2422 else {
2423 ++digits;
2424 lastdigit = scan;
2425 }
2426 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002428 }
2429 if (prev == '_') {
2430 /* Trailing underscore not allowed. */
2431 /* Set error pointer to first underscore. */
2432 str = lastdigit + 1;
2433 goto onError;
2434 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002435
Serhiy Storchaka95949422013-08-27 19:40:23 +03002436 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 * integer with this base and length. Note that there's no
2438 * need to initialize z->ob_digit -- no slot is read up before
2439 * being stored into.
2440 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002441 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2442 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002443 /* The same exception as in _PyLong_New(). */
2444 PyErr_SetString(PyExc_OverflowError,
2445 "too many digits in integer");
2446 return NULL;
2447 }
2448 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 /* Uncomment next line to test exceedingly rare copy code */
2450 /* size_z = 1; */
2451 assert(size_z > 0);
2452 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002453 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002455 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* `convwidth` consecutive input digits are treated as a single
2459 * digit in base `convmultmax`.
2460 */
2461 convwidth = convwidth_base[base];
2462 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 /* Work ;-) */
2465 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002466 if (*str == '_') {
2467 str++;
2468 continue;
2469 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 /* grab up to convwidth digits from the input string */
2471 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002472 for (i = 1; i < convwidth && str != scan; ++str) {
2473 if (*str == '_') {
2474 continue;
2475 }
2476 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002478 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 assert(c < PyLong_BASE);
2480 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 convmult = convmultmax;
2483 /* Calculate the shift only if we couldn't get
2484 * convwidth digits.
2485 */
2486 if (i != convwidth) {
2487 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002488 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002490 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 /* Multiply z by convmult, and add c. */
2494 pz = z->ob_digit;
2495 pzstop = pz + Py_SIZE(z);
2496 for (; pz < pzstop; ++pz) {
2497 c += (twodigits)*pz * convmult;
2498 *pz = (digit)(c & PyLong_MASK);
2499 c >>= PyLong_SHIFT;
2500 }
2501 /* carry off the current end? */
2502 if (c) {
2503 assert(c < PyLong_BASE);
2504 if (Py_SIZE(z) < size_z) {
2505 *pz = (digit)c;
2506 ++Py_SIZE(z);
2507 }
2508 else {
2509 PyLongObject *tmp;
2510 /* Extremely rare. Get more space. */
2511 assert(Py_SIZE(z) == size_z);
2512 tmp = _PyLong_New(size_z + 1);
2513 if (tmp == NULL) {
2514 Py_DECREF(z);
2515 return NULL;
2516 }
2517 memcpy(tmp->ob_digit,
2518 z->ob_digit,
2519 sizeof(digit) * size_z);
2520 Py_DECREF(z);
2521 z = tmp;
2522 z->ob_digit[size_z] = (digit)c;
2523 ++size_z;
2524 }
2525 }
2526 }
2527 }
Brett Cannona721aba2016-09-09 14:57:09 -07002528 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002530 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 if (error_if_nonzero) {
2532 /* reset the base to 0, else the exception message
2533 doesn't make too much sense */
2534 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002535 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002537 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 /* there might still be other problems, therefore base
2539 remains zero here for the same reason */
2540 }
Brett Cannona721aba2016-09-09 14:57:09 -07002541 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002543 }
2544 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002546 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002547 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002549 }
2550 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002552 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002554 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002555 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002556 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002557 }
2558 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002559 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002560 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002561 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002562
Mark Dickinson22b20182010-05-10 21:27:53 +00002563 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002564 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002565 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002566 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 Py_XDECREF(z);
2568 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2569 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002570 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002572 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002574 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 base, strobj);
2576 Py_DECREF(strobj);
2577 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002578}
2579
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002580/* Since PyLong_FromString doesn't have a length parameter,
2581 * check here for possible NULs in the string.
2582 *
2583 * Reports an invalid literal as a bytes object.
2584 */
2585PyObject *
2586_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2587{
2588 PyObject *result, *strobj;
2589 char *end = NULL;
2590
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002591 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002592 if (end == NULL || (result != NULL && end == s + len))
2593 return result;
2594 Py_XDECREF(result);
2595 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2596 if (strobj != NULL) {
2597 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002598 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002599 base, strobj);
2600 Py_DECREF(strobj);
2601 }
2602 return NULL;
2603}
2604
Guido van Rossum9e896b32000-04-05 20:11:21 +00002605PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002606PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002607{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002608 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 if (unicode == NULL)
2610 return NULL;
2611 v = PyLong_FromUnicodeObject(unicode, base);
2612 Py_DECREF(unicode);
2613 return v;
2614}
2615
2616PyObject *
2617PyLong_FromUnicodeObject(PyObject *u, int base)
2618{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002619 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002620 const char *buffer;
2621 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002622 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002623
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002624 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002625 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002627 assert(PyUnicode_IS_ASCII(asciidig));
2628 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002629 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002630 assert(buffer != NULL);
2631
2632 result = PyLong_FromString(buffer, &end, base);
2633 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002634 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002635 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002637 Py_DECREF(asciidig);
2638 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002639 PyErr_Format(PyExc_ValueError,
2640 "invalid literal for int() with base %d: %.200R",
2641 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002642 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002643}
2644
Tim Peters9f688bf2000-07-07 15:53:28 +00002645/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002646static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002648static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002649
Serhiy Storchaka95949422013-08-27 19:40:23 +03002650/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002651
Guido van Rossume32e0141992-01-19 16:31:05 +00002652static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002653long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002655{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002656 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 if (size_b == 0) {
2660 PyErr_SetString(PyExc_ZeroDivisionError,
2661 "integer division or modulo by zero");
2662 return -1;
2663 }
2664 if (size_a < size_b ||
2665 (size_a == size_b &&
2666 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2667 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002668 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002669 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002670 return -1;
2671 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002672 Py_INCREF(_PyLong_Zero);
2673 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 return 0;
2675 }
2676 if (size_b == 1) {
2677 digit rem = 0;
2678 z = divrem1(a, b->ob_digit[0], &rem);
2679 if (z == NULL)
2680 return -1;
2681 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2682 if (*prem == NULL) {
2683 Py_DECREF(z);
2684 return -1;
2685 }
2686 }
2687 else {
2688 z = x_divrem(a, b, prem);
2689 if (z == NULL)
2690 return -1;
2691 }
2692 /* Set the signs.
2693 The quotient z has the sign of a*b;
2694 the remainder r has the sign of a,
2695 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002696 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2697 _PyLong_Negate(&z);
2698 if (z == NULL) {
2699 Py_CLEAR(*prem);
2700 return -1;
2701 }
2702 }
2703 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2704 _PyLong_Negate(prem);
2705 if (*prem == NULL) {
2706 Py_DECREF(z);
2707 Py_CLEAR(*prem);
2708 return -1;
2709 }
2710 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 *pdiv = maybe_small_long(z);
2712 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002713}
2714
Serhiy Storchaka95949422013-08-27 19:40:23 +03002715/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002716 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002717
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002718static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002719x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 PyLongObject *v, *w, *a;
2722 Py_ssize_t i, k, size_v, size_w;
2723 int d;
2724 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2725 twodigits vv;
2726 sdigit zhi;
2727 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2730 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2731 handle the special case when the initial estimate q for a quotient
2732 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2733 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002736 size_v = Py_ABS(Py_SIZE(v1));
2737 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2739 v = _PyLong_New(size_v+1);
2740 if (v == NULL) {
2741 *prem = NULL;
2742 return NULL;
2743 }
2744 w = _PyLong_New(size_w);
2745 if (w == NULL) {
2746 Py_DECREF(v);
2747 *prem = NULL;
2748 return NULL;
2749 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2752 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002753 d = PyLong_SHIFT - _Py_bit_length(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2755 assert(carry == 0);
2756 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2757 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2758 v->ob_digit[size_v] = carry;
2759 size_v++;
2760 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2763 at most (and usually exactly) k = size_v - size_w digits. */
2764 k = size_v - size_w;
2765 assert(k >= 0);
2766 a = _PyLong_New(k);
2767 if (a == NULL) {
2768 Py_DECREF(w);
2769 Py_DECREF(v);
2770 *prem = NULL;
2771 return NULL;
2772 }
2773 v0 = v->ob_digit;
2774 w0 = w->ob_digit;
2775 wm1 = w0[size_w-1];
2776 wm2 = w0[size_w-2];
2777 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2778 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2779 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002782 Py_DECREF(a);
2783 Py_DECREF(w);
2784 Py_DECREF(v);
2785 *prem = NULL;
2786 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002787 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 /* estimate quotient digit q; may overestimate by 1 (rare) */
2790 vtop = vk[size_w];
2791 assert(vtop <= wm1);
2792 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2793 q = (digit)(vv / wm1);
2794 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2795 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2796 | vk[size_w-2])) {
2797 --q;
2798 r += wm1;
2799 if (r >= PyLong_BASE)
2800 break;
2801 }
2802 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2805 zhi = 0;
2806 for (i = 0; i < size_w; ++i) {
2807 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2808 -PyLong_BASE * q <= z < PyLong_BASE */
2809 z = (sdigit)vk[i] + zhi -
2810 (stwodigits)q * (stwodigits)w0[i];
2811 vk[i] = (digit)z & PyLong_MASK;
2812 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002813 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 /* add w back if q was too large (this branch taken rarely) */
2817 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2818 if ((sdigit)vtop + zhi < 0) {
2819 carry = 0;
2820 for (i = 0; i < size_w; ++i) {
2821 carry += vk[i] + w0[i];
2822 vk[i] = carry & PyLong_MASK;
2823 carry >>= PyLong_SHIFT;
2824 }
2825 --q;
2826 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 /* store quotient digit */
2829 assert(q < PyLong_BASE);
2830 *--ak = q;
2831 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 /* unshift remainder; we reuse w to store the result */
2834 carry = v_rshift(w0, v0, size_w, d);
2835 assert(carry==0);
2836 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 *prem = long_normalize(w);
2839 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002840}
2841
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002842/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2843 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2844 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2845 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2846 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2847 -1.0. */
2848
2849/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2850#if DBL_MANT_DIG == 53
2851#define EXP2_DBL_MANT_DIG 9007199254740992.0
2852#else
2853#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2854#endif
2855
2856double
2857_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2860 /* See below for why x_digits is always large enough. */
2861 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2862 double dx;
2863 /* Correction term for round-half-to-even rounding. For a digit x,
2864 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2865 multiple of 4, rounding ties to a multiple of 8. */
2866 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002867
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002868 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 if (a_size == 0) {
2870 /* Special case for 0: significand 0.0, exponent 0. */
2871 *e = 0;
2872 return 0.0;
2873 }
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002874 a_bits = _Py_bit_length(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 /* The following is an overflow-free version of the check
2876 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2877 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2878 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2879 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002880 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2884 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 Number of digits needed for result: write // for floor division.
2887 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2896 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2899 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2900 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 in both cases.
2907 */
2908 if (a_bits <= DBL_MANT_DIG + 2) {
2909 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2910 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2911 x_size = 0;
2912 while (x_size < shift_digits)
2913 x_digits[x_size++] = 0;
2914 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2915 (int)shift_bits);
2916 x_size += a_size;
2917 x_digits[x_size++] = rem;
2918 }
2919 else {
2920 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2921 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2922 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2923 a_size - shift_digits, (int)shift_bits);
2924 x_size = a_size - shift_digits;
2925 /* For correct rounding below, we need the least significant
2926 bit of x to be 'sticky' for this shift: if any of the bits
2927 shifted out was nonzero, we set the least significant bit
2928 of x. */
2929 if (rem)
2930 x_digits[0] |= 1;
2931 else
2932 while (shift_digits > 0)
2933 if (a->ob_digit[--shift_digits]) {
2934 x_digits[0] |= 1;
2935 break;
2936 }
2937 }
Victor Stinner63941882011-09-29 00:42:28 +02002938 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 /* Round, and convert to double. */
2941 x_digits[0] += half_even_correction[x_digits[0] & 7];
2942 dx = x_digits[--x_size];
2943 while (x_size > 0)
2944 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 /* Rescale; make correction if result is 1.0. */
2947 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2948 if (dx == 1.0) {
2949 if (a_bits == PY_SSIZE_T_MAX)
2950 goto overflow;
2951 dx = 0.5;
2952 a_bits += 1;
2953 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 *e = a_bits;
2956 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002957
2958 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 /* exponent > PY_SSIZE_T_MAX */
2960 PyErr_SetString(PyExc_OverflowError,
2961 "huge integer: number of bits overflows a Py_ssize_t");
2962 *e = 0;
2963 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002964}
2965
Serhiy Storchaka95949422013-08-27 19:40:23 +03002966/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002967 using the round-half-to-even rule in the case of a tie. */
2968
2969double
2970PyLong_AsDouble(PyObject *v)
2971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 Py_ssize_t exponent;
2973 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002974
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002975 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 PyErr_BadInternalCall();
2977 return -1.0;
2978 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002979 if (!PyLong_Check(v)) {
2980 PyErr_SetString(PyExc_TypeError, "an integer is required");
2981 return -1.0;
2982 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002983 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002984 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002985 to double. This improves performance of FP/long operations
2986 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002987 */
2988 return (double)MEDIUM_VALUE((PyLongObject *)v);
2989 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2991 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2992 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002993 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 return -1.0;
2995 }
2996 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002997}
2998
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002999/* Methods */
3000
HongWeipeng42acb7b2019-09-18 23:10:15 +08003001/* if a < b, return a negative number
3002 if a == b, return 0
3003 if a > b, return a positive number */
3004
3005static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003006long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003007{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003008 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
3009 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003010 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08003011 sdigit diff = 0;
3012 while (--i >= 0) {
3013 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
3014 if (diff) {
3015 break;
3016 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003018 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003020 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003021}
3022
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003023static PyObject *
3024long_richcompare(PyObject *self, PyObject *other, int op)
3025{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003026 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 CHECK_BINOP(self, other);
3028 if (self == other)
3029 result = 0;
3030 else
3031 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003032 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003033}
3034
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003035static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003036long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003037{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003038 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 Py_ssize_t i;
3040 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 i = Py_SIZE(v);
3043 switch(i) {
3044 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3045 case 0: return 0;
3046 case 1: return v->ob_digit[0];
3047 }
3048 sign = 1;
3049 x = 0;
3050 if (i < 0) {
3051 sign = -1;
3052 i = -(i);
3053 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003055 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3056 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3057 _PyHASH_MODULUS.
3058
3059 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3060 amounts to a rotation of the bits of x. To see this, write
3061
3062 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3063
3064 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3065 PyLong_SHIFT bits of x (those that are shifted out of the
3066 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3067 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3068 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3069 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3070 congruent to y modulo _PyHASH_MODULUS. So
3071
3072 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3073
3074 The right-hand side is just the result of rotating the
3075 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3076 not all _PyHASH_BITS bits of x are 1s, the same is true
3077 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3078 the reduction of x*2**PyLong_SHIFT modulo
3079 _PyHASH_MODULUS. */
3080 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3081 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003083 if (x >= _PyHASH_MODULUS)
3084 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 }
3086 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003087 if (x == (Py_uhash_t)-1)
3088 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003089 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003090}
3091
3092
Serhiy Storchaka95949422013-08-27 19:40:23 +03003093/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003094
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003095static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003096x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003097{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003098 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 PyLongObject *z;
3100 Py_ssize_t i;
3101 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 /* Ensure a is the larger of the two: */
3104 if (size_a < size_b) {
3105 { PyLongObject *temp = a; a = b; b = temp; }
3106 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003107 size_a = size_b;
3108 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 }
3110 z = _PyLong_New(size_a+1);
3111 if (z == NULL)
3112 return NULL;
3113 for (i = 0; i < size_b; ++i) {
3114 carry += a->ob_digit[i] + b->ob_digit[i];
3115 z->ob_digit[i] = carry & PyLong_MASK;
3116 carry >>= PyLong_SHIFT;
3117 }
3118 for (; i < size_a; ++i) {
3119 carry += a->ob_digit[i];
3120 z->ob_digit[i] = carry & PyLong_MASK;
3121 carry >>= PyLong_SHIFT;
3122 }
3123 z->ob_digit[i] = carry;
3124 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003125}
3126
3127/* Subtract the absolute values of two integers. */
3128
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003129static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003130x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003131{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003132 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 PyLongObject *z;
3134 Py_ssize_t i;
3135 int sign = 1;
3136 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 /* Ensure a is the larger of the two: */
3139 if (size_a < size_b) {
3140 sign = -1;
3141 { PyLongObject *temp = a; a = b; b = temp; }
3142 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003143 size_a = size_b;
3144 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 }
3146 else if (size_a == size_b) {
3147 /* Find highest digit where a and b differ: */
3148 i = size_a;
3149 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3150 ;
3151 if (i < 0)
3152 return (PyLongObject *)PyLong_FromLong(0);
3153 if (a->ob_digit[i] < b->ob_digit[i]) {
3154 sign = -1;
3155 { PyLongObject *temp = a; a = b; b = temp; }
3156 }
3157 size_a = size_b = i+1;
3158 }
3159 z = _PyLong_New(size_a);
3160 if (z == NULL)
3161 return NULL;
3162 for (i = 0; i < size_b; ++i) {
3163 /* The following assumes unsigned arithmetic
3164 works module 2**N for some N>PyLong_SHIFT. */
3165 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3166 z->ob_digit[i] = borrow & PyLong_MASK;
3167 borrow >>= PyLong_SHIFT;
3168 borrow &= 1; /* Keep only one sign bit */
3169 }
3170 for (; i < size_a; ++i) {
3171 borrow = a->ob_digit[i] - borrow;
3172 z->ob_digit[i] = borrow & PyLong_MASK;
3173 borrow >>= PyLong_SHIFT;
3174 borrow &= 1; /* Keep only one sign bit */
3175 }
3176 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003177 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003178 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003179 }
HongWeipeng036fe852019-11-26 15:54:49 +08003180 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003181}
3182
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003183static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003184long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003189
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003190 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003191 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 }
3193 if (Py_SIZE(a) < 0) {
3194 if (Py_SIZE(b) < 0) {
3195 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003196 if (z != NULL) {
3197 /* x_add received at least one multiple-digit int,
3198 and thus z must be a multiple-digit int.
3199 That also means z is not an element of
3200 small_ints, so negating it in-place is safe. */
3201 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003203 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 }
3205 else
3206 z = x_sub(b, a);
3207 }
3208 else {
3209 if (Py_SIZE(b) < 0)
3210 z = x_sub(a, b);
3211 else
3212 z = x_add(a, b);
3213 }
3214 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003215}
3216
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003217static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003218long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003223
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003224 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003225 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 }
3227 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003228 if (Py_SIZE(b) < 0) {
3229 z = x_sub(b, a);
3230 }
3231 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003233 if (z != NULL) {
3234 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
3235 Py_SIZE(z) = -(Py_SIZE(z));
3236 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003237 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 }
3239 else {
3240 if (Py_SIZE(b) < 0)
3241 z = x_add(a, b);
3242 else
3243 z = x_sub(a, b);
3244 }
3245 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003246}
3247
Tim Peters5af4e6c2002-08-12 02:31:19 +00003248/* Grade school multiplication, ignoring the signs.
3249 * Returns the absolute value of the product, or NULL if error.
3250 */
3251static PyLongObject *
3252x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003255 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3256 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 z = _PyLong_New(size_a + size_b);
3260 if (z == NULL)
3261 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3264 if (a == b) {
3265 /* Efficient squaring per HAC, Algorithm 14.16:
3266 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3267 * Gives slightly less than a 2x speedup when a == b,
3268 * via exploiting that each entry in the multiplication
3269 * pyramid appears twice (except for the size_a squares).
3270 */
3271 for (i = 0; i < size_a; ++i) {
3272 twodigits carry;
3273 twodigits f = a->ob_digit[i];
3274 digit *pz = z->ob_digit + (i << 1);
3275 digit *pa = a->ob_digit + i + 1;
3276 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003279 Py_DECREF(z);
3280 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003281 });
Tim Peters0973b992004-08-29 22:16:50 +00003282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 carry = *pz + f * f;
3284 *pz++ = (digit)(carry & PyLong_MASK);
3285 carry >>= PyLong_SHIFT;
3286 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 /* Now f is added in twice in each column of the
3289 * pyramid it appears. Same as adding f<<1 once.
3290 */
3291 f <<= 1;
3292 while (pa < paend) {
3293 carry += *pz + *pa++ * f;
3294 *pz++ = (digit)(carry & PyLong_MASK);
3295 carry >>= PyLong_SHIFT;
3296 assert(carry <= (PyLong_MASK << 1));
3297 }
3298 if (carry) {
3299 carry += *pz;
3300 *pz++ = (digit)(carry & PyLong_MASK);
3301 carry >>= PyLong_SHIFT;
3302 }
3303 if (carry)
3304 *pz += (digit)(carry & PyLong_MASK);
3305 assert((carry >> PyLong_SHIFT) == 0);
3306 }
3307 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003308 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 for (i = 0; i < size_a; ++i) {
3310 twodigits carry = 0;
3311 twodigits f = a->ob_digit[i];
3312 digit *pz = z->ob_digit + i;
3313 digit *pb = b->ob_digit;
3314 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003317 Py_DECREF(z);
3318 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003319 });
Tim Peters0973b992004-08-29 22:16:50 +00003320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 while (pb < pbend) {
3322 carry += *pz + *pb++ * f;
3323 *pz++ = (digit)(carry & PyLong_MASK);
3324 carry >>= PyLong_SHIFT;
3325 assert(carry <= PyLong_MASK);
3326 }
3327 if (carry)
3328 *pz += (digit)(carry & PyLong_MASK);
3329 assert((carry >> PyLong_SHIFT) == 0);
3330 }
3331 }
3332 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003333}
3334
3335/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003336 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003337 split, and sets low and high such that abs(n) == (high << size) + low,
3338 viewing the shift as being by digits. The sign bit is ignored, and
3339 the return values are >= 0.
3340 Returns 0 on success, -1 on failure.
3341*/
3342static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003343kmul_split(PyLongObject *n,
3344 Py_ssize_t size,
3345 PyLongObject **high,
3346 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 PyLongObject *hi, *lo;
3349 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003350 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003351
Victor Stinner640c35c2013-06-04 23:14:37 +02003352 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 if ((hi = _PyLong_New(size_hi)) == NULL)
3356 return -1;
3357 if ((lo = _PyLong_New(size_lo)) == NULL) {
3358 Py_DECREF(hi);
3359 return -1;
3360 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3363 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 *high = long_normalize(hi);
3366 *low = long_normalize(lo);
3367 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003368}
3369
Tim Peters60004642002-08-12 22:01:34 +00003370static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3371
Tim Peters5af4e6c2002-08-12 02:31:19 +00003372/* Karatsuba multiplication. Ignores the input signs, and returns the
3373 * absolute value of the product (or NULL if error).
3374 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3375 */
3376static PyLongObject *
3377k_mul(PyLongObject *a, PyLongObject *b)
3378{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003379 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3380 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 PyLongObject *ah = NULL;
3382 PyLongObject *al = NULL;
3383 PyLongObject *bh = NULL;
3384 PyLongObject *bl = NULL;
3385 PyLongObject *ret = NULL;
3386 PyLongObject *t1, *t2, *t3;
3387 Py_ssize_t shift; /* the number of digits we split off */
3388 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3391 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3392 * Then the original product is
3393 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3394 * By picking X to be a power of 2, "*X" is just shifting, and it's
3395 * been reduced to 3 multiplies on numbers half the size.
3396 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 /* We want to split based on the larger number; fiddle so that b
3399 * is largest.
3400 */
3401 if (asize > bsize) {
3402 t1 = a;
3403 a = b;
3404 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 i = asize;
3407 asize = bsize;
3408 bsize = i;
3409 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 /* Use gradeschool math when either number is too small. */
3412 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3413 if (asize <= i) {
3414 if (asize == 0)
3415 return (PyLongObject *)PyLong_FromLong(0);
3416 else
3417 return x_mul(a, b);
3418 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 /* If a is small compared to b, splitting on b gives a degenerate
3421 * case with ah==0, and Karatsuba may be (even much) less efficient
3422 * than "grade school" then. However, we can still win, by viewing
3423 * b as a string of "big digits", each of width a->ob_size. That
3424 * leads to a sequence of balanced calls to k_mul.
3425 */
3426 if (2 * asize <= bsize)
3427 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 /* Split a & b into hi & lo pieces. */
3430 shift = bsize >> 1;
3431 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3432 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 if (a == b) {
3435 bh = ah;
3436 bl = al;
3437 Py_INCREF(bh);
3438 Py_INCREF(bl);
3439 }
3440 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 /* The plan:
3443 * 1. Allocate result space (asize + bsize digits: that's always
3444 * enough).
3445 * 2. Compute ah*bh, and copy into result at 2*shift.
3446 * 3. Compute al*bl, and copy into result at 0. Note that this
3447 * can't overlap with #2.
3448 * 4. Subtract al*bl from the result, starting at shift. This may
3449 * underflow (borrow out of the high digit), but we don't care:
3450 * we're effectively doing unsigned arithmetic mod
3451 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3452 * borrows and carries out of the high digit can be ignored.
3453 * 5. Subtract ah*bh from the result, starting at shift.
3454 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3455 * at shift.
3456 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 /* 1. Allocate result space. */
3459 ret = _PyLong_New(asize + bsize);
3460 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003461#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 /* Fill with trash, to catch reference to uninitialized digits. */
3463 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003464#endif
Tim Peters44121a62002-08-12 06:17:58 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3467 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3468 assert(Py_SIZE(t1) >= 0);
3469 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3470 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3471 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 /* Zero-out the digits higher than the ah*bh copy. */
3474 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3475 if (i)
3476 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3477 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 /* 3. t2 <- al*bl, and copy into the low digits. */
3480 if ((t2 = k_mul(al, bl)) == NULL) {
3481 Py_DECREF(t1);
3482 goto fail;
3483 }
3484 assert(Py_SIZE(t2) >= 0);
3485 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3486 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 /* Zero out remaining digits. */
3489 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3490 if (i)
3491 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3494 * because it's fresher in cache.
3495 */
3496 i = Py_SIZE(ret) - shift; /* # digits after shift */
3497 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3498 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3501 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3504 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3505 Py_DECREF(ah);
3506 Py_DECREF(al);
3507 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 if (a == b) {
3510 t2 = t1;
3511 Py_INCREF(t2);
3512 }
3513 else if ((t2 = x_add(bh, bl)) == NULL) {
3514 Py_DECREF(t1);
3515 goto fail;
3516 }
3517 Py_DECREF(bh);
3518 Py_DECREF(bl);
3519 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 t3 = k_mul(t1, t2);
3522 Py_DECREF(t1);
3523 Py_DECREF(t2);
3524 if (t3 == NULL) goto fail;
3525 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 /* Add t3. It's not obvious why we can't run out of room here.
3528 * See the (*) comment after this function.
3529 */
3530 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3531 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003534
Mark Dickinson22b20182010-05-10 21:27:53 +00003535 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 Py_XDECREF(ret);
3537 Py_XDECREF(ah);
3538 Py_XDECREF(al);
3539 Py_XDECREF(bh);
3540 Py_XDECREF(bl);
3541 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003542}
3543
Tim Petersd6974a52002-08-13 20:37:51 +00003544/* (*) Why adding t3 can't "run out of room" above.
3545
Tim Petersab86c2b2002-08-15 20:06:00 +00003546Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3547to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003548
Tim Petersab86c2b2002-08-15 20:06:00 +000035491. For any integer i, i = c(i/2) + f(i/2). In particular,
3550 bsize = c(bsize/2) + f(bsize/2).
35512. shift = f(bsize/2)
35523. asize <= bsize
35534. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3554 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003555
Tim Petersab86c2b2002-08-15 20:06:00 +00003556We allocated asize + bsize result digits, and add t3 into them at an offset
3557of shift. This leaves asize+bsize-shift allocated digit positions for t3
3558to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3559asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003560
Tim Petersab86c2b2002-08-15 20:06:00 +00003561bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3562at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003563
Tim Petersab86c2b2002-08-15 20:06:00 +00003564If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3565digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3566most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003567
Tim Petersab86c2b2002-08-15 20:06:00 +00003568The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003569
Tim Petersab86c2b2002-08-15 20:06:00 +00003570 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003571
Tim Petersab86c2b2002-08-15 20:06:00 +00003572and we have asize + c(bsize/2) available digit positions. We need to show
3573this is always enough. An instance of c(bsize/2) cancels out in both, so
3574the question reduces to whether asize digits is enough to hold
3575(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3576then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3577asize 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 +00003578digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003579asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003580c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3581is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3582bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003583
Tim Peters48d52c02002-08-14 17:07:32 +00003584Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3585clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3586ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003587*/
3588
Tim Peters60004642002-08-12 22:01:34 +00003589/* b has at least twice the digits of a, and a is big enough that Karatsuba
3590 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3591 * of slices, each with a->ob_size digits, and multiply the slices by a,
3592 * one at a time. This gives k_mul balanced inputs to work with, and is
3593 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003594 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003595 * single-width slice overlap between successive partial sums).
3596 */
3597static PyLongObject *
3598k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3599{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003600 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3601 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 Py_ssize_t nbdone; /* # of b digits already multiplied */
3603 PyLongObject *ret;
3604 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 assert(asize > KARATSUBA_CUTOFF);
3607 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 /* Allocate result space, and zero it out. */
3610 ret = _PyLong_New(asize + bsize);
3611 if (ret == NULL)
3612 return NULL;
3613 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 /* Successive slices of b are copied into bslice. */
3616 bslice = _PyLong_New(asize);
3617 if (bslice == NULL)
3618 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 nbdone = 0;
3621 while (bsize > 0) {
3622 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003623 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 /* Multiply the next slice of b by a. */
3626 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3627 nbtouse * sizeof(digit));
3628 Py_SIZE(bslice) = nbtouse;
3629 product = k_mul(a, bslice);
3630 if (product == NULL)
3631 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 /* Add into result. */
3634 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3635 product->ob_digit, Py_SIZE(product));
3636 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 bsize -= nbtouse;
3639 nbdone += nbtouse;
3640 }
Tim Peters60004642002-08-12 22:01:34 +00003641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 Py_DECREF(bslice);
3643 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003644
Mark Dickinson22b20182010-05-10 21:27:53 +00003645 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 Py_DECREF(ret);
3647 Py_XDECREF(bslice);
3648 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003649}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003650
3651static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003652long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003659 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003661 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 z = k_mul(a, b);
3665 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003666 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3667 _PyLong_Negate(&z);
3668 if (z == NULL)
3669 return NULL;
3670 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003672}
3673
Yury Selivanove0b23092016-02-11 10:26:27 -05003674/* Fast modulo division for single-digit longs. */
3675static PyObject *
3676fast_mod(PyLongObject *a, PyLongObject *b)
3677{
3678 sdigit left = a->ob_digit[0];
3679 sdigit right = b->ob_digit[0];
3680 sdigit mod;
3681
3682 assert(Py_ABS(Py_SIZE(a)) == 1);
3683 assert(Py_ABS(Py_SIZE(b)) == 1);
3684
3685 if (Py_SIZE(a) == Py_SIZE(b)) {
3686 /* 'a' and 'b' have the same sign. */
3687 mod = left % right;
3688 }
3689 else {
3690 /* Either 'a' or 'b' is negative. */
3691 mod = right - 1 - (left - 1) % right;
3692 }
3693
Victor Stinnerf963c132016-03-23 18:36:54 +01003694 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003695}
3696
3697/* Fast floor division for single-digit longs. */
3698static PyObject *
3699fast_floor_div(PyLongObject *a, PyLongObject *b)
3700{
3701 sdigit left = a->ob_digit[0];
3702 sdigit right = b->ob_digit[0];
3703 sdigit div;
3704
3705 assert(Py_ABS(Py_SIZE(a)) == 1);
3706 assert(Py_ABS(Py_SIZE(b)) == 1);
3707
3708 if (Py_SIZE(a) == Py_SIZE(b)) {
3709 /* 'a' and 'b' have the same sign. */
3710 div = left / right;
3711 }
3712 else {
3713 /* Either 'a' or 'b' is negative. */
3714 div = -1 - (left - 1) / right;
3715 }
3716
3717 return PyLong_FromLong(div);
3718}
3719
Guido van Rossume32e0141992-01-19 16:31:05 +00003720/* The / and % operators are now defined in terms of divmod().
3721 The expression a mod b has the value a - b*floor(a/b).
3722 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003723 |a| by |b|, with the sign of a. This is also expressed
3724 as a - b*trunc(a/b), if trunc truncates towards zero.
3725 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 a b a rem b a mod b
3727 13 10 3 3
3728 -13 10 -3 7
3729 13 -10 3 -7
3730 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003731 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003732 have different signs. We then subtract one from the 'div'
3733 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003734
Tim Peters47e52ee2004-08-30 02:44:38 +00003735/* Compute
3736 * *pdiv, *pmod = divmod(v, w)
3737 * NULL can be passed for pdiv or pmod, in which case that part of
3738 * the result is simply thrown away. The caller owns a reference to
3739 * each of these it requests (does not pass NULL for).
3740 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003741static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003742l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003746
Yury Selivanove0b23092016-02-11 10:26:27 -05003747 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3748 /* Fast path for single-digit longs */
3749 div = NULL;
3750 if (pdiv != NULL) {
3751 div = (PyLongObject *)fast_floor_div(v, w);
3752 if (div == NULL) {
3753 return -1;
3754 }
3755 }
3756 if (pmod != NULL) {
3757 mod = (PyLongObject *)fast_mod(v, w);
3758 if (mod == NULL) {
3759 Py_XDECREF(div);
3760 return -1;
3761 }
3762 *pmod = mod;
3763 }
3764 if (pdiv != NULL) {
3765 /* We only want to set `*pdiv` when `*pmod` is
3766 set successfully. */
3767 *pdiv = div;
3768 }
3769 return 0;
3770 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 if (long_divrem(v, w, &div, &mod) < 0)
3772 return -1;
3773 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3774 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3775 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 temp = (PyLongObject *) long_add(mod, w);
3777 Py_DECREF(mod);
3778 mod = temp;
3779 if (mod == NULL) {
3780 Py_DECREF(div);
3781 return -1;
3782 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003783 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3784 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 Py_DECREF(mod);
3786 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 return -1;
3788 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 Py_DECREF(div);
3790 div = temp;
3791 }
3792 if (pdiv != NULL)
3793 *pdiv = div;
3794 else
3795 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 if (pmod != NULL)
3798 *pmod = mod;
3799 else
3800 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003803}
3804
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003805static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003806long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003811
3812 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3813 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3814 }
3815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3817 div = NULL;
3818 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003819}
3820
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003821/* PyLong/PyLong -> float, with correctly rounded result. */
3822
3823#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3824#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3825
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003826static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003827long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 PyLongObject *a, *b, *x;
3830 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3831 digit mask, low;
3832 int inexact, negate, a_is_small, b_is_small;
3833 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 CHECK_BINOP(v, w);
3836 a = (PyLongObject *)v;
3837 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 /*
3840 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3843 1. choose a suitable integer 'shift'
3844 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3845 3. adjust x for correct rounding
3846 4. convert x to a double dx with the same value
3847 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3852 returns either 0.0 or -0.0, depending on the sign of b. For a and
3853 b both nonzero, ignore signs of a and b, and add the sign back in
3854 at the end. Now write a_bits and b_bits for the bit lengths of a
3855 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3856 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3861 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3862 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3863 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 1. The integer 'shift' is chosen so that x has the right number of
3868 bits for a double, plus two or three extra bits that will be used
3869 in the rounding decisions. Writing a_bits and b_bits for the
3870 number of significant bits in a and b respectively, a
3871 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 This is fine in the usual case, but if a/b is smaller than the
3876 smallest normal float then it can lead to double rounding on an
3877 IEEE 754 platform, giving incorrectly rounded results. So we
3878 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 2. The quantity x is computed by first shifting a (left -shift bits
3883 if shift <= 0, right shift bits if shift > 0) and then dividing by
3884 b. For both the shift and the division, we keep track of whether
3885 the result is inexact, in a flag 'inexact'; this information is
3886 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 With the choice of shift above, together with our assumption that
3889 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3890 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3893 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 For float representability, we need x/2**extra_bits <
3898 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3899 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 To round, we just modify the bottom digit of x in-place; this can
3904 end up giving a digit with value > PyLONG_MASK, but that's not a
3905 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 With the original choices for shift above, extra_bits will always
3908 be 2 or 3. Then rounding under the round-half-to-even rule, we
3909 round up iff the most significant of the extra bits is 1, and
3910 either: (a) the computation of x in step 2 had an inexact result,
3911 or (b) at least one other of the extra bits is 1, or (c) the least
3912 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 4. Conversion to a double is straightforward; all floating-point
3915 operations involved in the conversion are exact, so there's no
3916 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3919 The result will always be exactly representable as a double, except
3920 in the case that it overflows. To avoid dependence on the exact
3921 behaviour of ldexp on overflow, we check for overflow before
3922 applying ldexp. The result of ldexp is adjusted for sign before
3923 returning.
3924 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003927 a_size = Py_ABS(Py_SIZE(a));
3928 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3930 if (b_size == 0) {
3931 PyErr_SetString(PyExc_ZeroDivisionError,
3932 "division by zero");
3933 goto error;
3934 }
3935 if (a_size == 0)
3936 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 /* Fast path for a and b small (exactly representable in a double).
3939 Relies on floating-point division being correctly rounded; results
3940 may be subject to double rounding on x86 machines that operate with
3941 the x87 FPU set to 64-bit precision. */
3942 a_is_small = a_size <= MANT_DIG_DIGITS ||
3943 (a_size == MANT_DIG_DIGITS+1 &&
3944 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3945 b_is_small = b_size <= MANT_DIG_DIGITS ||
3946 (b_size == MANT_DIG_DIGITS+1 &&
3947 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3948 if (a_is_small && b_is_small) {
3949 double da, db;
3950 da = a->ob_digit[--a_size];
3951 while (a_size > 0)
3952 da = da * PyLong_BASE + a->ob_digit[--a_size];
3953 db = b->ob_digit[--b_size];
3954 while (b_size > 0)
3955 db = db * PyLong_BASE + b->ob_digit[--b_size];
3956 result = da / db;
3957 goto success;
3958 }
Tim Peterse2a60002001-09-04 06:17:36 +00003959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 /* Catch obvious cases of underflow and overflow */
3961 diff = a_size - b_size;
3962 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3963 /* Extreme overflow */
3964 goto overflow;
3965 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3966 /* Extreme underflow */
3967 goto underflow_or_zero;
3968 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01003969 diff = diff * PyLong_SHIFT + _Py_bit_length(a->ob_digit[a_size - 1]) -
3970 _Py_bit_length(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 /* Now diff = a_bits - b_bits. */
3972 if (diff > DBL_MAX_EXP)
3973 goto overflow;
3974 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3975 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003978 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 /* x = abs(a * 2**-shift) */
3983 if (shift <= 0) {
3984 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3985 digit rem;
3986 /* x = a << -shift */
3987 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3988 /* In practice, it's probably impossible to end up
3989 here. Both a and b would have to be enormous,
3990 using close to SIZE_T_MAX bytes of memory each. */
3991 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003992 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 goto error;
3994 }
3995 x = _PyLong_New(a_size + shift_digits + 1);
3996 if (x == NULL)
3997 goto error;
3998 for (i = 0; i < shift_digits; i++)
3999 x->ob_digit[i] = 0;
4000 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
4001 a_size, -shift % PyLong_SHIFT);
4002 x->ob_digit[a_size + shift_digits] = rem;
4003 }
4004 else {
4005 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
4006 digit rem;
4007 /* x = a >> shift */
4008 assert(a_size >= shift_digits);
4009 x = _PyLong_New(a_size - shift_digits);
4010 if (x == NULL)
4011 goto error;
4012 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4013 a_size - shift_digits, shift % PyLong_SHIFT);
4014 /* set inexact if any of the bits shifted out is nonzero */
4015 if (rem)
4016 inexact = 1;
4017 while (!inexact && shift_digits > 0)
4018 if (a->ob_digit[--shift_digits])
4019 inexact = 1;
4020 }
4021 long_normalize(x);
4022 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4025 reference to x, so it's safe to modify it in-place. */
4026 if (b_size == 1) {
4027 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4028 b->ob_digit[0]);
4029 long_normalize(x);
4030 if (rem)
4031 inexact = 1;
4032 }
4033 else {
4034 PyLongObject *div, *rem;
4035 div = x_divrem(x, b, &rem);
4036 Py_DECREF(x);
4037 x = div;
4038 if (x == NULL)
4039 goto error;
4040 if (Py_SIZE(rem))
4041 inexact = 1;
4042 Py_DECREF(rem);
4043 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004044 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004046 x_bits = (x_size-1)*PyLong_SHIFT+_Py_bit_length(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004049 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 /* Round by directly modifying the low digit of x. */
4053 mask = (digit)1 << (extra_bits - 1);
4054 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004055 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004057 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 /* Convert x to a double dx; the conversion is exact. */
4060 dx = x->ob_digit[--x_size];
4061 while (x_size > 0)
4062 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4063 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 /* Check whether ldexp result will overflow a double. */
4066 if (shift + x_bits >= DBL_MAX_EXP &&
4067 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4068 goto overflow;
4069 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004070
4071 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004073
4074 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004075 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004076
4077 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 PyErr_SetString(PyExc_OverflowError,
4079 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004080 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004082}
4083
4084static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004085long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 CHECK_BINOP(a, b);
4090
Yury Selivanove0b23092016-02-11 10:26:27 -05004091 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4092 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4093 }
4094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4096 mod = NULL;
4097 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004098}
4099
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004100static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004101long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 PyLongObject *div, *mod;
4104 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4109 return NULL;
4110 }
4111 z = PyTuple_New(2);
4112 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004113 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4114 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 }
4116 else {
4117 Py_DECREF(div);
4118 Py_DECREF(mod);
4119 }
4120 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004121}
4122
Mark Dickinsonc5299672019-06-02 10:24:06 +01004123
4124/* Compute an inverse to a modulo n, or raise ValueError if a is not
4125 invertible modulo n. Assumes n is positive. The inverse returned
4126 is whatever falls out of the extended Euclidean algorithm: it may
4127 be either positive or negative, but will be smaller than n in
4128 absolute value.
4129
4130 Pure Python equivalent for long_invmod:
4131
4132 def invmod(a, n):
4133 b, c = 1, 0
4134 while n:
4135 q, r = divmod(a, n)
4136 a, b, c, n = n, c, b - q*c, r
4137
4138 # at this point a is the gcd of the original inputs
4139 if a == 1:
4140 return b
4141 raise ValueError("Not invertible")
4142*/
4143
4144static PyLongObject *
4145long_invmod(PyLongObject *a, PyLongObject *n)
4146{
4147 PyLongObject *b, *c;
4148
4149 /* Should only ever be called for positive n */
4150 assert(Py_SIZE(n) > 0);
4151
4152 b = (PyLongObject *)PyLong_FromLong(1L);
4153 if (b == NULL) {
4154 return NULL;
4155 }
4156 c = (PyLongObject *)PyLong_FromLong(0L);
4157 if (c == NULL) {
4158 Py_DECREF(b);
4159 return NULL;
4160 }
4161 Py_INCREF(a);
4162 Py_INCREF(n);
4163
4164 /* references now owned: a, b, c, n */
4165 while (Py_SIZE(n) != 0) {
4166 PyLongObject *q, *r, *s, *t;
4167
4168 if (l_divmod(a, n, &q, &r) == -1) {
4169 goto Error;
4170 }
4171 Py_DECREF(a);
4172 a = n;
4173 n = r;
4174 t = (PyLongObject *)long_mul(q, c);
4175 Py_DECREF(q);
4176 if (t == NULL) {
4177 goto Error;
4178 }
4179 s = (PyLongObject *)long_sub(b, t);
4180 Py_DECREF(t);
4181 if (s == NULL) {
4182 goto Error;
4183 }
4184 Py_DECREF(b);
4185 b = c;
4186 c = s;
4187 }
4188 /* references now owned: a, b, c, n */
4189
4190 Py_DECREF(c);
4191 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004192 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004193 /* a != 1; we don't have an inverse. */
4194 Py_DECREF(a);
4195 Py_DECREF(b);
4196 PyErr_SetString(PyExc_ValueError,
4197 "base is not invertible for the given modulus");
4198 return NULL;
4199 }
4200 else {
4201 /* a == 1; b gives an inverse modulo n */
4202 Py_DECREF(a);
4203 return b;
4204 }
4205
4206 Error:
4207 Py_DECREF(a);
4208 Py_DECREF(b);
4209 Py_DECREF(c);
4210 Py_DECREF(n);
4211 return NULL;
4212}
4213
4214
Tim Peters47e52ee2004-08-30 02:44:38 +00004215/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004216static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004217long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4220 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 PyLongObject *z = NULL; /* accumulated result */
4223 Py_ssize_t i, j, k; /* counters */
4224 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 /* 5-ary values. If the exponent is large enough, table is
4227 * precomputed so that table[i] == a**i % c for i in range(32).
4228 */
4229 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4230 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 /* a, b, c = v, w, x */
4233 CHECK_BINOP(v, w);
4234 a = (PyLongObject*)v; Py_INCREF(a);
4235 b = (PyLongObject*)w; Py_INCREF(b);
4236 if (PyLong_Check(x)) {
4237 c = (PyLongObject *)x;
4238 Py_INCREF(x);
4239 }
4240 else if (x == Py_None)
4241 c = NULL;
4242 else {
4243 Py_DECREF(a);
4244 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004245 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 }
Tim Peters4c483c42001-09-05 06:24:58 +00004247
Mark Dickinsonc5299672019-06-02 10:24:06 +01004248 if (Py_SIZE(b) < 0 && c == NULL) {
4249 /* if exponent is negative and there's no modulus:
4250 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 that this calls float_pow() which converts its
4252 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004253 Py_DECREF(a);
4254 Py_DECREF(b);
4255 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 if (c) {
4259 /* if modulus == 0:
4260 raise ValueError() */
4261 if (Py_SIZE(c) == 0) {
4262 PyErr_SetString(PyExc_ValueError,
4263 "pow() 3rd argument cannot be 0");
4264 goto Error;
4265 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 /* if modulus < 0:
4268 negativeOutput = True
4269 modulus = -modulus */
4270 if (Py_SIZE(c) < 0) {
4271 negativeOutput = 1;
4272 temp = (PyLongObject *)_PyLong_Copy(c);
4273 if (temp == NULL)
4274 goto Error;
4275 Py_DECREF(c);
4276 c = temp;
4277 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004278 _PyLong_Negate(&c);
4279 if (c == NULL)
4280 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 /* if modulus == 1:
4284 return 0 */
4285 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4286 z = (PyLongObject *)PyLong_FromLong(0L);
4287 goto Done;
4288 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004289
Mark Dickinsonc5299672019-06-02 10:24:06 +01004290 /* if exponent is negative, negate the exponent and
4291 replace the base with a modular inverse */
4292 if (Py_SIZE(b) < 0) {
4293 temp = (PyLongObject *)_PyLong_Copy(b);
4294 if (temp == NULL)
4295 goto Error;
4296 Py_DECREF(b);
4297 b = temp;
4298 temp = NULL;
4299 _PyLong_Negate(&b);
4300 if (b == NULL)
4301 goto Error;
4302
4303 temp = long_invmod(a, c);
4304 if (temp == NULL)
4305 goto Error;
4306 Py_DECREF(a);
4307 a = temp;
4308 }
4309
Tim Peters81a93152013-10-05 16:53:52 -05004310 /* Reduce base by modulus in some cases:
4311 1. If base < 0. Forcing the base non-negative makes things easier.
4312 2. If base is obviously larger than the modulus. The "small
4313 exponent" case later can multiply directly by base repeatedly,
4314 while the "large exponent" case multiplies directly by base 31
4315 times. It can be unboundedly faster to multiply by
4316 base % modulus instead.
4317 We could _always_ do this reduction, but l_divmod() isn't cheap,
4318 so we only do it when it buys something. */
4319 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 if (l_divmod(a, c, NULL, &temp) < 0)
4321 goto Error;
4322 Py_DECREF(a);
4323 a = temp;
4324 temp = NULL;
4325 }
4326 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 /* At this point a, b, and c are guaranteed non-negative UNLESS
4329 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 z = (PyLongObject *)PyLong_FromLong(1L);
4332 if (z == NULL)
4333 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 /* Perform a modular reduction, X = X % c, but leave X alone if c
4336 * is NULL.
4337 */
4338#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004339 do { \
4340 if (c != NULL) { \
4341 if (l_divmod(X, c, NULL, &temp) < 0) \
4342 goto Error; \
4343 Py_XDECREF(X); \
4344 X = temp; \
4345 temp = NULL; \
4346 } \
4347 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 /* Multiply two values, then reduce the result:
4350 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004351#define MULT(X, Y, result) \
4352 do { \
4353 temp = (PyLongObject *)long_mul(X, Y); \
4354 if (temp == NULL) \
4355 goto Error; \
4356 Py_XDECREF(result); \
4357 result = temp; \
4358 temp = NULL; \
4359 REDUCE(result); \
4360 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4363 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4364 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4365 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4366 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004369 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004371 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 }
4373 }
4374 }
4375 else {
4376 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4377 Py_INCREF(z); /* still holds 1L */
4378 table[0] = z;
4379 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004380 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4383 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4386 const int index = (bi >> j) & 0x1f;
4387 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004388 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004390 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 }
4392 }
4393 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 if (negativeOutput && (Py_SIZE(z) != 0)) {
4396 temp = (PyLongObject *)long_sub(z, c);
4397 if (temp == NULL)
4398 goto Error;
4399 Py_DECREF(z);
4400 z = temp;
4401 temp = NULL;
4402 }
4403 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004404
Mark Dickinson22b20182010-05-10 21:27:53 +00004405 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004406 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004408 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004409 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4410 for (i = 0; i < 32; ++i)
4411 Py_XDECREF(table[i]);
4412 }
4413 Py_DECREF(a);
4414 Py_DECREF(b);
4415 Py_XDECREF(c);
4416 Py_XDECREF(temp);
4417 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004418}
4419
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004420static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004421long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 /* Implement ~x as -(x+1) */
4424 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004425 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004427 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 if (x == NULL)
4429 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004430 _PyLong_Negate(&x);
4431 /* No need for maybe_small_long here, since any small
4432 longs will have been caught in the Py_SIZE <= 1 fast path. */
4433 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004434}
4435
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004436static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004437long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004440 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 return PyLong_FromLong(-MEDIUM_VALUE(v));
4442 z = (PyLongObject *)_PyLong_Copy(v);
4443 if (z != NULL)
4444 Py_SIZE(z) = -(Py_SIZE(v));
4445 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004446}
4447
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004448static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004449long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 if (Py_SIZE(v) < 0)
4452 return long_neg(v);
4453 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004454 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004455}
4456
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004457static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004458long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004461}
4462
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004463/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4464static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004465divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004466{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004467 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004468 assert(Py_SIZE(shiftby) >= 0);
4469 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4470 if (lshiftby >= 0) {
4471 *wordshift = lshiftby / PyLong_SHIFT;
4472 *remshift = lshiftby % PyLong_SHIFT;
4473 return 0;
4474 }
4475 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4476 be that PyLong_AsSsize_t raised an OverflowError. */
4477 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4478 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004479 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004480 if (wordshift_obj == NULL) {
4481 return -1;
4482 }
4483 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4484 Py_DECREF(wordshift_obj);
4485 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4486 return 0;
4487 }
4488 PyErr_Clear();
4489 /* Clip the value. With such large wordshift the right shift
4490 returns 0 and the left shift raises an error in _PyLong_New(). */
4491 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4492 *remshift = 0;
4493 return 0;
4494}
4495
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004496static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004497long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004500 Py_ssize_t newsize, hishift, i, j;
4501 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 if (Py_SIZE(a) < 0) {
4504 /* Right shifting negative numbers is harder */
4505 PyLongObject *a1, *a2;
4506 a1 = (PyLongObject *) long_invert(a);
4507 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004508 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004509 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 Py_DECREF(a1);
4511 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004512 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 z = (PyLongObject *) long_invert(a2);
4514 Py_DECREF(a2);
4515 }
4516 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004517 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 if (newsize <= 0)
4519 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004520 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 lomask = ((digit)1 << hishift) - 1;
4522 himask = PyLong_MASK ^ lomask;
4523 z = _PyLong_New(newsize);
4524 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004525 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004527 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004529 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004531 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004533 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004534}
4535
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004536static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004537long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004538{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004539 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004540 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004543
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004544 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004546 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004548 if (Py_SIZE(a) == 0) {
4549 return PyLong_FromLong(0);
4550 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004551 if (divmod_shift(b, &wordshift, &remshift) < 0)
4552 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004553 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4554}
4555
4556/* Return a >> shiftby. */
4557PyObject *
4558_PyLong_Rshift(PyObject *a, size_t shiftby)
4559{
4560 Py_ssize_t wordshift;
4561 digit remshift;
4562
4563 assert(PyLong_Check(a));
4564 if (Py_SIZE(a) == 0) {
4565 return PyLong_FromLong(0);
4566 }
4567 wordshift = shiftby / PyLong_SHIFT;
4568 remshift = shiftby % PyLong_SHIFT;
4569 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4570}
4571
4572static PyObject *
4573long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4574{
4575 /* This version due to Tim Peters */
4576 PyLongObject *z = NULL;
4577 Py_ssize_t oldsize, newsize, i, j;
4578 twodigits accum;
4579
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004580 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 newsize = oldsize + wordshift;
4582 if (remshift)
4583 ++newsize;
4584 z = _PyLong_New(newsize);
4585 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004586 return NULL;
4587 if (Py_SIZE(a) < 0) {
4588 assert(Py_REFCNT(z) == 1);
4589 Py_SIZE(z) = -Py_SIZE(z);
4590 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 for (i = 0; i < wordshift; i++)
4592 z->ob_digit[i] = 0;
4593 accum = 0;
4594 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4595 accum |= (twodigits)a->ob_digit[j] << remshift;
4596 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4597 accum >>= PyLong_SHIFT;
4598 }
4599 if (remshift)
4600 z->ob_digit[newsize-1] = (digit)accum;
4601 else
4602 assert(!accum);
4603 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004605}
4606
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004607static PyObject *
4608long_lshift(PyObject *a, PyObject *b)
4609{
4610 Py_ssize_t wordshift;
4611 digit remshift;
4612
4613 CHECK_BINOP(a, b);
4614
4615 if (Py_SIZE(b) < 0) {
4616 PyErr_SetString(PyExc_ValueError, "negative shift count");
4617 return NULL;
4618 }
4619 if (Py_SIZE(a) == 0) {
4620 return PyLong_FromLong(0);
4621 }
4622 if (divmod_shift(b, &wordshift, &remshift) < 0)
4623 return NULL;
4624 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4625}
4626
4627/* Return a << shiftby. */
4628PyObject *
4629_PyLong_Lshift(PyObject *a, size_t shiftby)
4630{
4631 Py_ssize_t wordshift;
4632 digit remshift;
4633
4634 assert(PyLong_Check(a));
4635 if (Py_SIZE(a) == 0) {
4636 return PyLong_FromLong(0);
4637 }
4638 wordshift = shiftby / PyLong_SHIFT;
4639 remshift = shiftby % PyLong_SHIFT;
4640 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4641}
4642
Mark Dickinson27a87a22009-10-25 20:43:34 +00004643/* Compute two's complement of digit vector a[0:m], writing result to
4644 z[0:m]. The digit vector a need not be normalized, but should not
4645 be entirely zero. a and z may point to the same digit vector. */
4646
4647static void
4648v_complement(digit *z, digit *a, Py_ssize_t m)
4649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 Py_ssize_t i;
4651 digit carry = 1;
4652 for (i = 0; i < m; ++i) {
4653 carry += a[i] ^ PyLong_MASK;
4654 z[i] = carry & PyLong_MASK;
4655 carry >>= PyLong_SHIFT;
4656 }
4657 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004658}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004659
4660/* Bitwise and/xor/or operations */
4661
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004662static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004663long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004664 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004665 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 int nega, negb, negz;
4668 Py_ssize_t size_a, size_b, size_z, i;
4669 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 /* Bitwise operations for negative numbers operate as though
4672 on a two's complement representation. So convert arguments
4673 from sign-magnitude to two's complement, and convert the
4674 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004677 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 nega = Py_SIZE(a) < 0;
4679 if (nega) {
4680 z = _PyLong_New(size_a);
4681 if (z == NULL)
4682 return NULL;
4683 v_complement(z->ob_digit, a->ob_digit, size_a);
4684 a = z;
4685 }
4686 else
4687 /* Keep reference count consistent. */
4688 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004691 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 negb = Py_SIZE(b) < 0;
4693 if (negb) {
4694 z = _PyLong_New(size_b);
4695 if (z == NULL) {
4696 Py_DECREF(a);
4697 return NULL;
4698 }
4699 v_complement(z->ob_digit, b->ob_digit, size_b);
4700 b = z;
4701 }
4702 else
4703 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 /* Swap a and b if necessary to ensure size_a >= size_b. */
4706 if (size_a < size_b) {
4707 z = a; a = b; b = z;
4708 size_z = size_a; size_a = size_b; size_b = size_z;
4709 negz = nega; nega = negb; negb = negz;
4710 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 /* JRH: The original logic here was to allocate the result value (z)
4713 as the longer of the two operands. However, there are some cases
4714 where the result is guaranteed to be shorter than that: AND of two
4715 positives, OR of two negatives: use the shorter number. AND with
4716 mixed signs: use the positive number. OR with mixed signs: use the
4717 negative number.
4718 */
4719 switch (op) {
4720 case '^':
4721 negz = nega ^ negb;
4722 size_z = size_a;
4723 break;
4724 case '&':
4725 negz = nega & negb;
4726 size_z = negb ? size_a : size_b;
4727 break;
4728 case '|':
4729 negz = nega | negb;
4730 size_z = negb ? size_b : size_a;
4731 break;
4732 default:
stratakisa10d4262019-03-18 18:59:20 +01004733 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 /* We allow an extra digit if z is negative, to make sure that
4737 the final two's complement of z doesn't overflow. */
4738 z = _PyLong_New(size_z + negz);
4739 if (z == NULL) {
4740 Py_DECREF(a);
4741 Py_DECREF(b);
4742 return NULL;
4743 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 /* Compute digits for overlap of a and b. */
4746 switch(op) {
4747 case '&':
4748 for (i = 0; i < size_b; ++i)
4749 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4750 break;
4751 case '|':
4752 for (i = 0; i < size_b; ++i)
4753 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4754 break;
4755 case '^':
4756 for (i = 0; i < size_b; ++i)
4757 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4758 break;
4759 default:
stratakisa10d4262019-03-18 18:59:20 +01004760 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004761 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 /* Copy any remaining digits of a, inverting if necessary. */
4764 if (op == '^' && negb)
4765 for (; i < size_z; ++i)
4766 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4767 else if (i < size_z)
4768 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4769 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771 /* Complement result if negative. */
4772 if (negz) {
4773 Py_SIZE(z) = -(Py_SIZE(z));
4774 z->ob_digit[size_z] = PyLong_MASK;
4775 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4776 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778 Py_DECREF(a);
4779 Py_DECREF(b);
4780 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004781}
4782
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004783static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004784long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 PyObject *c;
4787 CHECK_BINOP(a, b);
4788 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4789 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004790}
4791
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004792static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004793long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 PyObject *c;
4796 CHECK_BINOP(a, b);
4797 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4798 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004799}
4800
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004801static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004802long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 PyObject *c;
4805 CHECK_BINOP(a, b);
4806 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4807 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004808}
4809
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004810static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004811long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 if (PyLong_CheckExact(v))
4814 Py_INCREF(v);
4815 else
4816 v = _PyLong_Copy((PyLongObject *)v);
4817 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004818}
4819
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004820PyObject *
4821_PyLong_GCD(PyObject *aarg, PyObject *barg)
4822{
4823 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4824 stwodigits x, y, q, s, t, c_carry, d_carry;
4825 stwodigits A, B, C, D, T;
4826 int nbits, k;
4827 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4828 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4829
4830 a = (PyLongObject *)aarg;
4831 b = (PyLongObject *)barg;
4832 size_a = Py_SIZE(a);
4833 size_b = Py_SIZE(b);
4834 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4835 Py_INCREF(a);
4836 Py_INCREF(b);
4837 goto simple;
4838 }
4839
4840 /* Initial reduction: make sure that 0 <= b <= a. */
4841 a = (PyLongObject *)long_abs(a);
4842 if (a == NULL)
4843 return NULL;
4844 b = (PyLongObject *)long_abs(b);
4845 if (b == NULL) {
4846 Py_DECREF(a);
4847 return NULL;
4848 }
4849 if (long_compare(a, b) < 0) {
4850 r = a;
4851 a = b;
4852 b = r;
4853 }
4854 /* We now own references to a and b */
4855
4856 alloc_a = Py_SIZE(a);
4857 alloc_b = Py_SIZE(b);
4858 /* reduce until a fits into 2 digits */
4859 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004860 nbits = _Py_bit_length(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004861 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4862 corresponding bits of b into y */
4863 size_b = Py_SIZE(b);
4864 assert(size_b <= size_a);
4865 if (size_b == 0) {
4866 if (size_a < alloc_a) {
4867 r = (PyLongObject *)_PyLong_Copy(a);
4868 Py_DECREF(a);
4869 }
4870 else
4871 r = a;
4872 Py_DECREF(b);
4873 Py_XDECREF(c);
4874 Py_XDECREF(d);
4875 return (PyObject *)r;
4876 }
4877 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4878 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4879 (a->ob_digit[size_a-3] >> nbits));
4880
4881 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4882 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4883 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4884
4885 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4886 larger than PyLong_MASK during the algorithm. */
4887 A = 1; B = 0; C = 0; D = 1;
4888 for (k=0;; k++) {
4889 if (y-C == 0)
4890 break;
4891 q = (x+(A-1))/(y-C);
4892 s = B+q*D;
4893 t = x-q*y;
4894 if (s > t)
4895 break;
4896 x = y; y = t;
4897 t = A+q*C; A = D; B = C; C = s; D = t;
4898 }
4899
4900 if (k == 0) {
4901 /* no progress; do a Euclidean step */
4902 if (l_divmod(a, b, NULL, &r) < 0)
4903 goto error;
4904 Py_DECREF(a);
4905 a = b;
4906 b = r;
4907 alloc_a = alloc_b;
4908 alloc_b = Py_SIZE(b);
4909 continue;
4910 }
4911
4912 /*
4913 a, b = A*b-B*a, D*a-C*b if k is odd
4914 a, b = A*a-B*b, D*b-C*a if k is even
4915 */
4916 if (k&1) {
4917 T = -A; A = -B; B = T;
4918 T = -C; C = -D; D = T;
4919 }
4920 if (c != NULL)
4921 Py_SIZE(c) = size_a;
4922 else if (Py_REFCNT(a) == 1) {
4923 Py_INCREF(a);
4924 c = a;
4925 }
4926 else {
4927 alloc_a = size_a;
4928 c = _PyLong_New(size_a);
4929 if (c == NULL)
4930 goto error;
4931 }
4932
4933 if (d != NULL)
4934 Py_SIZE(d) = size_a;
4935 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4936 Py_INCREF(b);
4937 d = b;
4938 Py_SIZE(d) = size_a;
4939 }
4940 else {
4941 alloc_b = size_a;
4942 d = _PyLong_New(size_a);
4943 if (d == NULL)
4944 goto error;
4945 }
4946 a_end = a->ob_digit + size_a;
4947 b_end = b->ob_digit + size_b;
4948
4949 /* compute new a and new b in parallel */
4950 a_digit = a->ob_digit;
4951 b_digit = b->ob_digit;
4952 c_digit = c->ob_digit;
4953 d_digit = d->ob_digit;
4954 c_carry = 0;
4955 d_carry = 0;
4956 while (b_digit < b_end) {
4957 c_carry += (A * *a_digit) - (B * *b_digit);
4958 d_carry += (D * *b_digit++) - (C * *a_digit++);
4959 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4960 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4961 c_carry >>= PyLong_SHIFT;
4962 d_carry >>= PyLong_SHIFT;
4963 }
4964 while (a_digit < a_end) {
4965 c_carry += A * *a_digit;
4966 d_carry -= C * *a_digit++;
4967 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4968 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4969 c_carry >>= PyLong_SHIFT;
4970 d_carry >>= PyLong_SHIFT;
4971 }
4972 assert(c_carry == 0);
4973 assert(d_carry == 0);
4974
4975 Py_INCREF(c);
4976 Py_INCREF(d);
4977 Py_DECREF(a);
4978 Py_DECREF(b);
4979 a = long_normalize(c);
4980 b = long_normalize(d);
4981 }
4982 Py_XDECREF(c);
4983 Py_XDECREF(d);
4984
4985simple:
4986 assert(Py_REFCNT(a) > 0);
4987 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004988/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4989 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4990#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004991 /* a fits into a long, so b must too */
4992 x = PyLong_AsLong((PyObject *)a);
4993 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004994#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004995 x = PyLong_AsLongLong((PyObject *)a);
4996 y = PyLong_AsLongLong((PyObject *)b);
4997#else
4998# error "_PyLong_GCD"
4999#endif
5000 x = Py_ABS(x);
5001 y = Py_ABS(y);
5002 Py_DECREF(a);
5003 Py_DECREF(b);
5004
5005 /* usual Euclidean algorithm for longs */
5006 while (y != 0) {
5007 t = y;
5008 y = x % y;
5009 x = t;
5010 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005011#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005012 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05005013#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005014 return PyLong_FromLongLong(x);
5015#else
5016# error "_PyLong_GCD"
5017#endif
5018
5019error:
5020 Py_DECREF(a);
5021 Py_DECREF(b);
5022 Py_XDECREF(c);
5023 Py_XDECREF(d);
5024 return NULL;
5025}
5026
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005027static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005028long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 double result;
5031 result = PyLong_AsDouble(v);
5032 if (result == -1.0 && PyErr_Occurred())
5033 return NULL;
5034 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005035}
5036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005037static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005038long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5039
5040/*[clinic input]
5041@classmethod
5042int.__new__ as long_new
5043 x: object(c_default="NULL") = 0
5044 /
5045 base as obase: object(c_default="NULL") = 10
5046[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005047
Tim Peters6d6c1a32001-08-02 04:15:00 +00005048static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005049long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5050/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005051{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005052 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005055 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005056 if (x == NULL) {
5057 if (obase != NULL) {
5058 PyErr_SetString(PyExc_TypeError,
5059 "int() missing string argument");
5060 return NULL;
5061 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005062 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005063 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005064 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005066
Gregory P. Smitha689e522012-12-25 22:38:32 -08005067 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005068 if (base == -1 && PyErr_Occurred())
5069 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005070 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005071 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305072 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005073 return NULL;
5074 }
5075
5076 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005077 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005078 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 if (PyByteArray_Check(x))
5081 string = PyByteArray_AS_STRING(x);
5082 else
5083 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005084 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 }
5086 else {
5087 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005088 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 return NULL;
5090 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005091}
5092
Serhiy Storchaka95949422013-08-27 19:40:23 +03005093/* Wimpy, slow approach to tp_new calls for subtypes of int:
5094 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005095 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005096 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005097*/
5098static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005099long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 PyLongObject *tmp, *newobj;
5102 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005105 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 if (tmp == NULL)
5107 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005108 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 n = Py_SIZE(tmp);
5110 if (n < 0)
5111 n = -n;
5112 newobj = (PyLongObject *)type->tp_alloc(type, n);
5113 if (newobj == NULL) {
5114 Py_DECREF(tmp);
5115 return NULL;
5116 }
5117 assert(PyLong_Check(newobj));
5118 Py_SIZE(newobj) = Py_SIZE(tmp);
5119 for (i = 0; i < n; i++)
5120 newobj->ob_digit[i] = tmp->ob_digit[i];
5121 Py_DECREF(tmp);
5122 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005123}
5124
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005125/*[clinic input]
5126int.__getnewargs__
5127[clinic start generated code]*/
5128
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005129static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005130int___getnewargs___impl(PyObject *self)
5131/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005132{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005133 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005134}
5135
Guido van Rossumb43daf72007-08-01 18:08:08 +00005136static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005137long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005139 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005140}
5141
5142static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005143long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005146}
5147
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005148/*[clinic input]
5149int.__format__
5150
5151 format_spec: unicode
5152 /
5153[clinic start generated code]*/
5154
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005155static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005156int___format___impl(PyObject *self, PyObject *format_spec)
5157/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005158{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005159 _PyUnicodeWriter writer;
5160 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005161
Victor Stinner8f674cc2013-04-17 23:02:17 +02005162 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005163 ret = _PyLong_FormatAdvancedWriter(
5164 &writer,
5165 self,
5166 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5167 if (ret == -1) {
5168 _PyUnicodeWriter_Dealloc(&writer);
5169 return NULL;
5170 }
5171 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005172}
5173
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005174/* Return a pair (q, r) such that a = b * q + r, and
5175 abs(r) <= abs(b)/2, with equality possible only if q is even.
5176 In other words, q == a / b, rounded to the nearest integer using
5177 round-half-to-even. */
5178
5179PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005180_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005181{
5182 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005183 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005184 int quo_is_odd, quo_is_neg;
5185 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005186
5187 /* Equivalent Python code:
5188
5189 def divmod_near(a, b):
5190 q, r = divmod(a, b)
5191 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5192 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5193 # positive, 2 * r < b if b negative.
5194 greater_than_half = 2*r > b if b > 0 else 2*r < b
5195 exactly_half = 2*r == b
5196 if greater_than_half or exactly_half and q % 2 == 1:
5197 q += 1
5198 r -= b
5199 return q, r
5200
5201 */
5202 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5203 PyErr_SetString(PyExc_TypeError,
5204 "non-integer arguments in division");
5205 return NULL;
5206 }
5207
5208 /* Do a and b have different signs? If so, quotient is negative. */
5209 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5210
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005211 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5212 goto error;
5213
5214 /* compare twice the remainder with the divisor, to see
5215 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005216 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005217 if (twice_rem == NULL)
5218 goto error;
5219 if (quo_is_neg) {
5220 temp = long_neg((PyLongObject*)twice_rem);
5221 Py_DECREF(twice_rem);
5222 twice_rem = temp;
5223 if (twice_rem == NULL)
5224 goto error;
5225 }
5226 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5227 Py_DECREF(twice_rem);
5228
5229 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5230 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5231 /* fix up quotient */
5232 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005233 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005234 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005235 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005236 Py_DECREF(quo);
5237 quo = (PyLongObject *)temp;
5238 if (quo == NULL)
5239 goto error;
5240 /* and remainder */
5241 if (quo_is_neg)
5242 temp = long_add(rem, (PyLongObject *)b);
5243 else
5244 temp = long_sub(rem, (PyLongObject *)b);
5245 Py_DECREF(rem);
5246 rem = (PyLongObject *)temp;
5247 if (rem == NULL)
5248 goto error;
5249 }
5250
5251 result = PyTuple_New(2);
5252 if (result == NULL)
5253 goto error;
5254
5255 /* PyTuple_SET_ITEM steals references */
5256 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5257 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005258 return result;
5259
5260 error:
5261 Py_XDECREF(quo);
5262 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005263 return NULL;
5264}
5265
Eric Smith8c663262007-08-25 02:26:07 +00005266static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005267long_round(PyObject *self, PyObject *args)
5268{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005269 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005270
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005271 /* To round an integer m to the nearest 10**n (n positive), we make use of
5272 * the divmod_near operation, defined by:
5273 *
5274 * divmod_near(a, b) = (q, r)
5275 *
5276 * where q is the nearest integer to the quotient a / b (the
5277 * nearest even integer in the case of a tie) and r == a - q * b.
5278 * Hence q * b = a - r is the nearest multiple of b to a,
5279 * preferring even multiples in the case of a tie.
5280 *
5281 * So the nearest multiple of 10**n to m is:
5282 *
5283 * m - divmod_near(m, 10**n)[1].
5284 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5286 return NULL;
5287 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005288 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005289
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005290 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 if (ndigits == NULL)
5292 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005293
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005294 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 if (Py_SIZE(ndigits) >= 0) {
5296 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005297 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005299
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005300 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5301 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005303 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005305 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005306
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005307 result = PyLong_FromLong(10L);
5308 if (result == NULL) {
5309 Py_DECREF(ndigits);
5310 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005312
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005313 temp = long_pow(result, ndigits, Py_None);
5314 Py_DECREF(ndigits);
5315 Py_DECREF(result);
5316 result = temp;
5317 if (result == NULL)
5318 return NULL;
5319
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005320 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005321 Py_DECREF(result);
5322 result = temp;
5323 if (result == NULL)
5324 return NULL;
5325
5326 temp = long_sub((PyLongObject *)self,
5327 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5328 Py_DECREF(result);
5329 result = temp;
5330
5331 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005332}
5333
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005334/*[clinic input]
5335int.__sizeof__ -> Py_ssize_t
5336
5337Returns size in memory, in bytes.
5338[clinic start generated code]*/
5339
5340static Py_ssize_t
5341int___sizeof___impl(PyObject *self)
5342/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005345
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005346 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5347 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005348}
5349
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005350/*[clinic input]
5351int.bit_length
5352
5353Number of bits necessary to represent self in binary.
5354
5355>>> bin(37)
5356'0b100101'
5357>>> (37).bit_length()
53586
5359[clinic start generated code]*/
5360
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005361static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005362int_bit_length_impl(PyObject *self)
5363/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005366 Py_ssize_t ndigits;
5367 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005368 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005369
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005370 assert(self != NULL);
5371 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005372
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005373 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 if (ndigits == 0)
5375 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005376
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005377 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekasc5b79002020-01-16 15:09:19 +01005378 msd_bits = _Py_bit_length(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5381 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 /* expression above may overflow; use Python integers instead */
5384 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5385 if (result == NULL)
5386 return NULL;
5387 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5388 if (x == NULL)
5389 goto error;
5390 y = (PyLongObject *)long_mul(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 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5398 if (x == NULL)
5399 goto error;
5400 y = (PyLongObject *)long_add(result, x);
5401 Py_DECREF(x);
5402 if (y == NULL)
5403 goto error;
5404 Py_DECREF(result);
5405 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005408
Mark Dickinson22b20182010-05-10 21:27:53 +00005409 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 Py_DECREF(result);
5411 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005412}
5413
Christian Heimes53876d92008-04-19 00:31:39 +00005414#if 0
5415static PyObject *
5416long_is_finite(PyObject *v)
5417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005419}
5420#endif
5421
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005422/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005423int.as_integer_ratio
5424
5425Return integer ratio.
5426
5427Return a pair of integers, whose ratio is exactly equal to the original int
5428and with a positive denominator.
5429
5430>>> (10).as_integer_ratio()
5431(10, 1)
5432>>> (-10).as_integer_ratio()
5433(-10, 1)
5434>>> (0).as_integer_ratio()
5435(0, 1)
5436[clinic start generated code]*/
5437
5438static PyObject *
5439int_as_integer_ratio_impl(PyObject *self)
5440/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5441{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005442 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005443 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005444 if (numerator == NULL) {
5445 return NULL;
5446 }
5447 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5448 Py_DECREF(numerator);
5449 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005450}
5451
5452/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005453int.to_bytes
5454
5455 length: Py_ssize_t
5456 Length of bytes object to use. An OverflowError is raised if the
5457 integer is not representable with the given number of bytes.
5458 byteorder: unicode
5459 The byte order used to represent the integer. If byteorder is 'big',
5460 the most significant byte is at the beginning of the byte array. If
5461 byteorder is 'little', the most significant byte is at the end of the
5462 byte array. To request the native byte order of the host system, use
5463 `sys.byteorder' as the byte order value.
5464 *
5465 signed as is_signed: bool = False
5466 Determines whether two's complement is used to represent the integer.
5467 If signed is False and a negative integer is given, an OverflowError
5468 is raised.
5469
5470Return an array of bytes representing an integer.
5471[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005472
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005473static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005474int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5475 int is_signed)
5476/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005478 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005480
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005481 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005482 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005483 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 little_endian = 0;
5485 else {
5486 PyErr_SetString(PyExc_ValueError,
5487 "byteorder must be either 'little' or 'big'");
5488 return NULL;
5489 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 if (length < 0) {
5492 PyErr_SetString(PyExc_ValueError,
5493 "length argument must be non-negative");
5494 return NULL;
5495 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005497 bytes = PyBytes_FromStringAndSize(NULL, length);
5498 if (bytes == NULL)
5499 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005500
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005501 if (_PyLong_AsByteArray((PyLongObject *)self,
5502 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 length, little_endian, is_signed) < 0) {
5504 Py_DECREF(bytes);
5505 return NULL;
5506 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005509}
5510
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005511/*[clinic input]
5512@classmethod
5513int.from_bytes
5514
5515 bytes as bytes_obj: object
5516 Holds the array of bytes to convert. The argument must either
5517 support the buffer protocol or be an iterable object producing bytes.
5518 Bytes and bytearray are examples of built-in objects that support the
5519 buffer protocol.
5520 byteorder: unicode
5521 The byte order used to represent the integer. If byteorder is 'big',
5522 the most significant byte is at the beginning of the byte array. If
5523 byteorder is 'little', the most significant byte is at the end of the
5524 byte array. To request the native byte order of the host system, use
5525 `sys.byteorder' as the byte order value.
5526 *
5527 signed as is_signed: bool = False
5528 Indicates whether two's complement is used to represent the integer.
5529
5530Return the integer represented by the given array of bytes.
5531[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005532
5533static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005534int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5535 PyObject *byteorder, int is_signed)
5536/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005539 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005540
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005541 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005543 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 little_endian = 0;
5545 else {
5546 PyErr_SetString(PyExc_ValueError,
5547 "byteorder must be either 'little' or 'big'");
5548 return NULL;
5549 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005550
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005551 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 if (bytes == NULL)
5553 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 long_obj = _PyLong_FromByteArray(
5556 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5557 little_endian, is_signed);
5558 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005559
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005560 if (long_obj != NULL && type != &PyLong_Type) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02005561 Py_SETREF(long_obj, _PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005562 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005565}
5566
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005567static PyObject *
5568long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5569{
5570 return long_long(self);
5571}
5572
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005573static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005574 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005576 INT_BIT_LENGTH_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00005577#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005578 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5579 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005580#endif
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005581 INT_TO_BYTES_METHODDEF
5582 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005583 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005584 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005586 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005587 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005588 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 "Ceiling of an Integral returns itself."},
5590 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5591 "Rounding an Integral returns itself.\n"
5592 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005593 INT___GETNEWARGS___METHODDEF
5594 INT___FORMAT___METHODDEF
5595 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005597};
5598
Guido van Rossumb43daf72007-08-01 18:08:08 +00005599static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005600 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005601 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005602 "the real part of a complex number",
5603 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005604 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005605 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005606 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005607 NULL},
5608 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005609 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005610 "the numerator of a rational number in lowest terms",
5611 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005612 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005613 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005614 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005615 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005616 {NULL} /* Sentinel */
5617};
5618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005619PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005620"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005621int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005622\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005623Convert a number or string to an integer, or return 0 if no arguments\n\
5624are given. If x is a number, return x.__int__(). For floating point\n\
5625numbers, this truncates towards zero.\n\
5626\n\
5627If x is not a number or if base is given, then x must be a string,\n\
5628bytes, or bytearray instance representing an integer literal in the\n\
5629given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5630by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5631Base 0 means to interpret the base from the string as an integer literal.\n\
5632>>> int('0b100', base=0)\n\
56334");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005634
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005635static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005636 (binaryfunc)long_add, /*nb_add*/
5637 (binaryfunc)long_sub, /*nb_subtract*/
5638 (binaryfunc)long_mul, /*nb_multiply*/
5639 long_mod, /*nb_remainder*/
5640 long_divmod, /*nb_divmod*/
5641 long_pow, /*nb_power*/
5642 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005643 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005644 (unaryfunc)long_abs, /*tp_absolute*/
5645 (inquiry)long_bool, /*tp_bool*/
5646 (unaryfunc)long_invert, /*nb_invert*/
5647 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005648 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005649 long_and, /*nb_and*/
5650 long_xor, /*nb_xor*/
5651 long_or, /*nb_or*/
5652 long_long, /*nb_int*/
5653 0, /*nb_reserved*/
5654 long_float, /*nb_float*/
5655 0, /* nb_inplace_add */
5656 0, /* nb_inplace_subtract */
5657 0, /* nb_inplace_multiply */
5658 0, /* nb_inplace_remainder */
5659 0, /* nb_inplace_power */
5660 0, /* nb_inplace_lshift */
5661 0, /* nb_inplace_rshift */
5662 0, /* nb_inplace_and */
5663 0, /* nb_inplace_xor */
5664 0, /* nb_inplace_or */
5665 long_div, /* nb_floor_divide */
5666 long_true_divide, /* nb_true_divide */
5667 0, /* nb_inplace_floor_divide */
5668 0, /* nb_inplace_true_divide */
5669 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005670};
5671
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005672PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005673 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5674 "int", /* tp_name */
5675 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5676 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005677 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005678 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 0, /* tp_getattr */
5680 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005681 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 long_to_decimal_string, /* tp_repr */
5683 &long_as_number, /* tp_as_number */
5684 0, /* tp_as_sequence */
5685 0, /* tp_as_mapping */
5686 (hashfunc)long_hash, /* tp_hash */
5687 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005688 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005689 PyObject_GenericGetAttr, /* tp_getattro */
5690 0, /* tp_setattro */
5691 0, /* tp_as_buffer */
5692 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5693 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5694 long_doc, /* tp_doc */
5695 0, /* tp_traverse */
5696 0, /* tp_clear */
5697 long_richcompare, /* tp_richcompare */
5698 0, /* tp_weaklistoffset */
5699 0, /* tp_iter */
5700 0, /* tp_iternext */
5701 long_methods, /* tp_methods */
5702 0, /* tp_members */
5703 long_getset, /* tp_getset */
5704 0, /* tp_base */
5705 0, /* tp_dict */
5706 0, /* tp_descr_get */
5707 0, /* tp_descr_set */
5708 0, /* tp_dictoffset */
5709 0, /* tp_init */
5710 0, /* tp_alloc */
5711 long_new, /* tp_new */
5712 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005713};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005714
Mark Dickinsonbd792642009-03-18 20:06:12 +00005715static PyTypeObject Int_InfoType;
5716
5717PyDoc_STRVAR(int_info__doc__,
5718"sys.int_info\n\
5719\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005720A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005721internal representation of integers. The attributes are read only.");
5722
5723static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005725 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005727};
5728
5729static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005730 "sys.int_info", /* name */
5731 int_info__doc__, /* doc */
5732 int_info_fields, /* fields */
5733 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005734};
5735
5736PyObject *
5737PyLong_GetInfo(void)
5738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005739 PyObject* int_info;
5740 int field = 0;
5741 int_info = PyStructSequence_New(&Int_InfoType);
5742 if (int_info == NULL)
5743 return NULL;
5744 PyStructSequence_SET_ITEM(int_info, field++,
5745 PyLong_FromLong(PyLong_SHIFT));
5746 PyStructSequence_SET_ITEM(int_info, field++,
5747 PyLong_FromLong(sizeof(digit)));
5748 if (PyErr_Occurred()) {
5749 Py_CLEAR(int_info);
5750 return NULL;
5751 }
5752 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005753}
5754
Guido van Rossumddefaf32007-01-14 03:31:43 +00005755int
Victor Stinner630c8df2019-12-17 13:02:18 +01005756_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005757{
5758#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005759 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5760 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5761 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005762
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005763 PyLongObject *v = _PyLong_New(1);
5764 if (!v) {
5765 return -1;
5766 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005769 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005770
Victor Stinner630c8df2019-12-17 13:02:18 +01005771 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005773#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005774
Victor Stinner630c8df2019-12-17 13:02:18 +01005775 if (_Py_IsMainInterpreter(tstate)) {
5776 _PyLong_Zero = PyLong_FromLong(0);
5777 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005778 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005779 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005780
5781 _PyLong_One = PyLong_FromLong(1);
5782 if (_PyLong_One == NULL) {
5783 return 0;
5784 }
5785
5786 /* initialize int_info */
5787 if (Int_InfoType.tp_name == NULL) {
5788 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5789 return 0;
5790 }
5791 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005792 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005795}
5796
5797void
Victor Stinner630c8df2019-12-17 13:02:18 +01005798_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005799{
Victor Stinner630c8df2019-12-17 13:02:18 +01005800 if (_Py_IsMainInterpreter(tstate)) {
5801 Py_CLEAR(_PyLong_One);
5802 Py_CLEAR(_PyLong_Zero);
5803 }
5804
Guido van Rossumddefaf32007-01-14 03:31:43 +00005805#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005806 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005807 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005809#endif
5810}