blob: 11fc75b918f77f22185632c75a00bbe0d12af19d [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 Stinner4a3fe082020-04-14 14:26:24 +02006#include "pycore_interp.h" // _PY_NSMALLPOSINTS
7#include "pycore_pystate.h" // _Py_IsMainInterpreter()
Guido van Rossumedcc38a1991-05-05 20:09:44 +00008#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00009
Mark Dickinsonc6300392009-04-20 21:38:00 +000010#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000011#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000012#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000013
Serhiy Storchaka495e8802017-02-01 23:12:20 +020014#include "clinic/longobject.c.h"
15/*[clinic input]
16class int "PyObject *" "&PyLong_Type"
17[clinic start generated code]*/
18/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
19
Victor Stinner630c8df2019-12-17 13:02:18 +010020#define NSMALLPOSINTS _PY_NSMALLPOSINTS
21#define NSMALLNEGINTS _PY_NSMALLNEGINTS
Facundo Batista6e6f59b2008-07-24 18:57:11 +000022
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020023_Py_IDENTIFIER(little);
24_Py_IDENTIFIER(big);
25
Mark Dickinsone4416742009-02-15 15:14:57 +000026/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020027#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
28 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 (Py_SIZE(x) == 0 ? (sdigit)0 : \
30 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000031
Serhiy Storchakaba85d692017-03-30 09:09:41 +030032PyObject *_PyLong_Zero = NULL;
33PyObject *_PyLong_One = NULL;
34
Guido van Rossumddefaf32007-01-14 03:31:43 +000035#if NSMALLNEGINTS + NSMALLPOSINTS > 0
animalize6b519982019-09-06 14:00:56 +080036#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050037#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070038
Guido van Rossum7eaf8222007-06-18 17:58:50 +000039static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000040get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000041{
animalize6b519982019-09-06 14:00:56 +080042 assert(IS_SMALL_INT(ival));
Victor Stinner630c8df2019-12-17 13:02:18 +010043 PyThreadState *tstate = _PyThreadState_GET();
44 PyObject *v = (PyObject*)tstate->interp->small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000047}
Guido van Rossumddefaf32007-01-14 03:31:43 +000048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000050maybe_small_long(PyLongObject *v)
51{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020052 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080054 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 Py_DECREF(v);
56 return (PyLongObject *)get_small_int(ival);
57 }
58 }
59 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000060}
Guido van Rossumddefaf32007-01-14 03:31:43 +000061#else
animalize6b519982019-09-06 14:00:56 +080062#define IS_SMALL_INT(ival) 0
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050063#define IS_SMALL_UINT(ival) 0
animalize6b519982019-09-06 14:00:56 +080064#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#endif
67
Serhiy Storchaka95949422013-08-27 19:40:23 +030068/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000069 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020070Py_LOCAL_INLINE(void)
71_PyLong_Negate(PyLongObject **x_p)
72{
73 PyLongObject *x;
74
75 x = (PyLongObject *)*x_p;
76 if (Py_REFCNT(x) == 1) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +010077 Py_SET_SIZE(x, -Py_SIZE(x));
Victor Stinner8aed6f12013-07-17 22:31:17 +020078 return;
79 }
80
81 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
82 Py_DECREF(x);
83}
84
Serhiy Storchaka95949422013-08-27 19:40:23 +030085/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000086 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030087 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000088 */
Tim Peters0973b992004-08-29 22:16:50 +000089#define KARATSUBA_CUTOFF 70
90#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000091
Tim Peters47e52ee2004-08-30 02:44:38 +000092/* For exponentiation, use the binary left-to-right algorithm
93 * unless the exponent contains more than FIVEARY_CUTOFF digits.
94 * In that case, do 5 bits at a time. The potential drawback is that
95 * a table of 2**5 intermediate results is computed.
96 */
97#define FIVEARY_CUTOFF 8
98
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000099#define SIGCHECK(PyTryBlock) \
100 do { \
101 if (PyErr_CheckSignals()) PyTryBlock \
102 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000103
Serhiy Storchaka95949422013-08-27 19:40:23 +0300104/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000105 Doesn't attempt to free the storage--in most cases, due to the nature
106 of the algorithms used, this could save at most be one word anyway. */
107
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200109long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000110{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200111 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 while (i > 0 && v->ob_digit[i-1] == 0)
115 --i;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100116 if (i != j) {
117 Py_SET_SIZE(v, (Py_SIZE(v) < 0) ? -(i) : i);
118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000120}
121
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200122/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
123 using the nb_int slot, if available. Raise TypeError if either the
124 nb_int slot is not available or the result of the call to nb_int
125 returns something not of type int.
126*/
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200127PyObject *
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200128_PyLong_FromNbInt(PyObject *integral)
129{
130 PyNumberMethods *nb;
131 PyObject *result;
132
133 /* Fast path for the case that we already have an int. */
134 if (PyLong_CheckExact(integral)) {
135 Py_INCREF(integral);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200136 return integral;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200137 }
138
139 nb = Py_TYPE(integral)->tp_as_number;
140 if (nb == NULL || nb->nb_int == NULL) {
141 PyErr_Format(PyExc_TypeError,
142 "an integer is required (got type %.200s)",
143 Py_TYPE(integral)->tp_name);
144 return NULL;
145 }
146
147 /* Convert using the nb_int slot, which should return something
148 of exact type int. */
149 result = nb->nb_int(integral);
150 if (!result || PyLong_CheckExact(result))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200151 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200152 if (!PyLong_Check(result)) {
153 PyErr_Format(PyExc_TypeError,
154 "__int__ returned non-int (type %.200s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100155 Py_TYPE(result)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200156 Py_DECREF(result);
157 return NULL;
158 }
159 /* Issue #17576: warn if 'result' not of exact type int. */
160 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
161 "__int__ returned non-int (type %.200s). "
162 "The ability to return an instance of a strict subclass of int "
163 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100164 Py_TYPE(result)->tp_name)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200165 Py_DECREF(result);
166 return NULL;
167 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200168 return result;
169}
170
171/* Convert the given object to a PyLongObject using the nb_index or
172 nb_int slots, if available (the latter is deprecated).
173 Raise TypeError if either nb_index and nb_int slots are not
174 available or the result of the call to nb_index or nb_int
175 returns something not of type int.
176 Should be replaced with PyNumber_Index after the end of the
177 deprecation period.
178*/
179PyObject *
180_PyLong_FromNbIndexOrNbInt(PyObject *integral)
181{
182 PyNumberMethods *nb;
183 PyObject *result;
184
185 /* Fast path for the case that we already have an int. */
186 if (PyLong_CheckExact(integral)) {
187 Py_INCREF(integral);
188 return integral;
189 }
190
191 nb = Py_TYPE(integral)->tp_as_number;
192 if (nb == NULL || (nb->nb_index == NULL && nb->nb_int == NULL)) {
193 PyErr_Format(PyExc_TypeError,
194 "an integer is required (got type %.200s)",
195 Py_TYPE(integral)->tp_name);
196 return NULL;
197 }
198
199 if (nb->nb_index) {
200 /* Convert using the nb_index slot, which should return something
201 of exact type int. */
202 result = nb->nb_index(integral);
203 if (!result || PyLong_CheckExact(result))
204 return result;
205 if (!PyLong_Check(result)) {
206 PyErr_Format(PyExc_TypeError,
207 "__index__ returned non-int (type %.200s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100208 Py_TYPE(result)->tp_name);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200209 Py_DECREF(result);
210 return NULL;
211 }
212 /* Issue #17576: warn if 'result' not of exact type int. */
213 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
214 "__index__ returned non-int (type %.200s). "
215 "The ability to return an instance of a strict subclass of int "
216 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100217 Py_TYPE(result)->tp_name))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200218 {
219 Py_DECREF(result);
220 return NULL;
221 }
222 return result;
223 }
224
225 result = _PyLong_FromNbInt(integral);
226 if (result && PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
227 "an integer is required (got type %.200s). "
228 "Implicit conversion to integers using __int__ is deprecated, "
229 "and may be removed in a future version of Python.",
230 Py_TYPE(integral)->tp_name))
231 {
232 Py_DECREF(result);
233 return NULL;
234 }
235 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200236}
237
238
Serhiy Storchaka95949422013-08-27 19:40:23 +0300239/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000240 Return NULL and set exception if we run out of memory. */
241
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000242#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000244
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000246_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 PyLongObject *result;
249 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
250 sizeof(digit)*size. Previous incarnations of this code used
251 sizeof(PyVarObject) instead of the offsetof, but this risks being
252 incorrect in the presence of padding between the PyVarObject header
253 and the digits. */
254 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
255 PyErr_SetString(PyExc_OverflowError,
256 "too many digits in integer");
257 return NULL;
258 }
259 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
260 size*sizeof(digit));
261 if (!result) {
262 PyErr_NoMemory();
263 return NULL;
264 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100265 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000266}
267
Tim Peters64b5ce32001-09-10 20:52:51 +0000268PyObject *
269_PyLong_Copy(PyLongObject *src)
270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 PyLongObject *result;
272 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 assert(src != NULL);
275 i = Py_SIZE(src);
276 if (i < 0)
277 i = -(i);
278 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100279 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800280 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700281 return get_small_int(ival);
282 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 }
284 result = _PyLong_New(i);
285 if (result != NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100286 Py_SET_SIZE(result, Py_SIZE(src));
287 while (--i >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 result->ob_digit[i] = src->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 }
291 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000292}
293
Serhiy Storchaka95949422013-08-27 19:40:23 +0300294/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000295
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000296PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000297PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 PyLongObject *v;
300 unsigned long abs_ival;
301 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
302 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100303 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000304
animalize6b519982019-09-06 14:00:56 +0800305 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700306 return get_small_int((sdigit)ival);
307 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (ival < 0) {
310 /* negate: can't write this as abs_ival = -ival since that
311 invokes undefined behaviour when ival is LONG_MIN */
312 abs_ival = 0U-(unsigned long)ival;
313 sign = -1;
314 }
315 else {
316 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100317 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 /* Fast path for single-digit ints */
321 if (!(abs_ival >> PyLong_SHIFT)) {
322 v = _PyLong_New(1);
323 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100324 Py_SET_SIZE(v, sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 v->ob_digit[0] = Py_SAFE_DOWNCAST(
326 abs_ival, unsigned long, digit);
327 }
328 return (PyObject*)v;
329 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000330
Mark Dickinson249b8982009-04-27 19:41:00 +0000331#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* 2 digits */
333 if (!(abs_ival >> 2*PyLong_SHIFT)) {
334 v = _PyLong_New(2);
335 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100336 Py_SET_SIZE(v, 2 * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 v->ob_digit[0] = Py_SAFE_DOWNCAST(
338 abs_ival & PyLong_MASK, unsigned long, digit);
339 v->ob_digit[1] = Py_SAFE_DOWNCAST(
340 abs_ival >> PyLong_SHIFT, unsigned long, digit);
341 }
342 return (PyObject*)v;
343 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000344#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 /* Larger numbers: loop to determine number of digits */
347 t = abs_ival;
348 while (t) {
349 ++ndigits;
350 t >>= PyLong_SHIFT;
351 }
352 v = _PyLong_New(ndigits);
353 if (v != NULL) {
354 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100355 Py_SET_SIZE(v, ndigits * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 t = abs_ival;
357 while (t) {
358 *p++ = Py_SAFE_DOWNCAST(
359 t & PyLong_MASK, unsigned long, digit);
360 t >>= PyLong_SHIFT;
361 }
362 }
363 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000364}
365
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500366#define PYLONG_FROM_UINT(INT_TYPE, ival) \
367 do { \
368 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200369 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500370 } \
371 /* Count the number of Python digits. */ \
372 Py_ssize_t ndigits = 0; \
373 INT_TYPE t = (ival); \
374 while (t) { \
375 ++ndigits; \
376 t >>= PyLong_SHIFT; \
377 } \
378 PyLongObject *v = _PyLong_New(ndigits); \
379 if (v == NULL) { \
380 return NULL; \
381 } \
382 digit *p = v->ob_digit; \
383 while ((ival)) { \
384 *p++ = (digit)((ival) & PyLong_MASK); \
385 (ival) >>= PyLong_SHIFT; \
386 } \
387 return (PyObject *)v; \
388 } while(0)
389
Serhiy Storchaka95949422013-08-27 19:40:23 +0300390/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000391
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000392PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000393PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000394{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500395 PYLONG_FROM_UINT(unsigned long, ival);
396}
Tim Petersce9de2f2001-06-14 04:56:19 +0000397
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500398/* Create a new int object from a C unsigned long long int. */
399
400PyObject *
401PyLong_FromUnsignedLongLong(unsigned long long ival)
402{
403 PYLONG_FROM_UINT(unsigned long long, ival);
404}
405
406/* Create a new int object from a C size_t. */
407
408PyObject *
409PyLong_FromSize_t(size_t ival)
410{
411 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000412}
413
Serhiy Storchaka95949422013-08-27 19:40:23 +0300414/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000415
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000417PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 PyLongObject *v;
420 double frac;
421 int i, ndig, expo, neg;
422 neg = 0;
423 if (Py_IS_INFINITY(dval)) {
424 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000425 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 return NULL;
427 }
428 if (Py_IS_NAN(dval)) {
429 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000430 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 return NULL;
432 }
433 if (dval < 0.0) {
434 neg = 1;
435 dval = -dval;
436 }
437 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
438 if (expo <= 0)
439 return PyLong_FromLong(0L);
440 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
441 v = _PyLong_New(ndig);
442 if (v == NULL)
443 return NULL;
444 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
445 for (i = ndig; --i >= 0; ) {
446 digit bits = (digit)frac;
447 v->ob_digit[i] = bits;
448 frac = frac - (double)bits;
449 frac = ldexp(frac, PyLong_SHIFT);
450 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100451 if (neg) {
452 Py_SET_SIZE(v, -(Py_SIZE(v)));
453 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000455}
456
Thomas Wouters89f507f2006-12-13 04:49:30 +0000457/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
458 * anything about what happens when a signed integer operation overflows,
459 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700460 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461 * (unsigned long)LONG_MAX, and for the smallest negative signed long
462 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
463 * However, some other compilers warn about applying unary minus to an
464 * unsigned operand. Hence the weird "0-".
465 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
467#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000468
Serhiy Storchaka95949422013-08-27 19:40:23 +0300469/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100470 method.
471
472 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
473 the result. Otherwise *overflow is 0.
474
475 For other errors (e.g., TypeError), return -1 and set an error condition.
476 In this case *overflow will be 0.
477*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000478
479long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000480PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200483 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 unsigned long x, prev;
485 long res;
486 Py_ssize_t i;
487 int sign;
488 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 *overflow = 0;
491 if (vv == NULL) {
492 PyErr_BadInternalCall();
493 return -1;
494 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000495
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200496 if (PyLong_Check(vv)) {
497 v = (PyLongObject *)vv;
498 }
499 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200500 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200501 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 return -1;
503 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 switch (i) {
510 case -1:
511 res = -(sdigit)v->ob_digit[0];
512 break;
513 case 0:
514 res = 0;
515 break;
516 case 1:
517 res = v->ob_digit[0];
518 break;
519 default:
520 sign = 1;
521 x = 0;
522 if (i < 0) {
523 sign = -1;
524 i = -(i);
525 }
526 while (--i >= 0) {
527 prev = x;
528 x = (x << PyLong_SHIFT) | v->ob_digit[i];
529 if ((x >> PyLong_SHIFT) != prev) {
530 *overflow = sign;
531 goto exit;
532 }
533 }
534 /* Haven't lost any bits, but casting to long requires extra
535 * care (see comment above).
536 */
537 if (x <= (unsigned long)LONG_MAX) {
538 res = (long)x * sign;
539 }
540 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
541 res = LONG_MIN;
542 }
543 else {
544 *overflow = sign;
545 /* res is already set to -1 */
546 }
547 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000548 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200550 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 }
552 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000553}
554
Serhiy Storchaka95949422013-08-27 19:40:23 +0300555/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100556 method. Return -1 and set an error if overflow occurs. */
557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000559PyLong_AsLong(PyObject *obj)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 int overflow;
562 long result = PyLong_AsLongAndOverflow(obj, &overflow);
563 if (overflow) {
564 /* XXX: could be cute and give a different
565 message for overflow == -1 */
566 PyErr_SetString(PyExc_OverflowError,
567 "Python int too large to convert to C long");
568 }
569 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000570}
571
Serhiy Storchaka95949422013-08-27 19:40:23 +0300572/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200573 method. Return -1 and set an error if overflow occurs. */
574
575int
576_PyLong_AsInt(PyObject *obj)
577{
578 int overflow;
579 long result = PyLong_AsLongAndOverflow(obj, &overflow);
580 if (overflow || result > INT_MAX || result < INT_MIN) {
581 /* XXX: could be cute and give a different
582 message for overflow == -1 */
583 PyErr_SetString(PyExc_OverflowError,
584 "Python int too large to convert to C int");
585 return -1;
586 }
587 return (int)result;
588}
589
Serhiy Storchaka95949422013-08-27 19:40:23 +0300590/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000591 Returns -1 and sets an error condition if overflow occurs. */
592
593Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000594PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200595 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 size_t x, prev;
597 Py_ssize_t i;
598 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (vv == NULL) {
601 PyErr_BadInternalCall();
602 return -1;
603 }
604 if (!PyLong_Check(vv)) {
605 PyErr_SetString(PyExc_TypeError, "an integer is required");
606 return -1;
607 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 v = (PyLongObject *)vv;
610 i = Py_SIZE(v);
611 switch (i) {
612 case -1: return -(sdigit)v->ob_digit[0];
613 case 0: return 0;
614 case 1: return v->ob_digit[0];
615 }
616 sign = 1;
617 x = 0;
618 if (i < 0) {
619 sign = -1;
620 i = -(i);
621 }
622 while (--i >= 0) {
623 prev = x;
624 x = (x << PyLong_SHIFT) | v->ob_digit[i];
625 if ((x >> PyLong_SHIFT) != prev)
626 goto overflow;
627 }
628 /* Haven't lost any bits, but casting to a signed type requires
629 * extra care (see comment above).
630 */
631 if (x <= (size_t)PY_SSIZE_T_MAX) {
632 return (Py_ssize_t)x * sign;
633 }
634 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
635 return PY_SSIZE_T_MIN;
636 }
637 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000638
Mark Dickinson22b20182010-05-10 21:27:53 +0000639 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 PyErr_SetString(PyExc_OverflowError,
641 "Python int too large to convert to C ssize_t");
642 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000643}
644
Serhiy Storchaka95949422013-08-27 19:40:23 +0300645/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000646 Returns -1 and sets an error condition if overflow occurs. */
647
648unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000649PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000650{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200651 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 unsigned long x, prev;
653 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 if (vv == NULL) {
656 PyErr_BadInternalCall();
657 return (unsigned long)-1;
658 }
659 if (!PyLong_Check(vv)) {
660 PyErr_SetString(PyExc_TypeError, "an integer is required");
661 return (unsigned long)-1;
662 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 v = (PyLongObject *)vv;
665 i = Py_SIZE(v);
666 x = 0;
667 if (i < 0) {
668 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000669 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 return (unsigned long) -1;
671 }
672 switch (i) {
673 case 0: return 0;
674 case 1: return v->ob_digit[0];
675 }
676 while (--i >= 0) {
677 prev = x;
678 x = (x << PyLong_SHIFT) | v->ob_digit[i];
679 if ((x >> PyLong_SHIFT) != prev) {
680 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100681 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000682 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 return (unsigned long) -1;
684 }
685 }
686 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000687}
688
Serhiy Storchaka95949422013-08-27 19:40:23 +0300689/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200690 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000691
692size_t
693PyLong_AsSize_t(PyObject *vv)
694{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200695 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 size_t x, prev;
697 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 if (vv == NULL) {
700 PyErr_BadInternalCall();
701 return (size_t) -1;
702 }
703 if (!PyLong_Check(vv)) {
704 PyErr_SetString(PyExc_TypeError, "an integer is required");
705 return (size_t)-1;
706 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 v = (PyLongObject *)vv;
709 i = Py_SIZE(v);
710 x = 0;
711 if (i < 0) {
712 PyErr_SetString(PyExc_OverflowError,
713 "can't convert negative value to size_t");
714 return (size_t) -1;
715 }
716 switch (i) {
717 case 0: return 0;
718 case 1: return v->ob_digit[0];
719 }
720 while (--i >= 0) {
721 prev = x;
722 x = (x << PyLong_SHIFT) | v->ob_digit[i];
723 if ((x >> PyLong_SHIFT) != prev) {
724 PyErr_SetString(PyExc_OverflowError,
725 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200726 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 }
728 }
729 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000730}
731
Serhiy Storchaka95949422013-08-27 19:40:23 +0300732/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000733 Returns -1 and sets an error condition if an error occurs. */
734
Guido van Rossumddefaf32007-01-14 03:31:43 +0000735static unsigned long
736_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000737{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200738 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 unsigned long x;
740 Py_ssize_t i;
741 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (vv == NULL || !PyLong_Check(vv)) {
744 PyErr_BadInternalCall();
745 return (unsigned long) -1;
746 }
747 v = (PyLongObject *)vv;
748 i = Py_SIZE(v);
749 switch (i) {
750 case 0: return 0;
751 case 1: return v->ob_digit[0];
752 }
753 sign = 1;
754 x = 0;
755 if (i < 0) {
756 sign = -1;
757 i = -i;
758 }
759 while (--i >= 0) {
760 x = (x << PyLong_SHIFT) | v->ob_digit[i];
761 }
762 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000763}
764
Guido van Rossumddefaf32007-01-14 03:31:43 +0000765unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200766PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 PyLongObject *lo;
769 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000770
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200771 if (op == NULL) {
772 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 return (unsigned long)-1;
774 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000775
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200776 if (PyLong_Check(op)) {
777 return _PyLong_AsUnsignedLongMask(op);
778 }
779
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200780 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (lo == NULL)
782 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200783
784 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
785 Py_DECREF(lo);
786 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000787}
788
Tim Peters5b8132f2003-01-31 15:52:05 +0000789int
790_PyLong_Sign(PyObject *vv)
791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 assert(v != NULL);
795 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000798}
799
Tim Petersbaefd9e2003-01-28 20:37:45 +0000800size_t
801_PyLong_NumBits(PyObject *vv)
802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 PyLongObject *v = (PyLongObject *)vv;
804 size_t result = 0;
805 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200806 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 assert(v != NULL);
809 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200810 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
812 if (ndigits > 0) {
813 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700814 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100816 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Niklas Fiekasc5b79002020-01-16 15:09:19 +0100817 msd_bits = _Py_bit_length(msd);
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200818 if (SIZE_MAX - msd_bits < result)
819 goto Overflow;
820 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 }
822 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000823
Mark Dickinson22b20182010-05-10 21:27:53 +0000824 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
826 "to express in a platform size_t");
827 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000828}
829
Tim Peters2a9b3672001-06-11 21:23:58 +0000830PyObject *
831_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000833{
Mark Dickinson22b20182010-05-10 21:27:53 +0000834 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 int incr; /* direction to move pstartbyte */
836 const unsigned char* pendbyte; /* MSB of bytes */
837 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300838 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyLongObject* v; /* result */
840 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 if (n == 0)
843 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (little_endian) {
846 pstartbyte = bytes;
847 pendbyte = bytes + n - 1;
848 incr = 1;
849 }
850 else {
851 pstartbyte = bytes + n - 1;
852 pendbyte = bytes;
853 incr = -1;
854 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (is_signed)
857 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200860 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 is positive, and leading 0xff bytes if negative. */
862 {
863 size_t i;
864 const unsigned char* p = pendbyte;
865 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000866 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000869 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 break;
871 }
872 numsignificantbytes = n - i;
873 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
874 actually has 2 significant bytes. OTOH, 0xff0001 ==
875 -0x00ffff, so we wouldn't *need* to bump it there; but we
876 do for 0xffff = -0x0001. To be safe without bothering to
877 check every case, bump it regardless. */
878 if (is_signed && numsignificantbytes < n)
879 ++numsignificantbytes;
880 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000881
Serhiy Storchaka95949422013-08-27 19:40:23 +0300882 /* How many Python int digits do we need? We have
883 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
885 /* catch overflow before it happens */
886 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
887 PyErr_SetString(PyExc_OverflowError,
888 "byte array too long to convert to int");
889 return NULL;
890 }
891 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
892 v = _PyLong_New(ndigits);
893 if (v == NULL)
894 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 /* Copy the bits over. The tricky parts are computing 2's-comp on
897 the fly for signed numbers, and dealing with the mismatch between
898 8-bit bytes and (probably) 15-bit Python digits.*/
899 {
900 size_t i;
901 twodigits carry = 1; /* for 2's-comp calculation */
902 twodigits accum = 0; /* sliding register */
903 unsigned int accumbits = 0; /* number of bits in accum */
904 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
907 twodigits thisbyte = *p;
908 /* Compute correction for 2's comp, if needed. */
909 if (is_signed) {
910 thisbyte = (0xff ^ thisbyte) + carry;
911 carry = thisbyte >> 8;
912 thisbyte &= 0xff;
913 }
914 /* Because we're going LSB to MSB, thisbyte is
915 more significant than what's already in accum,
916 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200917 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 accumbits += 8;
919 if (accumbits >= PyLong_SHIFT) {
920 /* There's enough to fill a Python digit. */
921 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000922 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 ++idigit;
924 accum >>= PyLong_SHIFT;
925 accumbits -= PyLong_SHIFT;
926 assert(accumbits < PyLong_SHIFT);
927 }
928 }
929 assert(accumbits < PyLong_SHIFT);
930 if (accumbits) {
931 assert(idigit < ndigits);
932 v->ob_digit[idigit] = (digit)accum;
933 ++idigit;
934 }
935 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000936
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100937 Py_SET_SIZE(v, is_signed ? -idigit : idigit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000939}
940
941int
942_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 unsigned char* bytes, size_t n,
944 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000947 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000949 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
951 digit carry; /* for computing 2's-comp */
952 size_t j; /* # bytes filled */
953 unsigned char* p; /* pointer to next byte in bytes */
954 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (Py_SIZE(v) < 0) {
959 ndigits = -(Py_SIZE(v));
960 if (!is_signed) {
961 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000962 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 return -1;
964 }
965 do_twos_comp = 1;
966 }
967 else {
968 ndigits = Py_SIZE(v);
969 do_twos_comp = 0;
970 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 if (little_endian) {
973 p = bytes;
974 pincr = 1;
975 }
976 else {
977 p = bytes + n - 1;
978 pincr = -1;
979 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 /* Copy over all the Python digits.
982 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300983 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 normalized. */
985 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
986 j = 0;
987 accum = 0;
988 accumbits = 0;
989 carry = do_twos_comp ? 1 : 0;
990 for (i = 0; i < ndigits; ++i) {
991 digit thisdigit = v->ob_digit[i];
992 if (do_twos_comp) {
993 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
994 carry = thisdigit >> PyLong_SHIFT;
995 thisdigit &= PyLong_MASK;
996 }
997 /* Because we're going LSB to MSB, thisdigit is more
998 significant than what's already in accum, so needs to be
999 prepended to accum. */
1000 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* The most-significant digit may be (probably is) at least
1003 partly empty. */
1004 if (i == ndigits - 1) {
1005 /* Count # of sign bits -- they needn't be stored,
1006 * although for signed conversion we need later to
1007 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +00001008 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 while (s != 0) {
1010 s >>= 1;
1011 accumbits++;
1012 }
1013 }
1014 else
1015 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* Store as many bytes as possible. */
1018 while (accumbits >= 8) {
1019 if (j >= n)
1020 goto Overflow;
1021 ++j;
1022 *p = (unsigned char)(accum & 0xff);
1023 p += pincr;
1024 accumbits -= 8;
1025 accum >>= 8;
1026 }
1027 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 /* Store the straggler (if any). */
1030 assert(accumbits < 8);
1031 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1032 if (accumbits > 0) {
1033 if (j >= n)
1034 goto Overflow;
1035 ++j;
1036 if (do_twos_comp) {
1037 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +03001038 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 infinite supply of sign bits). */
1040 accum |= (~(twodigits)0) << accumbits;
1041 }
1042 *p = (unsigned char)(accum & 0xff);
1043 p += pincr;
1044 }
1045 else if (j == n && n > 0 && is_signed) {
1046 /* The main loop filled the byte array exactly, so the code
1047 just above didn't get to ensure there's a sign bit, and the
1048 loop below wouldn't add one either. Make sure a sign bit
1049 exists. */
1050 unsigned char msb = *(p - pincr);
1051 int sign_bit_set = msb >= 0x80;
1052 assert(accumbits == 0);
1053 if (sign_bit_set == do_twos_comp)
1054 return 0;
1055 else
1056 goto Overflow;
1057 }
Tim Peters05607ad2001-06-13 21:01:27 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 /* Fill remaining bytes with copies of the sign bit. */
1060 {
1061 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1062 for ( ; j < n; ++j, p += pincr)
1063 *p = signbyte;
1064 }
Tim Peters05607ad2001-06-13 21:01:27 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001067
Mark Dickinson22b20182010-05-10 21:27:53 +00001068 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1070 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001071
Tim Peters2a9b3672001-06-11 21:23:58 +00001072}
1073
Serhiy Storchaka95949422013-08-27 19:40:23 +03001074/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001075
1076PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001077PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001078{
Mark Dickinson91044792012-10-18 19:21:43 +01001079#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001080 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001081#else
1082
Tim Peters70128a12001-06-16 08:48:40 +00001083#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001084# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001085#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001086 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001087#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001088
Guido van Rossum78694d91998-09-18 14:14:13 +00001089}
1090
Serhiy Storchaka95949422013-08-27 19:40:23 +03001091/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001092
1093void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001094PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001095{
Tim Peters70128a12001-06-16 08:48:40 +00001096#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1100 x = PyLong_AsLong(vv);
1101 else
1102 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001103#else
Tim Peters70128a12001-06-16 08:48:40 +00001104
Tim Peters70128a12001-06-16 08:48:40 +00001105#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001106# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001107#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001108 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1111 x = PyLong_AsLongLong(vv);
1112 else
1113 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001114
1115#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (x == -1 && PyErr_Occurred())
1118 return NULL;
1119 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001120}
1121
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001122/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001123 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001124 */
1125
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001126#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001127
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001128/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001129
1130PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001131PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001134 unsigned long long abs_ival;
1135 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 int ndigits = 0;
1137 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001138
animalize6b519982019-09-06 14:00:56 +08001139 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001140 return get_small_int((sdigit)ival);
1141 }
1142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (ival < 0) {
1144 /* avoid signed overflow on negation; see comments
1145 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001146 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 negative = 1;
1148 }
1149 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001150 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 /* Count the number of Python digits.
1154 We used to pick 5 ("big enough for anything"), but that's a
1155 waste of time and space given that 5*15 = 75 bits are rarely
1156 needed. */
1157 t = abs_ival;
1158 while (t) {
1159 ++ndigits;
1160 t >>= PyLong_SHIFT;
1161 }
1162 v = _PyLong_New(ndigits);
1163 if (v != NULL) {
1164 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001165 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 t = abs_ival;
1167 while (t) {
1168 *p++ = (digit)(t & PyLong_MASK);
1169 t >>= PyLong_SHIFT;
1170 }
1171 }
1172 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001173}
1174
Serhiy Storchaka95949422013-08-27 19:40:23 +03001175/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001176
1177PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001178PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 PyLongObject *v;
1181 size_t abs_ival;
1182 size_t t; /* unsigned so >> doesn't propagate sign bit */
1183 int ndigits = 0;
1184 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001185
animalize6b519982019-09-06 14:00:56 +08001186 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001187 return get_small_int((sdigit)ival);
1188 }
1189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (ival < 0) {
1191 /* avoid signed overflow when ival = SIZE_T_MIN */
1192 abs_ival = (size_t)(-1-ival)+1;
1193 negative = 1;
1194 }
1195 else {
1196 abs_ival = (size_t)ival;
1197 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 /* Count the number of Python digits. */
1200 t = abs_ival;
1201 while (t) {
1202 ++ndigits;
1203 t >>= PyLong_SHIFT;
1204 }
1205 v = _PyLong_New(ndigits);
1206 if (v != NULL) {
1207 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001208 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 t = abs_ival;
1210 while (t) {
1211 *p++ = (digit)(t & PyLong_MASK);
1212 t >>= PyLong_SHIFT;
1213 }
1214 }
1215 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001216}
1217
Serhiy Storchaka95949422013-08-27 19:40:23 +03001218/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001219 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001220
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001221long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001222PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001225 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001227 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (vv == NULL) {
1230 PyErr_BadInternalCall();
1231 return -1;
1232 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001233
1234 if (PyLong_Check(vv)) {
1235 v = (PyLongObject *)vv;
1236 }
1237 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001238 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001239 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001241 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001243
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001244 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001246 case -1:
1247 bytes = -(sdigit)v->ob_digit[0];
1248 break;
1249 case 0:
1250 bytes = 0;
1251 break;
1252 case 1:
1253 bytes = v->ob_digit[0];
1254 break;
1255 default:
1256 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001257 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001259 if (do_decref) {
1260 Py_DECREF(v);
1261 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001262
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001263 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001265 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 else
1267 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001268}
1269
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001270/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001271 Return -1 and set an error if overflow occurs. */
1272
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001273unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001274PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001277 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001279
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001280 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001282 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001284 if (!PyLong_Check(vv)) {
1285 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001286 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001287 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 v = (PyLongObject*)vv;
1290 switch(Py_SIZE(v)) {
1291 case 0: return 0;
1292 case 1: return v->ob_digit[0];
1293 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001294
Mark Dickinson22b20182010-05-10 21:27:53 +00001295 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001296 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001297
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001298 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001300 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 else
1302 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001303}
Tim Petersd1a7da62001-06-13 00:35:57 +00001304
Serhiy Storchaka95949422013-08-27 19:40:23 +03001305/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001306 Returns -1 and sets an error condition if an error occurs. */
1307
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001308static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001309_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001310{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001311 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001312 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 Py_ssize_t i;
1314 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (vv == NULL || !PyLong_Check(vv)) {
1317 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001318 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 }
1320 v = (PyLongObject *)vv;
1321 switch(Py_SIZE(v)) {
1322 case 0: return 0;
1323 case 1: return v->ob_digit[0];
1324 }
1325 i = Py_SIZE(v);
1326 sign = 1;
1327 x = 0;
1328 if (i < 0) {
1329 sign = -1;
1330 i = -i;
1331 }
1332 while (--i >= 0) {
1333 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1334 }
1335 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001336}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001337
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001338unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001339PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001342 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001343
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001344 if (op == NULL) {
1345 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001346 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001348
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001349 if (PyLong_Check(op)) {
1350 return _PyLong_AsUnsignedLongLongMask(op);
1351 }
1352
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001353 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001355 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001356
1357 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1358 Py_DECREF(lo);
1359 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001360}
Tim Petersd1a7da62001-06-13 00:35:57 +00001361
Serhiy Storchaka95949422013-08-27 19:40:23 +03001362/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001363 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001364
Mark Dickinson8d48b432011-10-23 20:47:14 +01001365 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1366 the result. Otherwise *overflow is 0.
1367
1368 For other errors (e.g., TypeError), return -1 and set an error condition.
1369 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001370*/
1371
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001372long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001373PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001376 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001377 unsigned long long x, prev;
1378 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 Py_ssize_t i;
1380 int sign;
1381 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 *overflow = 0;
1384 if (vv == NULL) {
1385 PyErr_BadInternalCall();
1386 return -1;
1387 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001388
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001389 if (PyLong_Check(vv)) {
1390 v = (PyLongObject *)vv;
1391 }
1392 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001393 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001394 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 return -1;
1396 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 switch (i) {
1403 case -1:
1404 res = -(sdigit)v->ob_digit[0];
1405 break;
1406 case 0:
1407 res = 0;
1408 break;
1409 case 1:
1410 res = v->ob_digit[0];
1411 break;
1412 default:
1413 sign = 1;
1414 x = 0;
1415 if (i < 0) {
1416 sign = -1;
1417 i = -(i);
1418 }
1419 while (--i >= 0) {
1420 prev = x;
1421 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1422 if ((x >> PyLong_SHIFT) != prev) {
1423 *overflow = sign;
1424 goto exit;
1425 }
1426 }
1427 /* Haven't lost any bits, but casting to long requires extra
1428 * care (see comment above).
1429 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001430 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001431 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 }
1433 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001434 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 }
1436 else {
1437 *overflow = sign;
1438 /* res is already set to -1 */
1439 }
1440 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001441 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001443 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 }
1445 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001446}
1447
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001448int
1449_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1450{
1451 unsigned long uval;
1452
1453 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1454 PyErr_SetString(PyExc_ValueError, "value must be positive");
1455 return 0;
1456 }
1457 uval = PyLong_AsUnsignedLong(obj);
1458 if (uval == (unsigned long)-1 && PyErr_Occurred())
1459 return 0;
1460 if (uval > USHRT_MAX) {
1461 PyErr_SetString(PyExc_OverflowError,
1462 "Python int too large for C unsigned short");
1463 return 0;
1464 }
1465
1466 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1467 return 1;
1468}
1469
1470int
1471_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1472{
1473 unsigned long uval;
1474
1475 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1476 PyErr_SetString(PyExc_ValueError, "value must be positive");
1477 return 0;
1478 }
1479 uval = PyLong_AsUnsignedLong(obj);
1480 if (uval == (unsigned long)-1 && PyErr_Occurred())
1481 return 0;
1482 if (uval > UINT_MAX) {
1483 PyErr_SetString(PyExc_OverflowError,
1484 "Python int too large for C unsigned int");
1485 return 0;
1486 }
1487
1488 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1489 return 1;
1490}
1491
1492int
1493_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1494{
1495 unsigned long uval;
1496
1497 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1498 PyErr_SetString(PyExc_ValueError, "value must be positive");
1499 return 0;
1500 }
1501 uval = PyLong_AsUnsignedLong(obj);
1502 if (uval == (unsigned long)-1 && PyErr_Occurred())
1503 return 0;
1504
1505 *(unsigned long *)ptr = uval;
1506 return 1;
1507}
1508
1509int
1510_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1511{
1512 unsigned long long uval;
1513
1514 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1515 PyErr_SetString(PyExc_ValueError, "value must be positive");
1516 return 0;
1517 }
1518 uval = PyLong_AsUnsignedLongLong(obj);
1519 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1520 return 0;
1521
1522 *(unsigned long long *)ptr = uval;
1523 return 1;
1524}
1525
1526int
1527_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1528{
1529 size_t uval;
1530
1531 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1532 PyErr_SetString(PyExc_ValueError, "value must be positive");
1533 return 0;
1534 }
1535 uval = PyLong_AsSize_t(obj);
1536 if (uval == (size_t)-1 && PyErr_Occurred())
1537 return 0;
1538
1539 *(size_t *)ptr = uval;
1540 return 1;
1541}
1542
1543
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001544#define CHECK_BINOP(v,w) \
1545 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001546 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1547 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001548 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001549
Tim Peters877a2122002-08-12 05:09:36 +00001550/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1551 * is modified in place, by adding y to it. Carries are propagated as far as
1552 * x[m-1], and the remaining carry (0 or 1) is returned.
1553 */
1554static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001555v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 Py_ssize_t i;
1558 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 assert(m >= n);
1561 for (i = 0; i < n; ++i) {
1562 carry += x[i] + y[i];
1563 x[i] = carry & PyLong_MASK;
1564 carry >>= PyLong_SHIFT;
1565 assert((carry & 1) == carry);
1566 }
1567 for (; carry && i < m; ++i) {
1568 carry += x[i];
1569 x[i] = carry & PyLong_MASK;
1570 carry >>= PyLong_SHIFT;
1571 assert((carry & 1) == carry);
1572 }
1573 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001574}
1575
1576/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1577 * is modified in place, by subtracting y from it. Borrows are propagated as
1578 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1579 */
1580static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001581v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 Py_ssize_t i;
1584 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 assert(m >= n);
1587 for (i = 0; i < n; ++i) {
1588 borrow = x[i] - y[i] - borrow;
1589 x[i] = borrow & PyLong_MASK;
1590 borrow >>= PyLong_SHIFT;
1591 borrow &= 1; /* keep only 1 sign bit */
1592 }
1593 for (; borrow && i < m; ++i) {
1594 borrow = x[i] - borrow;
1595 x[i] = borrow & PyLong_MASK;
1596 borrow >>= PyLong_SHIFT;
1597 borrow &= 1;
1598 }
1599 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001600}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001601
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001602/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1603 * result in z[0:m], and return the d bits shifted out of the top.
1604 */
1605static digit
1606v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 Py_ssize_t i;
1609 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 assert(0 <= d && d < PyLong_SHIFT);
1612 for (i=0; i < m; i++) {
1613 twodigits acc = (twodigits)a[i] << d | carry;
1614 z[i] = (digit)acc & PyLong_MASK;
1615 carry = (digit)(acc >> PyLong_SHIFT);
1616 }
1617 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001618}
1619
1620/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1621 * result in z[0:m], and return the d bits shifted out of the bottom.
1622 */
1623static digit
1624v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 Py_ssize_t i;
1627 digit carry = 0;
1628 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 assert(0 <= d && d < PyLong_SHIFT);
1631 for (i=m; i-- > 0;) {
1632 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1633 carry = (digit)acc & mask;
1634 z[i] = (digit)(acc >> d);
1635 }
1636 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001637}
1638
Tim Peters212e6142001-07-14 12:23:19 +00001639/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1640 in pout, and returning the remainder. pin and pout point at the LSD.
1641 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001642 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001643 immutable. */
1644
1645static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001646inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 assert(n > 0 && n <= PyLong_MASK);
1651 pin += size;
1652 pout += size;
1653 while (--size >= 0) {
1654 digit hi;
1655 rem = (rem << PyLong_SHIFT) | *--pin;
1656 *--pout = hi = (digit)(rem / n);
1657 rem -= (twodigits)hi * n;
1658 }
1659 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001660}
1661
Serhiy Storchaka95949422013-08-27 19:40:23 +03001662/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001663 (as function result) and the remainder (through *prem).
1664 The sign of a is ignored; n should not be zero. */
1665
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001666static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001667divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001668{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001669 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 assert(n > 0 && n <= PyLong_MASK);
1673 z = _PyLong_New(size);
1674 if (z == NULL)
1675 return NULL;
1676 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1677 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001678}
1679
Serhiy Storchaka95949422013-08-27 19:40:23 +03001680/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001681 string. (Return value is non-shared so that callers can modify the
1682 returned value if necessary.) */
1683
Victor Stinnerd3f08822012-05-29 12:57:52 +02001684static int
1685long_to_decimal_string_internal(PyObject *aa,
1686 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001687 _PyUnicodeWriter *writer,
1688 _PyBytesWriter *bytes_writer,
1689 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001692 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 Py_ssize_t size, strlen, size_a, i, j;
1694 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001696 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001697 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 a = (PyLongObject *)aa;
1700 if (a == NULL || !PyLong_Check(a)) {
1701 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001702 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001704 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 /* quick and dirty upper bound for the number of digits
1708 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 But log2(a) < size_a * PyLong_SHIFT, and
1713 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001714 > 3.3 * _PyLong_DECIMAL_SHIFT
1715
1716 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1717 size_a + size_a / d < size_a + size_a / floor(d),
1718 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1719 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001721 d = (33 * _PyLong_DECIMAL_SHIFT) /
1722 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1723 assert(size_a < PY_SSIZE_T_MAX/2);
1724 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 scratch = _PyLong_New(size);
1726 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001727 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 /* convert array of base _PyLong_BASE digits in pin to an array of
1730 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1731 Volume 2 (3rd edn), section 4.4, Method 1b). */
1732 pin = a->ob_digit;
1733 pout = scratch->ob_digit;
1734 size = 0;
1735 for (i = size_a; --i >= 0; ) {
1736 digit hi = pin[i];
1737 for (j = 0; j < size; j++) {
1738 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1739 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1740 pout[j] = (digit)(z - (twodigits)hi *
1741 _PyLong_DECIMAL_BASE);
1742 }
1743 while (hi) {
1744 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1745 hi /= _PyLong_DECIMAL_BASE;
1746 }
1747 /* check for keyboard interrupt */
1748 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001749 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001750 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001751 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 }
1753 /* pout should have at least one digit, so that the case when a = 0
1754 works correctly */
1755 if (size == 0)
1756 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 /* calculate exact length of output string, and allocate */
1759 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1760 tenpow = 10;
1761 rem = pout[size-1];
1762 while (rem >= tenpow) {
1763 tenpow *= 10;
1764 strlen++;
1765 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001766 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001767 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1768 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001769 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001770 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001771 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001773 else if (bytes_writer) {
1774 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1775 if (*bytes_str == NULL) {
1776 Py_DECREF(scratch);
1777 return -1;
1778 }
1779 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001780 else {
1781 str = PyUnicode_New(strlen, '9');
1782 if (str == NULL) {
1783 Py_DECREF(scratch);
1784 return -1;
1785 }
1786 kind = PyUnicode_KIND(str);
1787 }
1788
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001789#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001790 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001791 /* pout[0] through pout[size-2] contribute exactly \
1792 _PyLong_DECIMAL_SHIFT digits each */ \
1793 for (i=0; i < size - 1; i++) { \
1794 rem = pout[i]; \
1795 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1796 *--p = '0' + rem % 10; \
1797 rem /= 10; \
1798 } \
1799 } \
1800 /* pout[size-1]: always produce at least one decimal digit */ \
1801 rem = pout[i]; \
1802 do { \
1803 *--p = '0' + rem % 10; \
1804 rem /= 10; \
1805 } while (rem != 0); \
1806 \
1807 /* and sign */ \
1808 if (negative) \
1809 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001810 } while (0)
1811
1812#define WRITE_UNICODE_DIGITS(TYPE) \
1813 do { \
1814 if (writer) \
1815 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1816 else \
1817 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1818 \
1819 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001820 \
1821 /* check we've counted correctly */ \
1822 if (writer) \
1823 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1824 else \
1825 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1826 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001829 if (bytes_writer) {
1830 char *p = *bytes_str + strlen;
1831 WRITE_DIGITS(p);
1832 assert(p == *bytes_str);
1833 }
1834 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001835 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001836 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001838 else if (kind == PyUnicode_2BYTE_KIND) {
1839 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001840 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001841 }
1842 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001843 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001844 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001845 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001846 }
1847#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001848#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001851 if (writer) {
1852 writer->pos += strlen;
1853 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001854 else if (bytes_writer) {
1855 (*bytes_str) += strlen;
1856 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001857 else {
1858 assert(_PyUnicode_CheckConsistency(str, 1));
1859 *p_output = (PyObject *)str;
1860 }
1861 return 0;
1862}
1863
1864static PyObject *
1865long_to_decimal_string(PyObject *aa)
1866{
1867 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001868 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001869 return NULL;
1870 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001871}
1872
Serhiy Storchaka95949422013-08-27 19:40:23 +03001873/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001874 which should be one of 2, 8 or 16. Return a string object.
1875 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1876 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001877
Victor Stinnerd3f08822012-05-29 12:57:52 +02001878static int
1879long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001880 PyObject **p_output, _PyUnicodeWriter *writer,
1881 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001882{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001883 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001884 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001885 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001887 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001888 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001890
Victor Stinnerd3f08822012-05-29 12:57:52 +02001891 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (a == NULL || !PyLong_Check(a)) {
1893 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001894 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001896 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001897 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* Compute a rough upper bound for the length of the string */
1900 switch (base) {
1901 case 16:
1902 bits = 4;
1903 break;
1904 case 8:
1905 bits = 3;
1906 break;
1907 case 2:
1908 bits = 1;
1909 break;
1910 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001911 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001913
Mark Dickinsone2846542012-04-20 21:21:24 +01001914 /* Compute exact length 'sz' of output string. */
1915 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001916 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001917 }
1918 else {
1919 Py_ssize_t size_a_in_bits;
1920 /* Ensure overflow doesn't occur during computation of sz. */
1921 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1922 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001923 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001924 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001925 }
1926 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001927 _Py_bit_length(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001928 /* Allow 1 character for a '-' sign. */
1929 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1930 }
1931 if (alternate) {
1932 /* 2 characters for prefix */
1933 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001934 }
1935
Victor Stinnerd3f08822012-05-29 12:57:52 +02001936 if (writer) {
1937 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1938 return -1;
1939 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001941 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001942 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1943 if (*bytes_str == NULL)
1944 return -1;
1945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001947 v = PyUnicode_New(sz, 'x');
1948 if (v == NULL)
1949 return -1;
1950 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001952
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001953#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001954 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001955 if (size_a == 0) { \
1956 *--p = '0'; \
1957 } \
1958 else { \
1959 /* JRH: special case for power-of-2 bases */ \
1960 twodigits accum = 0; \
1961 int accumbits = 0; /* # of bits in accum */ \
1962 Py_ssize_t i; \
1963 for (i = 0; i < size_a; ++i) { \
1964 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1965 accumbits += PyLong_SHIFT; \
1966 assert(accumbits >= bits); \
1967 do { \
1968 char cdigit; \
1969 cdigit = (char)(accum & (base - 1)); \
1970 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1971 *--p = cdigit; \
1972 accumbits -= bits; \
1973 accum >>= bits; \
1974 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1975 } \
1976 } \
1977 \
1978 if (alternate) { \
1979 if (base == 16) \
1980 *--p = 'x'; \
1981 else if (base == 8) \
1982 *--p = 'o'; \
1983 else /* (base == 2) */ \
1984 *--p = 'b'; \
1985 *--p = '0'; \
1986 } \
1987 if (negative) \
1988 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001989 } while (0)
1990
1991#define WRITE_UNICODE_DIGITS(TYPE) \
1992 do { \
1993 if (writer) \
1994 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1995 else \
1996 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1997 \
1998 WRITE_DIGITS(p); \
1999 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002000 if (writer) \
2001 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2002 else \
2003 assert(p == (TYPE*)PyUnicode_DATA(v)); \
2004 } while (0)
2005
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002006 if (bytes_writer) {
2007 char *p = *bytes_str + sz;
2008 WRITE_DIGITS(p);
2009 assert(p == *bytes_str);
2010 }
2011 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002012 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002013 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002014 }
2015 else if (kind == PyUnicode_2BYTE_KIND) {
2016 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002017 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002018 }
2019 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002020 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002021 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002022 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002023 }
2024#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002025#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002026
2027 if (writer) {
2028 writer->pos += sz;
2029 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002030 else if (bytes_writer) {
2031 (*bytes_str) += sz;
2032 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002033 else {
2034 assert(_PyUnicode_CheckConsistency(v, 1));
2035 *p_output = v;
2036 }
2037 return 0;
2038}
2039
2040PyObject *
2041_PyLong_Format(PyObject *obj, int base)
2042{
2043 PyObject *str;
2044 int err;
2045 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002046 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002047 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002048 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002049 if (err == -1)
2050 return NULL;
2051 return str;
2052}
2053
2054int
2055_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2056 PyObject *obj,
2057 int base, int alternate)
2058{
2059 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002060 return long_to_decimal_string_internal(obj, NULL, writer,
2061 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002062 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002063 return long_format_binary(obj, base, alternate, NULL, writer,
2064 NULL, NULL);
2065}
2066
2067char*
2068_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2069 PyObject *obj,
2070 int base, int alternate)
2071{
2072 char *str2;
2073 int res;
2074 str2 = str;
2075 if (base == 10)
2076 res = long_to_decimal_string_internal(obj, NULL, NULL,
2077 writer, &str2);
2078 else
2079 res = long_format_binary(obj, base, alternate, NULL, NULL,
2080 writer, &str2);
2081 if (res < 0)
2082 return NULL;
2083 assert(str2 != NULL);
2084 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002085}
2086
Thomas Wouters477c8d52006-05-27 19:21:47 +00002087/* Table of digit values for 8-bit string -> integer conversion.
2088 * '0' maps to 0, ..., '9' maps to 9.
2089 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2090 * All other indices map to 37.
2091 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002092 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002093 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002094unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2096 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2097 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2098 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2099 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2100 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2101 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2102 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2103 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2104 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2105 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2106 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2107 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2108 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 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,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002111};
2112
2113/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002114 * 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 +03002115 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002116 * The point to this routine is that it takes time linear in the number of
2117 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002118 *
2119 * Return values:
2120 * -1 on syntax error (exception needs to be set, *res is untouched)
2121 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002122 */
Brett Cannona721aba2016-09-09 14:57:09 -07002123static int
2124long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002125{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002126 const char *p = *str;
2127 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002128 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002129 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 int bits_per_char;
2131 Py_ssize_t n;
2132 PyLongObject *z;
2133 twodigits accum;
2134 int bits_in_accum;
2135 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2138 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002139 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002141 }
2142 /* count digits and set p to end-of-string */
2143 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2144 if (*p == '_') {
2145 if (prev == '_') {
2146 *str = p - 1;
2147 return -1;
2148 }
2149 } else {
2150 ++digits;
2151 }
2152 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002154 }
2155 if (prev == '_') {
2156 /* Trailing underscore not allowed. */
2157 *str = p - 1;
2158 return -1;
2159 }
2160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002162 /* n <- the number of Python digits needed,
2163 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2164 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 PyErr_SetString(PyExc_ValueError,
2166 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002167 *res = NULL;
2168 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002170 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002172 if (z == NULL) {
2173 *res = NULL;
2174 return 0;
2175 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002176 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 * from least to most significant in both.
2178 */
2179 accum = 0;
2180 bits_in_accum = 0;
2181 pdigit = z->ob_digit;
2182 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002183 int k;
2184 if (*p == '_') {
2185 continue;
2186 }
2187 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 assert(k >= 0 && k < base);
2189 accum |= (twodigits)k << bits_in_accum;
2190 bits_in_accum += bits_per_char;
2191 if (bits_in_accum >= PyLong_SHIFT) {
2192 *pdigit++ = (digit)(accum & PyLong_MASK);
2193 assert(pdigit - z->ob_digit <= n);
2194 accum >>= PyLong_SHIFT;
2195 bits_in_accum -= PyLong_SHIFT;
2196 assert(bits_in_accum < PyLong_SHIFT);
2197 }
2198 }
2199 if (bits_in_accum) {
2200 assert(bits_in_accum <= PyLong_SHIFT);
2201 *pdigit++ = (digit)accum;
2202 assert(pdigit - z->ob_digit <= n);
2203 }
2204 while (pdigit - z->ob_digit < n)
2205 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002206 *res = long_normalize(z);
2207 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002208}
2209
Serhiy Storchaka95949422013-08-27 19:40:23 +03002210/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002211 * ignored.
2212 *
2213 * If successful, a PyLong object will be returned and 'pend' will be pointing
2214 * to the first unused byte unless it's NULL.
2215 *
2216 * If unsuccessful, NULL will be returned.
2217 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002218PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002219PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002222 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 PyLongObject *z = NULL;
2224 PyObject *strobj;
2225 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 if ((base != 0 && base < 2) || base > 36) {
2228 PyErr_SetString(PyExc_ValueError,
2229 "int() arg 2 must be >= 2 and <= 36");
2230 return NULL;
2231 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002232 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002234 }
2235 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002237 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 else if (*str == '-') {
2239 ++str;
2240 sign = -1;
2241 }
2242 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002243 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002245 }
2246 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002248 }
2249 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002251 }
2252 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002254 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 else {
2256 /* "old" (C-style) octal literal, now invalid.
2257 it might still be zero though */
2258 error_if_nonzero = 1;
2259 base = 10;
2260 }
2261 }
2262 if (str[0] == '0' &&
2263 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2264 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002265 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002267 /* One underscore allowed here. */
2268 if (*str == '_') {
2269 ++str;
2270 }
2271 }
2272 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002273 /* May not start with underscores. */
2274 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002275 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002278 if ((base & (base - 1)) == 0) {
2279 int res = long_from_binary_base(&str, base, &z);
2280 if (res < 0) {
2281 /* Syntax error. */
2282 goto onError;
2283 }
2284 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002286/***
2287Binary bases can be converted in time linear in the number of digits, because
2288Python's representation base is binary. Other bases (including decimal!) use
2289the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002290
Thomas Wouters477c8d52006-05-27 19:21:47 +00002291First some math: the largest integer that can be expressed in N base-B digits
2292is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2293case number of Python digits needed to hold it is the smallest integer n s.t.
2294
2295 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2296 BASE**n >= B**N [taking logs to base BASE]
2297 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2298
2299The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002300this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002301and the result is computed into it.
2302
2303The input string is actually treated as being in base base**i (i.e., i digits
2304are processed at a time), where two more static arrays hold:
2305
2306 convwidth_base[base] = the largest integer i such that base**i <= BASE
2307 convmultmax_base[base] = base ** convwidth_base[base]
2308
2309The first of these is the largest i such that i consecutive input digits
2310must fit in a single Python digit. The second is effectively the input
2311base we're really using.
2312
2313Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2314convmultmax_base[base], the result is "simply"
2315
2316 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2317
2318where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002319
2320Error analysis: as above, the number of Python digits `n` needed is worst-
2321case
2322
2323 n >= N * log(B)/log(BASE)
2324
2325where `N` is the number of input digits in base `B`. This is computed via
2326
2327 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2328
2329below. Two numeric concerns are how much space this can waste, and whether
2330the computed result can be too small. To be concrete, assume BASE = 2**15,
2331which is the default (and it's unlikely anyone changes that).
2332
2333Waste isn't a problem: provided the first input digit isn't 0, the difference
2334between the worst-case input with N digits and the smallest input with N
2335digits is about a factor of B, but B is small compared to BASE so at most
2336one allocated Python digit can remain unused on that count. If
2337N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2338and adding 1 returns a result 1 larger than necessary. However, that can't
2339happen: whenever B is a power of 2, long_from_binary_base() is called
2340instead, and it's impossible for B**i to be an integer power of 2**15 when
2341B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2342an exact integer when B is not a power of 2, since B**i has a prime factor
2343other than 2 in that case, but (2**15)**j's only prime factor is 2).
2344
2345The computed result can be too small if the true value of N*log(B)/log(BASE)
2346is a little bit larger than an exact integer, but due to roundoff errors (in
2347computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2348yields a numeric result a little less than that integer. Unfortunately, "how
2349close can a transcendental function get to an integer over some range?"
2350questions are generally theoretically intractable. Computer analysis via
2351continued fractions is practical: expand log(B)/log(BASE) via continued
2352fractions, giving a sequence i/j of "the best" rational approximations. Then
2353j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2354we can get very close to being in trouble, but very rarely. For example,
235576573 is a denominator in one of the continued-fraction approximations to
2356log(10)/log(2**15), and indeed:
2357
2358 >>> log(10)/log(2**15)*76573
2359 16958.000000654003
2360
2361is very close to an integer. If we were working with IEEE single-precision,
2362rounding errors could kill us. Finding worst cases in IEEE double-precision
2363requires better-than-double-precision log() functions, and Tim didn't bother.
2364Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002365new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002366This should happen extremely rarely, and in fact I don't have a test case
2367that triggers it(!). Instead the code was tested by artificially allocating
2368just 1 digit at the start, so that the copying code was exercised for every
2369digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002370***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002371 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002373 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 int i;
2375 int convwidth;
2376 twodigits convmultmax, convmult;
2377 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002378 const char *scan, *lastdigit;
2379 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 static double log_base_BASE[37] = {0.0e0,};
2382 static int convwidth_base[37] = {0,};
2383 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 if (log_base_BASE[base] == 0.0) {
2386 twodigits convmax = base;
2387 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002388
Mark Dickinson22b20182010-05-10 21:27:53 +00002389 log_base_BASE[base] = (log((double)base) /
2390 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 for (;;) {
2392 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002393 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002395 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 convmax = next;
2397 ++i;
2398 }
2399 convmultmax_base[base] = convmax;
2400 assert(i > 0);
2401 convwidth_base[base] = i;
2402 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* Find length of the string of numeric characters. */
2405 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002406 lastdigit = str;
2407
2408 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2409 if (*scan == '_') {
2410 if (prev == '_') {
2411 /* Only one underscore allowed. */
2412 str = lastdigit + 1;
2413 goto onError;
2414 }
2415 }
2416 else {
2417 ++digits;
2418 lastdigit = scan;
2419 }
2420 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002422 }
2423 if (prev == '_') {
2424 /* Trailing underscore not allowed. */
2425 /* Set error pointer to first underscore. */
2426 str = lastdigit + 1;
2427 goto onError;
2428 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002429
Serhiy Storchaka95949422013-08-27 19:40:23 +03002430 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 * integer with this base and length. Note that there's no
2432 * need to initialize z->ob_digit -- no slot is read up before
2433 * being stored into.
2434 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002435 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2436 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002437 /* The same exception as in _PyLong_New(). */
2438 PyErr_SetString(PyExc_OverflowError,
2439 "too many digits in integer");
2440 return NULL;
2441 }
2442 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 /* Uncomment next line to test exceedingly rare copy code */
2444 /* size_z = 1; */
2445 assert(size_z > 0);
2446 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002447 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002449 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002450 Py_SET_SIZE(z, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 /* `convwidth` consecutive input digits are treated as a single
2453 * digit in base `convmultmax`.
2454 */
2455 convwidth = convwidth_base[base];
2456 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* Work ;-) */
2459 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002460 if (*str == '_') {
2461 str++;
2462 continue;
2463 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 /* grab up to convwidth digits from the input string */
2465 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002466 for (i = 1; i < convwidth && str != scan; ++str) {
2467 if (*str == '_') {
2468 continue;
2469 }
2470 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002472 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 assert(c < PyLong_BASE);
2474 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 convmult = convmultmax;
2477 /* Calculate the shift only if we couldn't get
2478 * convwidth digits.
2479 */
2480 if (i != convwidth) {
2481 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002482 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002484 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 /* Multiply z by convmult, and add c. */
2488 pz = z->ob_digit;
2489 pzstop = pz + Py_SIZE(z);
2490 for (; pz < pzstop; ++pz) {
2491 c += (twodigits)*pz * convmult;
2492 *pz = (digit)(c & PyLong_MASK);
2493 c >>= PyLong_SHIFT;
2494 }
2495 /* carry off the current end? */
2496 if (c) {
2497 assert(c < PyLong_BASE);
2498 if (Py_SIZE(z) < size_z) {
2499 *pz = (digit)c;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002500 Py_SET_SIZE(z, Py_SIZE(z) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 }
2502 else {
2503 PyLongObject *tmp;
2504 /* Extremely rare. Get more space. */
2505 assert(Py_SIZE(z) == size_z);
2506 tmp = _PyLong_New(size_z + 1);
2507 if (tmp == NULL) {
2508 Py_DECREF(z);
2509 return NULL;
2510 }
2511 memcpy(tmp->ob_digit,
2512 z->ob_digit,
2513 sizeof(digit) * size_z);
2514 Py_DECREF(z);
2515 z = tmp;
2516 z->ob_digit[size_z] = (digit)c;
2517 ++size_z;
2518 }
2519 }
2520 }
2521 }
Brett Cannona721aba2016-09-09 14:57:09 -07002522 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002524 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 if (error_if_nonzero) {
2526 /* reset the base to 0, else the exception message
2527 doesn't make too much sense */
2528 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002529 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002531 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 /* there might still be other problems, therefore base
2533 remains zero here for the same reason */
2534 }
Brett Cannona721aba2016-09-09 14:57:09 -07002535 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002537 }
2538 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002539 Py_SET_SIZE(z, -(Py_SIZE(z)));
Brett Cannona721aba2016-09-09 14:57:09 -07002540 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002541 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002543 }
2544 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002546 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002548 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002549 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002550 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002551 }
2552 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002553 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002554 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002555 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002556
Mark Dickinson22b20182010-05-10 21:27:53 +00002557 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002558 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002559 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 Py_XDECREF(z);
2562 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2563 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002564 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002566 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002568 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 base, strobj);
2570 Py_DECREF(strobj);
2571 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002572}
2573
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002574/* Since PyLong_FromString doesn't have a length parameter,
2575 * check here for possible NULs in the string.
2576 *
2577 * Reports an invalid literal as a bytes object.
2578 */
2579PyObject *
2580_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2581{
2582 PyObject *result, *strobj;
2583 char *end = NULL;
2584
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002585 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002586 if (end == NULL || (result != NULL && end == s + len))
2587 return result;
2588 Py_XDECREF(result);
2589 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2590 if (strobj != NULL) {
2591 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002592 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002593 base, strobj);
2594 Py_DECREF(strobj);
2595 }
2596 return NULL;
2597}
2598
Guido van Rossum9e896b32000-04-05 20:11:21 +00002599PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002600PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002601{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002602 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002603 if (unicode == NULL)
2604 return NULL;
2605 v = PyLong_FromUnicodeObject(unicode, base);
2606 Py_DECREF(unicode);
2607 return v;
2608}
2609
2610PyObject *
2611PyLong_FromUnicodeObject(PyObject *u, int base)
2612{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002613 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002614 const char *buffer;
2615 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002616 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002617
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002618 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002619 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002621 assert(PyUnicode_IS_ASCII(asciidig));
2622 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002623 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002624 assert(buffer != NULL);
2625
2626 result = PyLong_FromString(buffer, &end, base);
2627 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002628 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002629 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002631 Py_DECREF(asciidig);
2632 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002633 PyErr_Format(PyExc_ValueError,
2634 "invalid literal for int() with base %d: %.200R",
2635 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002636 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002637}
2638
Tim Peters9f688bf2000-07-07 15:53:28 +00002639/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002640static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002642static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002643
Serhiy Storchaka95949422013-08-27 19:40:23 +03002644/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002645
Guido van Rossume32e0141992-01-19 16:31:05 +00002646static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002647long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002649{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002650 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 if (size_b == 0) {
2654 PyErr_SetString(PyExc_ZeroDivisionError,
2655 "integer division or modulo by zero");
2656 return -1;
2657 }
2658 if (size_a < size_b ||
2659 (size_a == size_b &&
2660 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2661 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002662 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002663 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002664 return -1;
2665 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002666 Py_INCREF(_PyLong_Zero);
2667 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 return 0;
2669 }
2670 if (size_b == 1) {
2671 digit rem = 0;
2672 z = divrem1(a, b->ob_digit[0], &rem);
2673 if (z == NULL)
2674 return -1;
2675 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2676 if (*prem == NULL) {
2677 Py_DECREF(z);
2678 return -1;
2679 }
2680 }
2681 else {
2682 z = x_divrem(a, b, prem);
2683 if (z == NULL)
2684 return -1;
2685 }
2686 /* Set the signs.
2687 The quotient z has the sign of a*b;
2688 the remainder r has the sign of a,
2689 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002690 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2691 _PyLong_Negate(&z);
2692 if (z == NULL) {
2693 Py_CLEAR(*prem);
2694 return -1;
2695 }
2696 }
2697 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2698 _PyLong_Negate(prem);
2699 if (*prem == NULL) {
2700 Py_DECREF(z);
2701 Py_CLEAR(*prem);
2702 return -1;
2703 }
2704 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 *pdiv = maybe_small_long(z);
2706 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002707}
2708
Serhiy Storchaka95949422013-08-27 19:40:23 +03002709/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002710 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002711
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002712static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002713x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 PyLongObject *v, *w, *a;
2716 Py_ssize_t i, k, size_v, size_w;
2717 int d;
2718 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2719 twodigits vv;
2720 sdigit zhi;
2721 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2724 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2725 handle the special case when the initial estimate q for a quotient
2726 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2727 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002730 size_v = Py_ABS(Py_SIZE(v1));
2731 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2733 v = _PyLong_New(size_v+1);
2734 if (v == NULL) {
2735 *prem = NULL;
2736 return NULL;
2737 }
2738 w = _PyLong_New(size_w);
2739 if (w == NULL) {
2740 Py_DECREF(v);
2741 *prem = NULL;
2742 return NULL;
2743 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2746 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002747 d = PyLong_SHIFT - _Py_bit_length(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2749 assert(carry == 0);
2750 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2751 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2752 v->ob_digit[size_v] = carry;
2753 size_v++;
2754 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2757 at most (and usually exactly) k = size_v - size_w digits. */
2758 k = size_v - size_w;
2759 assert(k >= 0);
2760 a = _PyLong_New(k);
2761 if (a == NULL) {
2762 Py_DECREF(w);
2763 Py_DECREF(v);
2764 *prem = NULL;
2765 return NULL;
2766 }
2767 v0 = v->ob_digit;
2768 w0 = w->ob_digit;
2769 wm1 = w0[size_w-1];
2770 wm2 = w0[size_w-2];
2771 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2772 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2773 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002776 Py_DECREF(a);
2777 Py_DECREF(w);
2778 Py_DECREF(v);
2779 *prem = NULL;
2780 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002781 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 /* estimate quotient digit q; may overestimate by 1 (rare) */
2784 vtop = vk[size_w];
2785 assert(vtop <= wm1);
2786 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2787 q = (digit)(vv / wm1);
2788 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2789 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2790 | vk[size_w-2])) {
2791 --q;
2792 r += wm1;
2793 if (r >= PyLong_BASE)
2794 break;
2795 }
2796 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2799 zhi = 0;
2800 for (i = 0; i < size_w; ++i) {
2801 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2802 -PyLong_BASE * q <= z < PyLong_BASE */
2803 z = (sdigit)vk[i] + zhi -
2804 (stwodigits)q * (stwodigits)w0[i];
2805 vk[i] = (digit)z & PyLong_MASK;
2806 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002807 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 /* add w back if q was too large (this branch taken rarely) */
2811 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2812 if ((sdigit)vtop + zhi < 0) {
2813 carry = 0;
2814 for (i = 0; i < size_w; ++i) {
2815 carry += vk[i] + w0[i];
2816 vk[i] = carry & PyLong_MASK;
2817 carry >>= PyLong_SHIFT;
2818 }
2819 --q;
2820 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 /* store quotient digit */
2823 assert(q < PyLong_BASE);
2824 *--ak = q;
2825 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 /* unshift remainder; we reuse w to store the result */
2828 carry = v_rshift(w0, v0, size_w, d);
2829 assert(carry==0);
2830 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 *prem = long_normalize(w);
2833 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002834}
2835
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002836/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2837 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2838 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2839 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2840 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2841 -1.0. */
2842
2843/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2844#if DBL_MANT_DIG == 53
2845#define EXP2_DBL_MANT_DIG 9007199254740992.0
2846#else
2847#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2848#endif
2849
2850double
2851_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2854 /* See below for why x_digits is always large enough. */
Dong-hee Nab88cd582020-05-04 22:32:42 +09002855 digit rem;
2856 digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 double dx;
2858 /* Correction term for round-half-to-even rounding. For a digit x,
2859 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2860 multiple of 4, rounding ties to a multiple of 8. */
2861 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002862
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002863 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 if (a_size == 0) {
2865 /* Special case for 0: significand 0.0, exponent 0. */
2866 *e = 0;
2867 return 0.0;
2868 }
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002869 a_bits = _Py_bit_length(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 /* The following is an overflow-free version of the check
2871 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2872 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2873 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2874 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002875 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2879 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 Number of digits needed for result: write // for floor division.
2882 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2891 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2894 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2895 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 in both cases.
2902 */
2903 if (a_bits <= DBL_MANT_DIG + 2) {
2904 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2905 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
Dong-hee Nab88cd582020-05-04 22:32:42 +09002906 x_size = shift_digits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2908 (int)shift_bits);
2909 x_size += a_size;
2910 x_digits[x_size++] = rem;
2911 }
2912 else {
2913 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2914 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2915 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2916 a_size - shift_digits, (int)shift_bits);
2917 x_size = a_size - shift_digits;
2918 /* For correct rounding below, we need the least significant
2919 bit of x to be 'sticky' for this shift: if any of the bits
2920 shifted out was nonzero, we set the least significant bit
2921 of x. */
2922 if (rem)
2923 x_digits[0] |= 1;
2924 else
2925 while (shift_digits > 0)
2926 if (a->ob_digit[--shift_digits]) {
2927 x_digits[0] |= 1;
2928 break;
2929 }
2930 }
Victor Stinner63941882011-09-29 00:42:28 +02002931 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 /* Round, and convert to double. */
2934 x_digits[0] += half_even_correction[x_digits[0] & 7];
2935 dx = x_digits[--x_size];
2936 while (x_size > 0)
2937 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 /* Rescale; make correction if result is 1.0. */
2940 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2941 if (dx == 1.0) {
2942 if (a_bits == PY_SSIZE_T_MAX)
2943 goto overflow;
2944 dx = 0.5;
2945 a_bits += 1;
2946 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 *e = a_bits;
2949 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002950
2951 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 /* exponent > PY_SSIZE_T_MAX */
2953 PyErr_SetString(PyExc_OverflowError,
2954 "huge integer: number of bits overflows a Py_ssize_t");
2955 *e = 0;
2956 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002957}
2958
Serhiy Storchaka95949422013-08-27 19:40:23 +03002959/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002960 using the round-half-to-even rule in the case of a tie. */
2961
2962double
2963PyLong_AsDouble(PyObject *v)
2964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 Py_ssize_t exponent;
2966 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002967
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002968 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 PyErr_BadInternalCall();
2970 return -1.0;
2971 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002972 if (!PyLong_Check(v)) {
2973 PyErr_SetString(PyExc_TypeError, "an integer is required");
2974 return -1.0;
2975 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002976 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002977 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002978 to double. This improves performance of FP/long operations
2979 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002980 */
2981 return (double)MEDIUM_VALUE((PyLongObject *)v);
2982 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2984 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2985 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002986 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 return -1.0;
2988 }
2989 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002990}
2991
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002992/* Methods */
2993
HongWeipeng42acb7b2019-09-18 23:10:15 +08002994/* if a < b, return a negative number
2995 if a == b, return 0
2996 if a > b, return a positive number */
2997
2998static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002999long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003000{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003001 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
3002 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003003 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08003004 sdigit diff = 0;
3005 while (--i >= 0) {
3006 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
3007 if (diff) {
3008 break;
3009 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003011 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003013 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003014}
3015
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003016static PyObject *
3017long_richcompare(PyObject *self, PyObject *other, int op)
3018{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003019 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 CHECK_BINOP(self, other);
3021 if (self == other)
3022 result = 0;
3023 else
3024 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003025 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003026}
3027
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003028static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003029long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003030{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003031 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 Py_ssize_t i;
3033 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 i = Py_SIZE(v);
3036 switch(i) {
3037 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3038 case 0: return 0;
3039 case 1: return v->ob_digit[0];
3040 }
3041 sign = 1;
3042 x = 0;
3043 if (i < 0) {
3044 sign = -1;
3045 i = -(i);
3046 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003048 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3049 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3050 _PyHASH_MODULUS.
3051
3052 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3053 amounts to a rotation of the bits of x. To see this, write
3054
3055 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3056
3057 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3058 PyLong_SHIFT bits of x (those that are shifted out of the
3059 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3060 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3061 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3062 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3063 congruent to y modulo _PyHASH_MODULUS. So
3064
3065 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3066
3067 The right-hand side is just the result of rotating the
3068 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3069 not all _PyHASH_BITS bits of x are 1s, the same is true
3070 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3071 the reduction of x*2**PyLong_SHIFT modulo
3072 _PyHASH_MODULUS. */
3073 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3074 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003076 if (x >= _PyHASH_MODULUS)
3077 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 }
3079 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003080 if (x == (Py_uhash_t)-1)
3081 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003082 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003083}
3084
3085
Serhiy Storchaka95949422013-08-27 19:40:23 +03003086/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003087
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003088static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003089x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003090{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003091 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 PyLongObject *z;
3093 Py_ssize_t i;
3094 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 /* Ensure a is the larger of the two: */
3097 if (size_a < size_b) {
3098 { PyLongObject *temp = a; a = b; b = temp; }
3099 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003100 size_a = size_b;
3101 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 }
3103 z = _PyLong_New(size_a+1);
3104 if (z == NULL)
3105 return NULL;
3106 for (i = 0; i < size_b; ++i) {
3107 carry += a->ob_digit[i] + b->ob_digit[i];
3108 z->ob_digit[i] = carry & PyLong_MASK;
3109 carry >>= PyLong_SHIFT;
3110 }
3111 for (; i < size_a; ++i) {
3112 carry += a->ob_digit[i];
3113 z->ob_digit[i] = carry & PyLong_MASK;
3114 carry >>= PyLong_SHIFT;
3115 }
3116 z->ob_digit[i] = carry;
3117 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003118}
3119
3120/* Subtract the absolute values of two integers. */
3121
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003122static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003123x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003124{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003125 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 PyLongObject *z;
3127 Py_ssize_t i;
3128 int sign = 1;
3129 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 /* Ensure a is the larger of the two: */
3132 if (size_a < size_b) {
3133 sign = -1;
3134 { PyLongObject *temp = a; a = b; b = temp; }
3135 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003136 size_a = size_b;
3137 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 }
3139 else if (size_a == size_b) {
3140 /* Find highest digit where a and b differ: */
3141 i = size_a;
3142 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3143 ;
3144 if (i < 0)
3145 return (PyLongObject *)PyLong_FromLong(0);
3146 if (a->ob_digit[i] < b->ob_digit[i]) {
3147 sign = -1;
3148 { PyLongObject *temp = a; a = b; b = temp; }
3149 }
3150 size_a = size_b = i+1;
3151 }
3152 z = _PyLong_New(size_a);
3153 if (z == NULL)
3154 return NULL;
3155 for (i = 0; i < size_b; ++i) {
3156 /* The following assumes unsigned arithmetic
3157 works module 2**N for some N>PyLong_SHIFT. */
3158 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3159 z->ob_digit[i] = borrow & PyLong_MASK;
3160 borrow >>= PyLong_SHIFT;
3161 borrow &= 1; /* Keep only one sign bit */
3162 }
3163 for (; i < size_a; ++i) {
3164 borrow = a->ob_digit[i] - borrow;
3165 z->ob_digit[i] = borrow & PyLong_MASK;
3166 borrow >>= PyLong_SHIFT;
3167 borrow &= 1; /* Keep only one sign bit */
3168 }
3169 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003170 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003171 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02003172 }
HongWeipeng036fe852019-11-26 15:54:49 +08003173 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003174}
3175
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003176static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003177long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003182
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003183 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003184 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 }
3186 if (Py_SIZE(a) < 0) {
3187 if (Py_SIZE(b) < 0) {
3188 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003189 if (z != NULL) {
3190 /* x_add received at least one multiple-digit int,
3191 and thus z must be a multiple-digit int.
3192 That also means z is not an element of
3193 small_ints, so negating it in-place is safe. */
3194 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003195 Py_SET_SIZE(z, -(Py_SIZE(z)));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003196 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 }
3198 else
3199 z = x_sub(b, a);
3200 }
3201 else {
3202 if (Py_SIZE(b) < 0)
3203 z = x_sub(a, b);
3204 else
3205 z = x_add(a, b);
3206 }
3207 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003208}
3209
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003210static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003211long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003216
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003217 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003218 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 }
3220 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003221 if (Py_SIZE(b) < 0) {
3222 z = x_sub(b, a);
3223 }
3224 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003226 if (z != NULL) {
3227 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003228 Py_SET_SIZE(z, -(Py_SIZE(z)));
HongWeipeng036fe852019-11-26 15:54:49 +08003229 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003230 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 }
3232 else {
3233 if (Py_SIZE(b) < 0)
3234 z = x_add(a, b);
3235 else
3236 z = x_sub(a, b);
3237 }
3238 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003239}
3240
Tim Peters5af4e6c2002-08-12 02:31:19 +00003241/* Grade school multiplication, ignoring the signs.
3242 * Returns the absolute value of the product, or NULL if error.
3243 */
3244static PyLongObject *
3245x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003248 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3249 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 z = _PyLong_New(size_a + size_b);
3253 if (z == NULL)
3254 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3257 if (a == b) {
3258 /* Efficient squaring per HAC, Algorithm 14.16:
3259 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3260 * Gives slightly less than a 2x speedup when a == b,
3261 * via exploiting that each entry in the multiplication
3262 * pyramid appears twice (except for the size_a squares).
3263 */
3264 for (i = 0; i < size_a; ++i) {
3265 twodigits carry;
3266 twodigits f = a->ob_digit[i];
3267 digit *pz = z->ob_digit + (i << 1);
3268 digit *pa = a->ob_digit + i + 1;
3269 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003272 Py_DECREF(z);
3273 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003274 });
Tim Peters0973b992004-08-29 22:16:50 +00003275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 carry = *pz + f * f;
3277 *pz++ = (digit)(carry & PyLong_MASK);
3278 carry >>= PyLong_SHIFT;
3279 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 /* Now f is added in twice in each column of the
3282 * pyramid it appears. Same as adding f<<1 once.
3283 */
3284 f <<= 1;
3285 while (pa < paend) {
3286 carry += *pz + *pa++ * f;
3287 *pz++ = (digit)(carry & PyLong_MASK);
3288 carry >>= PyLong_SHIFT;
3289 assert(carry <= (PyLong_MASK << 1));
3290 }
3291 if (carry) {
3292 carry += *pz;
3293 *pz++ = (digit)(carry & PyLong_MASK);
3294 carry >>= PyLong_SHIFT;
3295 }
3296 if (carry)
3297 *pz += (digit)(carry & PyLong_MASK);
3298 assert((carry >> PyLong_SHIFT) == 0);
3299 }
3300 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003301 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 for (i = 0; i < size_a; ++i) {
3303 twodigits carry = 0;
3304 twodigits f = a->ob_digit[i];
3305 digit *pz = z->ob_digit + i;
3306 digit *pb = b->ob_digit;
3307 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003310 Py_DECREF(z);
3311 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003312 });
Tim Peters0973b992004-08-29 22:16:50 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 while (pb < pbend) {
3315 carry += *pz + *pb++ * f;
3316 *pz++ = (digit)(carry & PyLong_MASK);
3317 carry >>= PyLong_SHIFT;
3318 assert(carry <= PyLong_MASK);
3319 }
3320 if (carry)
3321 *pz += (digit)(carry & PyLong_MASK);
3322 assert((carry >> PyLong_SHIFT) == 0);
3323 }
3324 }
3325 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003326}
3327
3328/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003329 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003330 split, and sets low and high such that abs(n) == (high << size) + low,
3331 viewing the shift as being by digits. The sign bit is ignored, and
3332 the return values are >= 0.
3333 Returns 0 on success, -1 on failure.
3334*/
3335static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003336kmul_split(PyLongObject *n,
3337 Py_ssize_t size,
3338 PyLongObject **high,
3339 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 PyLongObject *hi, *lo;
3342 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003343 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003344
Victor Stinner640c35c2013-06-04 23:14:37 +02003345 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 if ((hi = _PyLong_New(size_hi)) == NULL)
3349 return -1;
3350 if ((lo = _PyLong_New(size_lo)) == NULL) {
3351 Py_DECREF(hi);
3352 return -1;
3353 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3356 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 *high = long_normalize(hi);
3359 *low = long_normalize(lo);
3360 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003361}
3362
Tim Peters60004642002-08-12 22:01:34 +00003363static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3364
Tim Peters5af4e6c2002-08-12 02:31:19 +00003365/* Karatsuba multiplication. Ignores the input signs, and returns the
3366 * absolute value of the product (or NULL if error).
3367 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3368 */
3369static PyLongObject *
3370k_mul(PyLongObject *a, PyLongObject *b)
3371{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003372 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3373 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 PyLongObject *ah = NULL;
3375 PyLongObject *al = NULL;
3376 PyLongObject *bh = NULL;
3377 PyLongObject *bl = NULL;
3378 PyLongObject *ret = NULL;
3379 PyLongObject *t1, *t2, *t3;
3380 Py_ssize_t shift; /* the number of digits we split off */
3381 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3384 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3385 * Then the original product is
3386 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3387 * By picking X to be a power of 2, "*X" is just shifting, and it's
3388 * been reduced to 3 multiplies on numbers half the size.
3389 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 /* We want to split based on the larger number; fiddle so that b
3392 * is largest.
3393 */
3394 if (asize > bsize) {
3395 t1 = a;
3396 a = b;
3397 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 i = asize;
3400 asize = bsize;
3401 bsize = i;
3402 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 /* Use gradeschool math when either number is too small. */
3405 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3406 if (asize <= i) {
3407 if (asize == 0)
3408 return (PyLongObject *)PyLong_FromLong(0);
3409 else
3410 return x_mul(a, b);
3411 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 /* If a is small compared to b, splitting on b gives a degenerate
3414 * case with ah==0, and Karatsuba may be (even much) less efficient
3415 * than "grade school" then. However, we can still win, by viewing
3416 * b as a string of "big digits", each of width a->ob_size. That
3417 * leads to a sequence of balanced calls to k_mul.
3418 */
3419 if (2 * asize <= bsize)
3420 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 /* Split a & b into hi & lo pieces. */
3423 shift = bsize >> 1;
3424 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3425 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 if (a == b) {
3428 bh = ah;
3429 bl = al;
3430 Py_INCREF(bh);
3431 Py_INCREF(bl);
3432 }
3433 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 /* The plan:
3436 * 1. Allocate result space (asize + bsize digits: that's always
3437 * enough).
3438 * 2. Compute ah*bh, and copy into result at 2*shift.
3439 * 3. Compute al*bl, and copy into result at 0. Note that this
3440 * can't overlap with #2.
3441 * 4. Subtract al*bl from the result, starting at shift. This may
3442 * underflow (borrow out of the high digit), but we don't care:
3443 * we're effectively doing unsigned arithmetic mod
3444 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3445 * borrows and carries out of the high digit can be ignored.
3446 * 5. Subtract ah*bh from the result, starting at shift.
3447 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3448 * at shift.
3449 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 /* 1. Allocate result space. */
3452 ret = _PyLong_New(asize + bsize);
3453 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003454#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 /* Fill with trash, to catch reference to uninitialized digits. */
3456 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003457#endif
Tim Peters44121a62002-08-12 06:17:58 +00003458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3460 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3461 assert(Py_SIZE(t1) >= 0);
3462 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3463 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3464 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 /* Zero-out the digits higher than the ah*bh copy. */
3467 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3468 if (i)
3469 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3470 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 /* 3. t2 <- al*bl, and copy into the low digits. */
3473 if ((t2 = k_mul(al, bl)) == NULL) {
3474 Py_DECREF(t1);
3475 goto fail;
3476 }
3477 assert(Py_SIZE(t2) >= 0);
3478 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3479 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 /* Zero out remaining digits. */
3482 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3483 if (i)
3484 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3487 * because it's fresher in cache.
3488 */
3489 i = Py_SIZE(ret) - shift; /* # digits after shift */
3490 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3491 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3494 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3497 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3498 Py_DECREF(ah);
3499 Py_DECREF(al);
3500 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 if (a == b) {
3503 t2 = t1;
3504 Py_INCREF(t2);
3505 }
3506 else if ((t2 = x_add(bh, bl)) == NULL) {
3507 Py_DECREF(t1);
3508 goto fail;
3509 }
3510 Py_DECREF(bh);
3511 Py_DECREF(bl);
3512 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 t3 = k_mul(t1, t2);
3515 Py_DECREF(t1);
3516 Py_DECREF(t2);
3517 if (t3 == NULL) goto fail;
3518 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 /* Add t3. It's not obvious why we can't run out of room here.
3521 * See the (*) comment after this function.
3522 */
3523 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3524 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003527
Mark Dickinson22b20182010-05-10 21:27:53 +00003528 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 Py_XDECREF(ret);
3530 Py_XDECREF(ah);
3531 Py_XDECREF(al);
3532 Py_XDECREF(bh);
3533 Py_XDECREF(bl);
3534 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003535}
3536
Tim Petersd6974a52002-08-13 20:37:51 +00003537/* (*) Why adding t3 can't "run out of room" above.
3538
Tim Petersab86c2b2002-08-15 20:06:00 +00003539Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3540to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003541
Tim Petersab86c2b2002-08-15 20:06:00 +000035421. For any integer i, i = c(i/2) + f(i/2). In particular,
3543 bsize = c(bsize/2) + f(bsize/2).
35442. shift = f(bsize/2)
35453. asize <= bsize
35464. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3547 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003548
Tim Petersab86c2b2002-08-15 20:06:00 +00003549We allocated asize + bsize result digits, and add t3 into them at an offset
3550of shift. This leaves asize+bsize-shift allocated digit positions for t3
3551to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3552asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003553
Tim Petersab86c2b2002-08-15 20:06:00 +00003554bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3555at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003556
Tim Petersab86c2b2002-08-15 20:06:00 +00003557If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3558digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3559most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003560
Tim Petersab86c2b2002-08-15 20:06:00 +00003561The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003562
Tim Petersab86c2b2002-08-15 20:06:00 +00003563 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003564
Tim Petersab86c2b2002-08-15 20:06:00 +00003565and we have asize + c(bsize/2) available digit positions. We need to show
3566this is always enough. An instance of c(bsize/2) cancels out in both, so
3567the question reduces to whether asize digits is enough to hold
3568(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3569then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3570asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003571digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003572asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003573c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3574is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3575bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003576
Tim Peters48d52c02002-08-14 17:07:32 +00003577Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3578clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3579ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003580*/
3581
Tim Peters60004642002-08-12 22:01:34 +00003582/* b has at least twice the digits of a, and a is big enough that Karatsuba
3583 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3584 * of slices, each with a->ob_size digits, and multiply the slices by a,
3585 * one at a time. This gives k_mul balanced inputs to work with, and is
3586 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003587 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003588 * single-width slice overlap between successive partial sums).
3589 */
3590static PyLongObject *
3591k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3592{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003593 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3594 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 Py_ssize_t nbdone; /* # of b digits already multiplied */
3596 PyLongObject *ret;
3597 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 assert(asize > KARATSUBA_CUTOFF);
3600 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 /* Allocate result space, and zero it out. */
3603 ret = _PyLong_New(asize + bsize);
3604 if (ret == NULL)
3605 return NULL;
3606 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 /* Successive slices of b are copied into bslice. */
3609 bslice = _PyLong_New(asize);
3610 if (bslice == NULL)
3611 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 nbdone = 0;
3614 while (bsize > 0) {
3615 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003616 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 /* Multiply the next slice of b by a. */
3619 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3620 nbtouse * sizeof(digit));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003621 Py_SET_SIZE(bslice, nbtouse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 product = k_mul(a, bslice);
3623 if (product == NULL)
3624 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 /* Add into result. */
3627 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3628 product->ob_digit, Py_SIZE(product));
3629 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 bsize -= nbtouse;
3632 nbdone += nbtouse;
3633 }
Tim Peters60004642002-08-12 22:01:34 +00003634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 Py_DECREF(bslice);
3636 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003637
Mark Dickinson22b20182010-05-10 21:27:53 +00003638 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 Py_DECREF(ret);
3640 Py_XDECREF(bslice);
3641 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003642}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003643
3644static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003645long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003652 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003654 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 z = k_mul(a, b);
3658 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003659 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3660 _PyLong_Negate(&z);
3661 if (z == NULL)
3662 return NULL;
3663 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003665}
3666
Yury Selivanove0b23092016-02-11 10:26:27 -05003667/* Fast modulo division for single-digit longs. */
3668static PyObject *
3669fast_mod(PyLongObject *a, PyLongObject *b)
3670{
3671 sdigit left = a->ob_digit[0];
3672 sdigit right = b->ob_digit[0];
3673 sdigit mod;
3674
3675 assert(Py_ABS(Py_SIZE(a)) == 1);
3676 assert(Py_ABS(Py_SIZE(b)) == 1);
3677
3678 if (Py_SIZE(a) == Py_SIZE(b)) {
3679 /* 'a' and 'b' have the same sign. */
3680 mod = left % right;
3681 }
3682 else {
3683 /* Either 'a' or 'b' is negative. */
3684 mod = right - 1 - (left - 1) % right;
3685 }
3686
Victor Stinnerf963c132016-03-23 18:36:54 +01003687 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003688}
3689
3690/* Fast floor division for single-digit longs. */
3691static PyObject *
3692fast_floor_div(PyLongObject *a, PyLongObject *b)
3693{
3694 sdigit left = a->ob_digit[0];
3695 sdigit right = b->ob_digit[0];
3696 sdigit div;
3697
3698 assert(Py_ABS(Py_SIZE(a)) == 1);
3699 assert(Py_ABS(Py_SIZE(b)) == 1);
3700
3701 if (Py_SIZE(a) == Py_SIZE(b)) {
3702 /* 'a' and 'b' have the same sign. */
3703 div = left / right;
3704 }
3705 else {
3706 /* Either 'a' or 'b' is negative. */
3707 div = -1 - (left - 1) / right;
3708 }
3709
3710 return PyLong_FromLong(div);
3711}
3712
Guido van Rossume32e0141992-01-19 16:31:05 +00003713/* The / and % operators are now defined in terms of divmod().
3714 The expression a mod b has the value a - b*floor(a/b).
3715 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003716 |a| by |b|, with the sign of a. This is also expressed
3717 as a - b*trunc(a/b), if trunc truncates towards zero.
3718 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 a b a rem b a mod b
3720 13 10 3 3
3721 -13 10 -3 7
3722 13 -10 3 -7
3723 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003724 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003725 have different signs. We then subtract one from the 'div'
3726 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003727
Tim Peters47e52ee2004-08-30 02:44:38 +00003728/* Compute
3729 * *pdiv, *pmod = divmod(v, w)
3730 * NULL can be passed for pdiv or pmod, in which case that part of
3731 * the result is simply thrown away. The caller owns a reference to
3732 * each of these it requests (does not pass NULL for).
3733 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003734static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003735l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003739
Yury Selivanove0b23092016-02-11 10:26:27 -05003740 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3741 /* Fast path for single-digit longs */
3742 div = NULL;
3743 if (pdiv != NULL) {
3744 div = (PyLongObject *)fast_floor_div(v, w);
3745 if (div == NULL) {
3746 return -1;
3747 }
3748 }
3749 if (pmod != NULL) {
3750 mod = (PyLongObject *)fast_mod(v, w);
3751 if (mod == NULL) {
3752 Py_XDECREF(div);
3753 return -1;
3754 }
3755 *pmod = mod;
3756 }
3757 if (pdiv != NULL) {
3758 /* We only want to set `*pdiv` when `*pmod` is
3759 set successfully. */
3760 *pdiv = div;
3761 }
3762 return 0;
3763 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 if (long_divrem(v, w, &div, &mod) < 0)
3765 return -1;
3766 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3767 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3768 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 temp = (PyLongObject *) long_add(mod, w);
3770 Py_DECREF(mod);
3771 mod = temp;
3772 if (mod == NULL) {
3773 Py_DECREF(div);
3774 return -1;
3775 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003776 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3777 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 Py_DECREF(mod);
3779 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 return -1;
3781 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 Py_DECREF(div);
3783 div = temp;
3784 }
3785 if (pdiv != NULL)
3786 *pdiv = div;
3787 else
3788 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 if (pmod != NULL)
3791 *pmod = mod;
3792 else
3793 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003796}
3797
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003798static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003799long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003804
3805 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3806 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3807 }
3808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3810 div = NULL;
3811 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003812}
3813
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003814/* PyLong/PyLong -> float, with correctly rounded result. */
3815
3816#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3817#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3818
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003819static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003820long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 PyLongObject *a, *b, *x;
3823 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3824 digit mask, low;
3825 int inexact, negate, a_is_small, b_is_small;
3826 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 CHECK_BINOP(v, w);
3829 a = (PyLongObject *)v;
3830 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 /*
3833 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3836 1. choose a suitable integer 'shift'
3837 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3838 3. adjust x for correct rounding
3839 4. convert x to a double dx with the same value
3840 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3845 returns either 0.0 or -0.0, depending on the sign of b. For a and
3846 b both nonzero, ignore signs of a and b, and add the sign back in
3847 at the end. Now write a_bits and b_bits for the bit lengths of a
3848 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3849 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3854 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3855 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3856 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 1. The integer 'shift' is chosen so that x has the right number of
3861 bits for a double, plus two or three extra bits that will be used
3862 in the rounding decisions. Writing a_bits and b_bits for the
3863 number of significant bits in a and b respectively, a
3864 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 This is fine in the usual case, but if a/b is smaller than the
3869 smallest normal float then it can lead to double rounding on an
3870 IEEE 754 platform, giving incorrectly rounded results. So we
3871 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 2. The quantity x is computed by first shifting a (left -shift bits
3876 if shift <= 0, right shift bits if shift > 0) and then dividing by
3877 b. For both the shift and the division, we keep track of whether
3878 the result is inexact, in a flag 'inexact'; this information is
3879 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 With the choice of shift above, together with our assumption that
3882 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3883 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3886 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 For float representability, we need x/2**extra_bits <
3891 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3892 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 To round, we just modify the bottom digit of x in-place; this can
3897 end up giving a digit with value > PyLONG_MASK, but that's not a
3898 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 With the original choices for shift above, extra_bits will always
3901 be 2 or 3. Then rounding under the round-half-to-even rule, we
3902 round up iff the most significant of the extra bits is 1, and
3903 either: (a) the computation of x in step 2 had an inexact result,
3904 or (b) at least one other of the extra bits is 1, or (c) the least
3905 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 4. Conversion to a double is straightforward; all floating-point
3908 operations involved in the conversion are exact, so there's no
3909 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3912 The result will always be exactly representable as a double, except
3913 in the case that it overflows. To avoid dependence on the exact
3914 behaviour of ldexp on overflow, we check for overflow before
3915 applying ldexp. The result of ldexp is adjusted for sign before
3916 returning.
3917 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003920 a_size = Py_ABS(Py_SIZE(a));
3921 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3923 if (b_size == 0) {
3924 PyErr_SetString(PyExc_ZeroDivisionError,
3925 "division by zero");
3926 goto error;
3927 }
3928 if (a_size == 0)
3929 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 /* Fast path for a and b small (exactly representable in a double).
3932 Relies on floating-point division being correctly rounded; results
3933 may be subject to double rounding on x86 machines that operate with
3934 the x87 FPU set to 64-bit precision. */
3935 a_is_small = a_size <= MANT_DIG_DIGITS ||
3936 (a_size == MANT_DIG_DIGITS+1 &&
3937 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3938 b_is_small = b_size <= MANT_DIG_DIGITS ||
3939 (b_size == MANT_DIG_DIGITS+1 &&
3940 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3941 if (a_is_small && b_is_small) {
3942 double da, db;
3943 da = a->ob_digit[--a_size];
3944 while (a_size > 0)
3945 da = da * PyLong_BASE + a->ob_digit[--a_size];
3946 db = b->ob_digit[--b_size];
3947 while (b_size > 0)
3948 db = db * PyLong_BASE + b->ob_digit[--b_size];
3949 result = da / db;
3950 goto success;
3951 }
Tim Peterse2a60002001-09-04 06:17:36 +00003952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 /* Catch obvious cases of underflow and overflow */
3954 diff = a_size - b_size;
3955 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3956 /* Extreme overflow */
3957 goto overflow;
3958 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3959 /* Extreme underflow */
3960 goto underflow_or_zero;
3961 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01003962 diff = diff * PyLong_SHIFT + _Py_bit_length(a->ob_digit[a_size - 1]) -
3963 _Py_bit_length(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 /* Now diff = a_bits - b_bits. */
3965 if (diff > DBL_MAX_EXP)
3966 goto overflow;
3967 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3968 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003971 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 /* x = abs(a * 2**-shift) */
3976 if (shift <= 0) {
3977 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3978 digit rem;
3979 /* x = a << -shift */
3980 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3981 /* In practice, it's probably impossible to end up
3982 here. Both a and b would have to be enormous,
3983 using close to SIZE_T_MAX bytes of memory each. */
3984 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003985 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 goto error;
3987 }
3988 x = _PyLong_New(a_size + shift_digits + 1);
3989 if (x == NULL)
3990 goto error;
3991 for (i = 0; i < shift_digits; i++)
3992 x->ob_digit[i] = 0;
3993 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3994 a_size, -shift % PyLong_SHIFT);
3995 x->ob_digit[a_size + shift_digits] = rem;
3996 }
3997 else {
3998 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3999 digit rem;
4000 /* x = a >> shift */
4001 assert(a_size >= shift_digits);
4002 x = _PyLong_New(a_size - shift_digits);
4003 if (x == NULL)
4004 goto error;
4005 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4006 a_size - shift_digits, shift % PyLong_SHIFT);
4007 /* set inexact if any of the bits shifted out is nonzero */
4008 if (rem)
4009 inexact = 1;
4010 while (!inexact && shift_digits > 0)
4011 if (a->ob_digit[--shift_digits])
4012 inexact = 1;
4013 }
4014 long_normalize(x);
4015 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4018 reference to x, so it's safe to modify it in-place. */
4019 if (b_size == 1) {
4020 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4021 b->ob_digit[0]);
4022 long_normalize(x);
4023 if (rem)
4024 inexact = 1;
4025 }
4026 else {
4027 PyLongObject *div, *rem;
4028 div = x_divrem(x, b, &rem);
4029 Py_DECREF(x);
4030 x = div;
4031 if (x == NULL)
4032 goto error;
4033 if (Py_SIZE(rem))
4034 inexact = 1;
4035 Py_DECREF(rem);
4036 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004037 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004039 x_bits = (x_size-1)*PyLong_SHIFT+_Py_bit_length(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004042 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 /* Round by directly modifying the low digit of x. */
4046 mask = (digit)1 << (extra_bits - 1);
4047 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004048 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004050 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 /* Convert x to a double dx; the conversion is exact. */
4053 dx = x->ob_digit[--x_size];
4054 while (x_size > 0)
4055 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4056 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 /* Check whether ldexp result will overflow a double. */
4059 if (shift + x_bits >= DBL_MAX_EXP &&
4060 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4061 goto overflow;
4062 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004063
4064 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004066
4067 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004069
4070 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 PyErr_SetString(PyExc_OverflowError,
4072 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004073 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004075}
4076
4077static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004078long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 CHECK_BINOP(a, b);
4083
Yury Selivanove0b23092016-02-11 10:26:27 -05004084 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4085 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4086 }
4087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4089 mod = NULL;
4090 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004091}
4092
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004093static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004094long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 PyLongObject *div, *mod;
4097 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4102 return NULL;
4103 }
4104 z = PyTuple_New(2);
4105 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004106 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4107 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 }
4109 else {
4110 Py_DECREF(div);
4111 Py_DECREF(mod);
4112 }
4113 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004114}
4115
Mark Dickinsonc5299672019-06-02 10:24:06 +01004116
4117/* Compute an inverse to a modulo n, or raise ValueError if a is not
4118 invertible modulo n. Assumes n is positive. The inverse returned
4119 is whatever falls out of the extended Euclidean algorithm: it may
4120 be either positive or negative, but will be smaller than n in
4121 absolute value.
4122
4123 Pure Python equivalent for long_invmod:
4124
4125 def invmod(a, n):
4126 b, c = 1, 0
4127 while n:
4128 q, r = divmod(a, n)
4129 a, b, c, n = n, c, b - q*c, r
4130
4131 # at this point a is the gcd of the original inputs
4132 if a == 1:
4133 return b
4134 raise ValueError("Not invertible")
4135*/
4136
4137static PyLongObject *
4138long_invmod(PyLongObject *a, PyLongObject *n)
4139{
4140 PyLongObject *b, *c;
4141
4142 /* Should only ever be called for positive n */
4143 assert(Py_SIZE(n) > 0);
4144
4145 b = (PyLongObject *)PyLong_FromLong(1L);
4146 if (b == NULL) {
4147 return NULL;
4148 }
4149 c = (PyLongObject *)PyLong_FromLong(0L);
4150 if (c == NULL) {
4151 Py_DECREF(b);
4152 return NULL;
4153 }
4154 Py_INCREF(a);
4155 Py_INCREF(n);
4156
4157 /* references now owned: a, b, c, n */
4158 while (Py_SIZE(n) != 0) {
4159 PyLongObject *q, *r, *s, *t;
4160
4161 if (l_divmod(a, n, &q, &r) == -1) {
4162 goto Error;
4163 }
4164 Py_DECREF(a);
4165 a = n;
4166 n = r;
4167 t = (PyLongObject *)long_mul(q, c);
4168 Py_DECREF(q);
4169 if (t == NULL) {
4170 goto Error;
4171 }
4172 s = (PyLongObject *)long_sub(b, t);
4173 Py_DECREF(t);
4174 if (s == NULL) {
4175 goto Error;
4176 }
4177 Py_DECREF(b);
4178 b = c;
4179 c = s;
4180 }
4181 /* references now owned: a, b, c, n */
4182
4183 Py_DECREF(c);
4184 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004185 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004186 /* a != 1; we don't have an inverse. */
4187 Py_DECREF(a);
4188 Py_DECREF(b);
4189 PyErr_SetString(PyExc_ValueError,
4190 "base is not invertible for the given modulus");
4191 return NULL;
4192 }
4193 else {
4194 /* a == 1; b gives an inverse modulo n */
4195 Py_DECREF(a);
4196 return b;
4197 }
4198
4199 Error:
4200 Py_DECREF(a);
4201 Py_DECREF(b);
4202 Py_DECREF(c);
4203 Py_DECREF(n);
4204 return NULL;
4205}
4206
4207
Tim Peters47e52ee2004-08-30 02:44:38 +00004208/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004209static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004210long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4213 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 PyLongObject *z = NULL; /* accumulated result */
4216 Py_ssize_t i, j, k; /* counters */
4217 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 /* 5-ary values. If the exponent is large enough, table is
4220 * precomputed so that table[i] == a**i % c for i in range(32).
4221 */
4222 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4223 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 /* a, b, c = v, w, x */
4226 CHECK_BINOP(v, w);
4227 a = (PyLongObject*)v; Py_INCREF(a);
4228 b = (PyLongObject*)w; Py_INCREF(b);
4229 if (PyLong_Check(x)) {
4230 c = (PyLongObject *)x;
4231 Py_INCREF(x);
4232 }
4233 else if (x == Py_None)
4234 c = NULL;
4235 else {
4236 Py_DECREF(a);
4237 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004238 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 }
Tim Peters4c483c42001-09-05 06:24:58 +00004240
Mark Dickinsonc5299672019-06-02 10:24:06 +01004241 if (Py_SIZE(b) < 0 && c == NULL) {
4242 /* if exponent is negative and there's no modulus:
4243 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 that this calls float_pow() which converts its
4245 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004246 Py_DECREF(a);
4247 Py_DECREF(b);
4248 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 if (c) {
4252 /* if modulus == 0:
4253 raise ValueError() */
4254 if (Py_SIZE(c) == 0) {
4255 PyErr_SetString(PyExc_ValueError,
4256 "pow() 3rd argument cannot be 0");
4257 goto Error;
4258 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 /* if modulus < 0:
4261 negativeOutput = True
4262 modulus = -modulus */
4263 if (Py_SIZE(c) < 0) {
4264 negativeOutput = 1;
4265 temp = (PyLongObject *)_PyLong_Copy(c);
4266 if (temp == NULL)
4267 goto Error;
4268 Py_DECREF(c);
4269 c = temp;
4270 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004271 _PyLong_Negate(&c);
4272 if (c == NULL)
4273 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 /* if modulus == 1:
4277 return 0 */
4278 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4279 z = (PyLongObject *)PyLong_FromLong(0L);
4280 goto Done;
4281 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004282
Mark Dickinsonc5299672019-06-02 10:24:06 +01004283 /* if exponent is negative, negate the exponent and
4284 replace the base with a modular inverse */
4285 if (Py_SIZE(b) < 0) {
4286 temp = (PyLongObject *)_PyLong_Copy(b);
4287 if (temp == NULL)
4288 goto Error;
4289 Py_DECREF(b);
4290 b = temp;
4291 temp = NULL;
4292 _PyLong_Negate(&b);
4293 if (b == NULL)
4294 goto Error;
4295
4296 temp = long_invmod(a, c);
4297 if (temp == NULL)
4298 goto Error;
4299 Py_DECREF(a);
4300 a = temp;
4301 }
4302
Tim Peters81a93152013-10-05 16:53:52 -05004303 /* Reduce base by modulus in some cases:
4304 1. If base < 0. Forcing the base non-negative makes things easier.
4305 2. If base is obviously larger than the modulus. The "small
4306 exponent" case later can multiply directly by base repeatedly,
4307 while the "large exponent" case multiplies directly by base 31
4308 times. It can be unboundedly faster to multiply by
4309 base % modulus instead.
4310 We could _always_ do this reduction, but l_divmod() isn't cheap,
4311 so we only do it when it buys something. */
4312 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 if (l_divmod(a, c, NULL, &temp) < 0)
4314 goto Error;
4315 Py_DECREF(a);
4316 a = temp;
4317 temp = NULL;
4318 }
4319 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 /* At this point a, b, and c are guaranteed non-negative UNLESS
4322 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 z = (PyLongObject *)PyLong_FromLong(1L);
4325 if (z == NULL)
4326 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 /* Perform a modular reduction, X = X % c, but leave X alone if c
4329 * is NULL.
4330 */
4331#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004332 do { \
4333 if (c != NULL) { \
4334 if (l_divmod(X, c, NULL, &temp) < 0) \
4335 goto Error; \
4336 Py_XDECREF(X); \
4337 X = temp; \
4338 temp = NULL; \
4339 } \
4340 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 /* Multiply two values, then reduce the result:
4343 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004344#define MULT(X, Y, result) \
4345 do { \
4346 temp = (PyLongObject *)long_mul(X, Y); \
4347 if (temp == NULL) \
4348 goto Error; \
4349 Py_XDECREF(result); \
4350 result = temp; \
4351 temp = NULL; \
4352 REDUCE(result); \
4353 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4356 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4357 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4358 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4359 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004362 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004364 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 }
4366 }
4367 }
4368 else {
4369 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4370 Py_INCREF(z); /* still holds 1L */
4371 table[0] = z;
4372 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004373 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4376 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4379 const int index = (bi >> j) & 0x1f;
4380 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004381 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004383 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 }
4385 }
4386 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 if (negativeOutput && (Py_SIZE(z) != 0)) {
4389 temp = (PyLongObject *)long_sub(z, c);
4390 if (temp == NULL)
4391 goto Error;
4392 Py_DECREF(z);
4393 z = temp;
4394 temp = NULL;
4395 }
4396 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004397
Mark Dickinson22b20182010-05-10 21:27:53 +00004398 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004399 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004401 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4403 for (i = 0; i < 32; ++i)
4404 Py_XDECREF(table[i]);
4405 }
4406 Py_DECREF(a);
4407 Py_DECREF(b);
4408 Py_XDECREF(c);
4409 Py_XDECREF(temp);
4410 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004411}
4412
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004413static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004414long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 /* Implement ~x as -(x+1) */
4417 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004418 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004420 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 if (x == NULL)
4422 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004423 _PyLong_Negate(&x);
4424 /* No need for maybe_small_long here, since any small
4425 longs will have been caught in the Py_SIZE <= 1 fast path. */
4426 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004427}
4428
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004429static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004430long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004433 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 return PyLong_FromLong(-MEDIUM_VALUE(v));
4435 z = (PyLongObject *)_PyLong_Copy(v);
4436 if (z != NULL)
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004437 Py_SET_SIZE(z, -(Py_SIZE(v)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004439}
4440
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004441static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004442long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 if (Py_SIZE(v) < 0)
4445 return long_neg(v);
4446 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004447 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004448}
4449
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004450static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004451long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004454}
4455
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004456/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4457static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004458divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004459{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004460 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004461 assert(Py_SIZE(shiftby) >= 0);
4462 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4463 if (lshiftby >= 0) {
4464 *wordshift = lshiftby / PyLong_SHIFT;
4465 *remshift = lshiftby % PyLong_SHIFT;
4466 return 0;
4467 }
4468 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4469 be that PyLong_AsSsize_t raised an OverflowError. */
4470 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4471 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004472 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004473 if (wordshift_obj == NULL) {
4474 return -1;
4475 }
4476 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4477 Py_DECREF(wordshift_obj);
4478 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4479 return 0;
4480 }
4481 PyErr_Clear();
4482 /* Clip the value. With such large wordshift the right shift
4483 returns 0 and the left shift raises an error in _PyLong_New(). */
4484 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4485 *remshift = 0;
4486 return 0;
4487}
4488
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004489static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004490long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004493 Py_ssize_t newsize, hishift, i, j;
4494 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 if (Py_SIZE(a) < 0) {
4497 /* Right shifting negative numbers is harder */
4498 PyLongObject *a1, *a2;
4499 a1 = (PyLongObject *) long_invert(a);
4500 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004501 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004502 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 Py_DECREF(a1);
4504 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004505 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 z = (PyLongObject *) long_invert(a2);
4507 Py_DECREF(a2);
4508 }
4509 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004510 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 if (newsize <= 0)
4512 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004513 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 lomask = ((digit)1 << hishift) - 1;
4515 himask = PyLong_MASK ^ lomask;
4516 z = _PyLong_New(newsize);
4517 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004518 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004520 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004522 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004524 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004526 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004527}
4528
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004529static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004530long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004531{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004532 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004533 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004536
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004537 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004539 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004541 if (Py_SIZE(a) == 0) {
4542 return PyLong_FromLong(0);
4543 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004544 if (divmod_shift(b, &wordshift, &remshift) < 0)
4545 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004546 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4547}
4548
4549/* Return a >> shiftby. */
4550PyObject *
4551_PyLong_Rshift(PyObject *a, size_t shiftby)
4552{
4553 Py_ssize_t wordshift;
4554 digit remshift;
4555
4556 assert(PyLong_Check(a));
4557 if (Py_SIZE(a) == 0) {
4558 return PyLong_FromLong(0);
4559 }
4560 wordshift = shiftby / PyLong_SHIFT;
4561 remshift = shiftby % PyLong_SHIFT;
4562 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4563}
4564
4565static PyObject *
4566long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4567{
4568 /* This version due to Tim Peters */
4569 PyLongObject *z = NULL;
4570 Py_ssize_t oldsize, newsize, i, j;
4571 twodigits accum;
4572
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004573 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 newsize = oldsize + wordshift;
4575 if (remshift)
4576 ++newsize;
4577 z = _PyLong_New(newsize);
4578 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004579 return NULL;
4580 if (Py_SIZE(a) < 0) {
4581 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004582 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02004583 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 for (i = 0; i < wordshift; i++)
4585 z->ob_digit[i] = 0;
4586 accum = 0;
4587 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4588 accum |= (twodigits)a->ob_digit[j] << remshift;
4589 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4590 accum >>= PyLong_SHIFT;
4591 }
4592 if (remshift)
4593 z->ob_digit[newsize-1] = (digit)accum;
4594 else
4595 assert(!accum);
4596 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004598}
4599
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004600static PyObject *
4601long_lshift(PyObject *a, PyObject *b)
4602{
4603 Py_ssize_t wordshift;
4604 digit remshift;
4605
4606 CHECK_BINOP(a, b);
4607
4608 if (Py_SIZE(b) < 0) {
4609 PyErr_SetString(PyExc_ValueError, "negative shift count");
4610 return NULL;
4611 }
4612 if (Py_SIZE(a) == 0) {
4613 return PyLong_FromLong(0);
4614 }
4615 if (divmod_shift(b, &wordshift, &remshift) < 0)
4616 return NULL;
4617 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4618}
4619
4620/* Return a << shiftby. */
4621PyObject *
4622_PyLong_Lshift(PyObject *a, size_t shiftby)
4623{
4624 Py_ssize_t wordshift;
4625 digit remshift;
4626
4627 assert(PyLong_Check(a));
4628 if (Py_SIZE(a) == 0) {
4629 return PyLong_FromLong(0);
4630 }
4631 wordshift = shiftby / PyLong_SHIFT;
4632 remshift = shiftby % PyLong_SHIFT;
4633 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4634}
4635
Mark Dickinson27a87a22009-10-25 20:43:34 +00004636/* Compute two's complement of digit vector a[0:m], writing result to
4637 z[0:m]. The digit vector a need not be normalized, but should not
4638 be entirely zero. a and z may point to the same digit vector. */
4639
4640static void
4641v_complement(digit *z, digit *a, Py_ssize_t m)
4642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 Py_ssize_t i;
4644 digit carry = 1;
4645 for (i = 0; i < m; ++i) {
4646 carry += a[i] ^ PyLong_MASK;
4647 z[i] = carry & PyLong_MASK;
4648 carry >>= PyLong_SHIFT;
4649 }
4650 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004651}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004652
4653/* Bitwise and/xor/or operations */
4654
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004655static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004656long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004657 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004658 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 int nega, negb, negz;
4661 Py_ssize_t size_a, size_b, size_z, i;
4662 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 /* Bitwise operations for negative numbers operate as though
4665 on a two's complement representation. So convert arguments
4666 from sign-magnitude to two's complement, and convert the
4667 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004670 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 nega = Py_SIZE(a) < 0;
4672 if (nega) {
4673 z = _PyLong_New(size_a);
4674 if (z == NULL)
4675 return NULL;
4676 v_complement(z->ob_digit, a->ob_digit, size_a);
4677 a = z;
4678 }
4679 else
4680 /* Keep reference count consistent. */
4681 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004684 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 negb = Py_SIZE(b) < 0;
4686 if (negb) {
4687 z = _PyLong_New(size_b);
4688 if (z == NULL) {
4689 Py_DECREF(a);
4690 return NULL;
4691 }
4692 v_complement(z->ob_digit, b->ob_digit, size_b);
4693 b = z;
4694 }
4695 else
4696 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 /* Swap a and b if necessary to ensure size_a >= size_b. */
4699 if (size_a < size_b) {
4700 z = a; a = b; b = z;
4701 size_z = size_a; size_a = size_b; size_b = size_z;
4702 negz = nega; nega = negb; negb = negz;
4703 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 /* JRH: The original logic here was to allocate the result value (z)
4706 as the longer of the two operands. However, there are some cases
4707 where the result is guaranteed to be shorter than that: AND of two
4708 positives, OR of two negatives: use the shorter number. AND with
4709 mixed signs: use the positive number. OR with mixed signs: use the
4710 negative number.
4711 */
4712 switch (op) {
4713 case '^':
4714 negz = nega ^ negb;
4715 size_z = size_a;
4716 break;
4717 case '&':
4718 negz = nega & negb;
4719 size_z = negb ? size_a : size_b;
4720 break;
4721 case '|':
4722 negz = nega | negb;
4723 size_z = negb ? size_b : size_a;
4724 break;
4725 default:
stratakisa10d4262019-03-18 18:59:20 +01004726 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 /* We allow an extra digit if z is negative, to make sure that
4730 the final two's complement of z doesn't overflow. */
4731 z = _PyLong_New(size_z + negz);
4732 if (z == NULL) {
4733 Py_DECREF(a);
4734 Py_DECREF(b);
4735 return NULL;
4736 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 /* Compute digits for overlap of a and b. */
4739 switch(op) {
4740 case '&':
4741 for (i = 0; i < size_b; ++i)
4742 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4743 break;
4744 case '|':
4745 for (i = 0; i < size_b; ++i)
4746 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4747 break;
4748 case '^':
4749 for (i = 0; i < size_b; ++i)
4750 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4751 break;
4752 default:
stratakisa10d4262019-03-18 18:59:20 +01004753 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 /* Copy any remaining digits of a, inverting if necessary. */
4757 if (op == '^' && negb)
4758 for (; i < size_z; ++i)
4759 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4760 else if (i < size_z)
4761 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4762 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 /* Complement result if negative. */
4765 if (negz) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004766 Py_SET_SIZE(z, -(Py_SIZE(z)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 z->ob_digit[size_z] = PyLong_MASK;
4768 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4769 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771 Py_DECREF(a);
4772 Py_DECREF(b);
4773 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004774}
4775
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004776static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004777long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 PyObject *c;
4780 CHECK_BINOP(a, b);
4781 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4782 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004783}
4784
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004785static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004786long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 PyObject *c;
4789 CHECK_BINOP(a, b);
4790 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4791 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004792}
4793
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004794static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004795long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 PyObject *c;
4798 CHECK_BINOP(a, b);
4799 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4800 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004801}
4802
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004803static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004804long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 if (PyLong_CheckExact(v))
4807 Py_INCREF(v);
4808 else
4809 v = _PyLong_Copy((PyLongObject *)v);
4810 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004811}
4812
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004813PyObject *
4814_PyLong_GCD(PyObject *aarg, PyObject *barg)
4815{
4816 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4817 stwodigits x, y, q, s, t, c_carry, d_carry;
4818 stwodigits A, B, C, D, T;
4819 int nbits, k;
4820 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4821 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4822
4823 a = (PyLongObject *)aarg;
4824 b = (PyLongObject *)barg;
4825 size_a = Py_SIZE(a);
4826 size_b = Py_SIZE(b);
4827 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4828 Py_INCREF(a);
4829 Py_INCREF(b);
4830 goto simple;
4831 }
4832
4833 /* Initial reduction: make sure that 0 <= b <= a. */
4834 a = (PyLongObject *)long_abs(a);
4835 if (a == NULL)
4836 return NULL;
4837 b = (PyLongObject *)long_abs(b);
4838 if (b == NULL) {
4839 Py_DECREF(a);
4840 return NULL;
4841 }
4842 if (long_compare(a, b) < 0) {
4843 r = a;
4844 a = b;
4845 b = r;
4846 }
4847 /* We now own references to a and b */
4848
4849 alloc_a = Py_SIZE(a);
4850 alloc_b = Py_SIZE(b);
4851 /* reduce until a fits into 2 digits */
4852 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004853 nbits = _Py_bit_length(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004854 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4855 corresponding bits of b into y */
4856 size_b = Py_SIZE(b);
4857 assert(size_b <= size_a);
4858 if (size_b == 0) {
4859 if (size_a < alloc_a) {
4860 r = (PyLongObject *)_PyLong_Copy(a);
4861 Py_DECREF(a);
4862 }
4863 else
4864 r = a;
4865 Py_DECREF(b);
4866 Py_XDECREF(c);
4867 Py_XDECREF(d);
4868 return (PyObject *)r;
4869 }
4870 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4871 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4872 (a->ob_digit[size_a-3] >> nbits));
4873
4874 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4875 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4876 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4877
4878 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4879 larger than PyLong_MASK during the algorithm. */
4880 A = 1; B = 0; C = 0; D = 1;
4881 for (k=0;; k++) {
4882 if (y-C == 0)
4883 break;
4884 q = (x+(A-1))/(y-C);
4885 s = B+q*D;
4886 t = x-q*y;
4887 if (s > t)
4888 break;
4889 x = y; y = t;
4890 t = A+q*C; A = D; B = C; C = s; D = t;
4891 }
4892
4893 if (k == 0) {
4894 /* no progress; do a Euclidean step */
4895 if (l_divmod(a, b, NULL, &r) < 0)
4896 goto error;
4897 Py_DECREF(a);
4898 a = b;
4899 b = r;
4900 alloc_a = alloc_b;
4901 alloc_b = Py_SIZE(b);
4902 continue;
4903 }
4904
4905 /*
4906 a, b = A*b-B*a, D*a-C*b if k is odd
4907 a, b = A*a-B*b, D*b-C*a if k is even
4908 */
4909 if (k&1) {
4910 T = -A; A = -B; B = T;
4911 T = -C; C = -D; D = T;
4912 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004913 if (c != NULL) {
4914 Py_SET_SIZE(c, size_a);
4915 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004916 else if (Py_REFCNT(a) == 1) {
4917 Py_INCREF(a);
4918 c = a;
4919 }
4920 else {
4921 alloc_a = size_a;
4922 c = _PyLong_New(size_a);
4923 if (c == NULL)
4924 goto error;
4925 }
4926
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004927 if (d != NULL) {
4928 Py_SET_SIZE(d, size_a);
4929 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004930 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4931 Py_INCREF(b);
4932 d = b;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004933 Py_SET_SIZE(d, size_a);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004934 }
4935 else {
4936 alloc_b = size_a;
4937 d = _PyLong_New(size_a);
4938 if (d == NULL)
4939 goto error;
4940 }
4941 a_end = a->ob_digit + size_a;
4942 b_end = b->ob_digit + size_b;
4943
4944 /* compute new a and new b in parallel */
4945 a_digit = a->ob_digit;
4946 b_digit = b->ob_digit;
4947 c_digit = c->ob_digit;
4948 d_digit = d->ob_digit;
4949 c_carry = 0;
4950 d_carry = 0;
4951 while (b_digit < b_end) {
4952 c_carry += (A * *a_digit) - (B * *b_digit);
4953 d_carry += (D * *b_digit++) - (C * *a_digit++);
4954 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4955 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4956 c_carry >>= PyLong_SHIFT;
4957 d_carry >>= PyLong_SHIFT;
4958 }
4959 while (a_digit < a_end) {
4960 c_carry += A * *a_digit;
4961 d_carry -= C * *a_digit++;
4962 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4963 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4964 c_carry >>= PyLong_SHIFT;
4965 d_carry >>= PyLong_SHIFT;
4966 }
4967 assert(c_carry == 0);
4968 assert(d_carry == 0);
4969
4970 Py_INCREF(c);
4971 Py_INCREF(d);
4972 Py_DECREF(a);
4973 Py_DECREF(b);
4974 a = long_normalize(c);
4975 b = long_normalize(d);
4976 }
4977 Py_XDECREF(c);
4978 Py_XDECREF(d);
4979
4980simple:
4981 assert(Py_REFCNT(a) > 0);
4982 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004983/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4984 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4985#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004986 /* a fits into a long, so b must too */
4987 x = PyLong_AsLong((PyObject *)a);
4988 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004989#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004990 x = PyLong_AsLongLong((PyObject *)a);
4991 y = PyLong_AsLongLong((PyObject *)b);
4992#else
4993# error "_PyLong_GCD"
4994#endif
4995 x = Py_ABS(x);
4996 y = Py_ABS(y);
4997 Py_DECREF(a);
4998 Py_DECREF(b);
4999
5000 /* usual Euclidean algorithm for longs */
5001 while (y != 0) {
5002 t = y;
5003 y = x % y;
5004 x = t;
5005 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005006#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005007 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05005008#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005009 return PyLong_FromLongLong(x);
5010#else
5011# error "_PyLong_GCD"
5012#endif
5013
5014error:
5015 Py_DECREF(a);
5016 Py_DECREF(b);
5017 Py_XDECREF(c);
5018 Py_XDECREF(d);
5019 return NULL;
5020}
5021
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005022static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005023long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 double result;
5026 result = PyLong_AsDouble(v);
5027 if (result == -1.0 && PyErr_Occurred())
5028 return NULL;
5029 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005030}
5031
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005032static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005033long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5034
5035/*[clinic input]
5036@classmethod
5037int.__new__ as long_new
5038 x: object(c_default="NULL") = 0
5039 /
5040 base as obase: object(c_default="NULL") = 10
5041[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005042
Tim Peters6d6c1a32001-08-02 04:15:00 +00005043static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005044long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5045/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005046{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005047 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005049 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005050 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005051 if (x == NULL) {
5052 if (obase != NULL) {
5053 PyErr_SetString(PyExc_TypeError,
5054 "int() missing string argument");
5055 return NULL;
5056 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005058 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005059 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005061
Gregory P. Smitha689e522012-12-25 22:38:32 -08005062 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005063 if (base == -1 && PyErr_Occurred())
5064 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005065 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005066 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305067 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005068 return NULL;
5069 }
5070
5071 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005072 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03005074 const char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 if (PyByteArray_Check(x))
5076 string = PyByteArray_AS_STRING(x);
5077 else
5078 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005079 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 }
5081 else {
5082 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005083 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 return NULL;
5085 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005086}
5087
Serhiy Storchaka95949422013-08-27 19:40:23 +03005088/* Wimpy, slow approach to tp_new calls for subtypes of int:
5089 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005090 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005091 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005092*/
5093static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005094long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 PyLongObject *tmp, *newobj;
5097 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005100 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 if (tmp == NULL)
5102 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005103 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 n = Py_SIZE(tmp);
5105 if (n < 0)
5106 n = -n;
5107 newobj = (PyLongObject *)type->tp_alloc(type, n);
5108 if (newobj == NULL) {
5109 Py_DECREF(tmp);
5110 return NULL;
5111 }
5112 assert(PyLong_Check(newobj));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005113 Py_SET_SIZE(newobj, Py_SIZE(tmp));
5114 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 newobj->ob_digit[i] = tmp->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 Py_DECREF(tmp);
5118 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005119}
5120
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005121/*[clinic input]
5122int.__getnewargs__
5123[clinic start generated code]*/
5124
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005125static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005126int___getnewargs___impl(PyObject *self)
5127/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005128{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005129 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005130}
5131
Guido van Rossumb43daf72007-08-01 18:08:08 +00005132static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005133long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005136}
5137
5138static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005139long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005141 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005142}
5143
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005144/*[clinic input]
5145int.__format__
5146
5147 format_spec: unicode
5148 /
5149[clinic start generated code]*/
5150
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005151static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005152int___format___impl(PyObject *self, PyObject *format_spec)
5153/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005154{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005155 _PyUnicodeWriter writer;
5156 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005157
Victor Stinner8f674cc2013-04-17 23:02:17 +02005158 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005159 ret = _PyLong_FormatAdvancedWriter(
5160 &writer,
5161 self,
5162 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5163 if (ret == -1) {
5164 _PyUnicodeWriter_Dealloc(&writer);
5165 return NULL;
5166 }
5167 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005168}
5169
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005170/* Return a pair (q, r) such that a = b * q + r, and
5171 abs(r) <= abs(b)/2, with equality possible only if q is even.
5172 In other words, q == a / b, rounded to the nearest integer using
5173 round-half-to-even. */
5174
5175PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005176_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005177{
5178 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005179 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005180 int quo_is_odd, quo_is_neg;
5181 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005182
5183 /* Equivalent Python code:
5184
5185 def divmod_near(a, b):
5186 q, r = divmod(a, b)
5187 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5188 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5189 # positive, 2 * r < b if b negative.
5190 greater_than_half = 2*r > b if b > 0 else 2*r < b
5191 exactly_half = 2*r == b
5192 if greater_than_half or exactly_half and q % 2 == 1:
5193 q += 1
5194 r -= b
5195 return q, r
5196
5197 */
5198 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5199 PyErr_SetString(PyExc_TypeError,
5200 "non-integer arguments in division");
5201 return NULL;
5202 }
5203
5204 /* Do a and b have different signs? If so, quotient is negative. */
5205 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5206
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005207 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5208 goto error;
5209
5210 /* compare twice the remainder with the divisor, to see
5211 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005212 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005213 if (twice_rem == NULL)
5214 goto error;
5215 if (quo_is_neg) {
5216 temp = long_neg((PyLongObject*)twice_rem);
5217 Py_DECREF(twice_rem);
5218 twice_rem = temp;
5219 if (twice_rem == NULL)
5220 goto error;
5221 }
5222 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5223 Py_DECREF(twice_rem);
5224
5225 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5226 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5227 /* fix up quotient */
5228 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005229 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005230 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005231 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005232 Py_DECREF(quo);
5233 quo = (PyLongObject *)temp;
5234 if (quo == NULL)
5235 goto error;
5236 /* and remainder */
5237 if (quo_is_neg)
5238 temp = long_add(rem, (PyLongObject *)b);
5239 else
5240 temp = long_sub(rem, (PyLongObject *)b);
5241 Py_DECREF(rem);
5242 rem = (PyLongObject *)temp;
5243 if (rem == NULL)
5244 goto error;
5245 }
5246
5247 result = PyTuple_New(2);
5248 if (result == NULL)
5249 goto error;
5250
5251 /* PyTuple_SET_ITEM steals references */
5252 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5253 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005254 return result;
5255
5256 error:
5257 Py_XDECREF(quo);
5258 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005259 return NULL;
5260}
5261
Eric Smith8c663262007-08-25 02:26:07 +00005262static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005263long_round(PyObject *self, PyObject *args)
5264{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005265 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005266
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005267 /* To round an integer m to the nearest 10**n (n positive), we make use of
5268 * the divmod_near operation, defined by:
5269 *
5270 * divmod_near(a, b) = (q, r)
5271 *
5272 * where q is the nearest integer to the quotient a / b (the
5273 * nearest even integer in the case of a tie) and r == a - q * b.
5274 * Hence q * b = a - r is the nearest multiple of b to a,
5275 * preferring even multiples in the case of a tie.
5276 *
5277 * So the nearest multiple of 10**n to m is:
5278 *
5279 * m - divmod_near(m, 10**n)[1].
5280 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5282 return NULL;
5283 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005284 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005285
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005286 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 if (ndigits == NULL)
5288 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005289
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005290 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 if (Py_SIZE(ndigits) >= 0) {
5292 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005293 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005295
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005296 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5297 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005299 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005301 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005302
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005303 result = PyLong_FromLong(10L);
5304 if (result == NULL) {
5305 Py_DECREF(ndigits);
5306 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005308
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005309 temp = long_pow(result, ndigits, Py_None);
5310 Py_DECREF(ndigits);
5311 Py_DECREF(result);
5312 result = temp;
5313 if (result == NULL)
5314 return NULL;
5315
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005316 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005317 Py_DECREF(result);
5318 result = temp;
5319 if (result == NULL)
5320 return NULL;
5321
5322 temp = long_sub((PyLongObject *)self,
5323 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5324 Py_DECREF(result);
5325 result = temp;
5326
5327 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005328}
5329
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005330/*[clinic input]
5331int.__sizeof__ -> Py_ssize_t
5332
5333Returns size in memory, in bytes.
5334[clinic start generated code]*/
5335
5336static Py_ssize_t
5337int___sizeof___impl(PyObject *self)
5338/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005341
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005342 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5343 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005344}
5345
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005346/*[clinic input]
5347int.bit_length
5348
5349Number of bits necessary to represent self in binary.
5350
5351>>> bin(37)
5352'0b100101'
5353>>> (37).bit_length()
53546
5355[clinic start generated code]*/
5356
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005357static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005358int_bit_length_impl(PyObject *self)
5359/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005362 Py_ssize_t ndigits;
5363 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005365
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005366 assert(self != NULL);
5367 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005368
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005369 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 if (ndigits == 0)
5371 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005372
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005373 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekasc5b79002020-01-16 15:09:19 +01005374 msd_bits = _Py_bit_length(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5377 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 /* expression above may overflow; use Python integers instead */
5380 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5381 if (result == NULL)
5382 return NULL;
5383 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5384 if (x == NULL)
5385 goto error;
5386 y = (PyLongObject *)long_mul(result, x);
5387 Py_DECREF(x);
5388 if (y == NULL)
5389 goto error;
5390 Py_DECREF(result);
5391 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5394 if (x == NULL)
5395 goto error;
5396 y = (PyLongObject *)long_add(result, x);
5397 Py_DECREF(x);
5398 if (y == NULL)
5399 goto error;
5400 Py_DECREF(result);
5401 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005404
Mark Dickinson22b20182010-05-10 21:27:53 +00005405 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 Py_DECREF(result);
5407 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005408}
5409
Christian Heimes53876d92008-04-19 00:31:39 +00005410
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005411/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005412int.as_integer_ratio
5413
5414Return integer ratio.
5415
5416Return a pair of integers, whose ratio is exactly equal to the original int
5417and with a positive denominator.
5418
5419>>> (10).as_integer_ratio()
5420(10, 1)
5421>>> (-10).as_integer_ratio()
5422(-10, 1)
5423>>> (0).as_integer_ratio()
5424(0, 1)
5425[clinic start generated code]*/
5426
5427static PyObject *
5428int_as_integer_ratio_impl(PyObject *self)
5429/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5430{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005431 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005432 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005433 if (numerator == NULL) {
5434 return NULL;
5435 }
5436 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5437 Py_DECREF(numerator);
5438 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005439}
5440
5441/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005442int.to_bytes
5443
5444 length: Py_ssize_t
5445 Length of bytes object to use. An OverflowError is raised if the
5446 integer is not representable with the given number of bytes.
5447 byteorder: unicode
5448 The byte order used to represent the integer. If byteorder is 'big',
5449 the most significant byte is at the beginning of the byte array. If
5450 byteorder is 'little', the most significant byte is at the end of the
5451 byte array. To request the native byte order of the host system, use
5452 `sys.byteorder' as the byte order value.
5453 *
5454 signed as is_signed: bool = False
5455 Determines whether two's complement is used to represent the integer.
5456 If signed is False and a negative integer is given, an OverflowError
5457 is raised.
5458
5459Return an array of bytes representing an integer.
5460[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005461
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005462static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005463int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5464 int is_signed)
5465/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005469
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005470 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005472 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 little_endian = 0;
5474 else {
5475 PyErr_SetString(PyExc_ValueError,
5476 "byteorder must be either 'little' or 'big'");
5477 return NULL;
5478 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 if (length < 0) {
5481 PyErr_SetString(PyExc_ValueError,
5482 "length argument must be non-negative");
5483 return NULL;
5484 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005486 bytes = PyBytes_FromStringAndSize(NULL, length);
5487 if (bytes == NULL)
5488 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005489
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005490 if (_PyLong_AsByteArray((PyLongObject *)self,
5491 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 length, little_endian, is_signed) < 0) {
5493 Py_DECREF(bytes);
5494 return NULL;
5495 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005497 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005498}
5499
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005500/*[clinic input]
5501@classmethod
5502int.from_bytes
5503
5504 bytes as bytes_obj: object
5505 Holds the array of bytes to convert. The argument must either
5506 support the buffer protocol or be an iterable object producing bytes.
5507 Bytes and bytearray are examples of built-in objects that support the
5508 buffer protocol.
5509 byteorder: unicode
5510 The byte order used to represent the integer. If byteorder is 'big',
5511 the most significant byte is at the beginning of the byte array. If
5512 byteorder is 'little', the most significant byte is at the end of the
5513 byte array. To request the native byte order of the host system, use
5514 `sys.byteorder' as the byte order value.
5515 *
5516 signed as is_signed: bool = False
5517 Indicates whether two's complement is used to represent the integer.
5518
5519Return the integer represented by the given array of bytes.
5520[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005521
5522static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005523int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5524 PyObject *byteorder, int is_signed)
5525/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005528 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005529
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005530 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005532 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 little_endian = 0;
5534 else {
5535 PyErr_SetString(PyExc_ValueError,
5536 "byteorder must be either 'little' or 'big'");
5537 return NULL;
5538 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005539
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005540 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 if (bytes == NULL)
5542 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 long_obj = _PyLong_FromByteArray(
5545 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5546 little_endian, is_signed);
5547 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005548
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005549 if (long_obj != NULL && type != &PyLong_Type) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005550 Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005553 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005554}
5555
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005556static PyObject *
5557long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5558{
5559 return long_long(self);
5560}
5561
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005562static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005563 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005565 INT_BIT_LENGTH_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005566 INT_TO_BYTES_METHODDEF
5567 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005568 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005569 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005571 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005573 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 "Ceiling of an Integral returns itself."},
5575 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5576 "Rounding an Integral returns itself.\n"
5577 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005578 INT___GETNEWARGS___METHODDEF
5579 INT___FORMAT___METHODDEF
5580 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005581 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005582};
5583
Guido van Rossumb43daf72007-08-01 18:08:08 +00005584static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005585 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005586 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005587 "the real part of a complex number",
5588 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005589 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005590 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005591 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005592 NULL},
5593 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005594 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005595 "the numerator of a rational number in lowest terms",
5596 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005597 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005598 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005599 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005600 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005601 {NULL} /* Sentinel */
5602};
5603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005604PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005605"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005606int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005607\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005608Convert a number or string to an integer, or return 0 if no arguments\n\
5609are given. If x is a number, return x.__int__(). For floating point\n\
5610numbers, this truncates towards zero.\n\
5611\n\
5612If x is not a number or if base is given, then x must be a string,\n\
5613bytes, or bytearray instance representing an integer literal in the\n\
5614given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5615by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5616Base 0 means to interpret the base from the string as an integer literal.\n\
5617>>> int('0b100', base=0)\n\
56184");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005619
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005620static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005621 (binaryfunc)long_add, /*nb_add*/
5622 (binaryfunc)long_sub, /*nb_subtract*/
5623 (binaryfunc)long_mul, /*nb_multiply*/
5624 long_mod, /*nb_remainder*/
5625 long_divmod, /*nb_divmod*/
5626 long_pow, /*nb_power*/
5627 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005628 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005629 (unaryfunc)long_abs, /*tp_absolute*/
5630 (inquiry)long_bool, /*tp_bool*/
5631 (unaryfunc)long_invert, /*nb_invert*/
5632 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005633 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005634 long_and, /*nb_and*/
5635 long_xor, /*nb_xor*/
5636 long_or, /*nb_or*/
5637 long_long, /*nb_int*/
5638 0, /*nb_reserved*/
5639 long_float, /*nb_float*/
5640 0, /* nb_inplace_add */
5641 0, /* nb_inplace_subtract */
5642 0, /* nb_inplace_multiply */
5643 0, /* nb_inplace_remainder */
5644 0, /* nb_inplace_power */
5645 0, /* nb_inplace_lshift */
5646 0, /* nb_inplace_rshift */
5647 0, /* nb_inplace_and */
5648 0, /* nb_inplace_xor */
5649 0, /* nb_inplace_or */
5650 long_div, /* nb_floor_divide */
5651 long_true_divide, /* nb_true_divide */
5652 0, /* nb_inplace_floor_divide */
5653 0, /* nb_inplace_true_divide */
5654 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005655};
5656
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005657PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5659 "int", /* tp_name */
5660 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5661 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005662 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005663 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 0, /* tp_getattr */
5665 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005666 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 long_to_decimal_string, /* tp_repr */
5668 &long_as_number, /* tp_as_number */
5669 0, /* tp_as_sequence */
5670 0, /* tp_as_mapping */
5671 (hashfunc)long_hash, /* tp_hash */
5672 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005673 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 PyObject_GenericGetAttr, /* tp_getattro */
5675 0, /* tp_setattro */
5676 0, /* tp_as_buffer */
5677 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5678 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5679 long_doc, /* tp_doc */
5680 0, /* tp_traverse */
5681 0, /* tp_clear */
5682 long_richcompare, /* tp_richcompare */
5683 0, /* tp_weaklistoffset */
5684 0, /* tp_iter */
5685 0, /* tp_iternext */
5686 long_methods, /* tp_methods */
5687 0, /* tp_members */
5688 long_getset, /* tp_getset */
5689 0, /* tp_base */
5690 0, /* tp_dict */
5691 0, /* tp_descr_get */
5692 0, /* tp_descr_set */
5693 0, /* tp_dictoffset */
5694 0, /* tp_init */
5695 0, /* tp_alloc */
5696 long_new, /* tp_new */
5697 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005698};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005699
Mark Dickinsonbd792642009-03-18 20:06:12 +00005700static PyTypeObject Int_InfoType;
5701
5702PyDoc_STRVAR(int_info__doc__,
5703"sys.int_info\n\
5704\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005705A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005706internal representation of integers. The attributes are read only.");
5707
5708static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005710 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005712};
5713
5714static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 "sys.int_info", /* name */
5716 int_info__doc__, /* doc */
5717 int_info_fields, /* fields */
5718 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005719};
5720
5721PyObject *
5722PyLong_GetInfo(void)
5723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 PyObject* int_info;
5725 int field = 0;
5726 int_info = PyStructSequence_New(&Int_InfoType);
5727 if (int_info == NULL)
5728 return NULL;
5729 PyStructSequence_SET_ITEM(int_info, field++,
5730 PyLong_FromLong(PyLong_SHIFT));
5731 PyStructSequence_SET_ITEM(int_info, field++,
5732 PyLong_FromLong(sizeof(digit)));
5733 if (PyErr_Occurred()) {
5734 Py_CLEAR(int_info);
5735 return NULL;
5736 }
5737 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005738}
5739
Guido van Rossumddefaf32007-01-14 03:31:43 +00005740int
Victor Stinner630c8df2019-12-17 13:02:18 +01005741_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005742{
5743#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005744 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5745 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5746 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005747
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005748 PyLongObject *v = _PyLong_New(1);
5749 if (!v) {
5750 return -1;
5751 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005752
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005753 Py_SET_SIZE(v, size);
Victor Stinner12174a52014-08-15 23:17:38 +02005754 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005755
Victor Stinner630c8df2019-12-17 13:02:18 +01005756 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005757 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005758#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005759
Victor Stinner630c8df2019-12-17 13:02:18 +01005760 if (_Py_IsMainInterpreter(tstate)) {
5761 _PyLong_Zero = PyLong_FromLong(0);
5762 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005763 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005764 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005765
5766 _PyLong_One = PyLong_FromLong(1);
5767 if (_PyLong_One == NULL) {
5768 return 0;
5769 }
5770
5771 /* initialize int_info */
5772 if (Int_InfoType.tp_name == NULL) {
5773 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5774 return 0;
5775 }
5776 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005777 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005780}
5781
5782void
Victor Stinner630c8df2019-12-17 13:02:18 +01005783_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005784{
Victor Stinner630c8df2019-12-17 13:02:18 +01005785 if (_Py_IsMainInterpreter(tstate)) {
5786 Py_CLEAR(_PyLong_One);
5787 Py_CLEAR(_PyLong_Zero);
5788 }
5789
Guido van Rossumddefaf32007-01-14 03:31:43 +00005790#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005791 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005792 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005794#endif
5795}