blob: a0bb6bc52be02b68e9d4b9022b96a757c3a37ede [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. */
2855 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2856 double dx;
2857 /* Correction term for round-half-to-even rounding. For a digit x,
2858 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2859 multiple of 4, rounding ties to a multiple of 8. */
2860 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002861
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002862 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 if (a_size == 0) {
2864 /* Special case for 0: significand 0.0, exponent 0. */
2865 *e = 0;
2866 return 0.0;
2867 }
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002868 a_bits = _Py_bit_length(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 /* The following is an overflow-free version of the check
2870 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2871 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2872 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2873 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002874 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2878 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 Number of digits needed for result: write // for floor division.
2881 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2890 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2893 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2894 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 in both cases.
2901 */
2902 if (a_bits <= DBL_MANT_DIG + 2) {
2903 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2904 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2905 x_size = 0;
2906 while (x_size < shift_digits)
2907 x_digits[x_size++] = 0;
2908 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2909 (int)shift_bits);
2910 x_size += a_size;
2911 x_digits[x_size++] = rem;
2912 }
2913 else {
2914 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2915 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2916 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2917 a_size - shift_digits, (int)shift_bits);
2918 x_size = a_size - shift_digits;
2919 /* For correct rounding below, we need the least significant
2920 bit of x to be 'sticky' for this shift: if any of the bits
2921 shifted out was nonzero, we set the least significant bit
2922 of x. */
2923 if (rem)
2924 x_digits[0] |= 1;
2925 else
2926 while (shift_digits > 0)
2927 if (a->ob_digit[--shift_digits]) {
2928 x_digits[0] |= 1;
2929 break;
2930 }
2931 }
Victor Stinner63941882011-09-29 00:42:28 +02002932 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 /* Round, and convert to double. */
2935 x_digits[0] += half_even_correction[x_digits[0] & 7];
2936 dx = x_digits[--x_size];
2937 while (x_size > 0)
2938 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 /* Rescale; make correction if result is 1.0. */
2941 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2942 if (dx == 1.0) {
2943 if (a_bits == PY_SSIZE_T_MAX)
2944 goto overflow;
2945 dx = 0.5;
2946 a_bits += 1;
2947 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 *e = a_bits;
2950 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002951
2952 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 /* exponent > PY_SSIZE_T_MAX */
2954 PyErr_SetString(PyExc_OverflowError,
2955 "huge integer: number of bits overflows a Py_ssize_t");
2956 *e = 0;
2957 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002958}
2959
Serhiy Storchaka95949422013-08-27 19:40:23 +03002960/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002961 using the round-half-to-even rule in the case of a tie. */
2962
2963double
2964PyLong_AsDouble(PyObject *v)
2965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 Py_ssize_t exponent;
2967 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002968
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002969 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 PyErr_BadInternalCall();
2971 return -1.0;
2972 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002973 if (!PyLong_Check(v)) {
2974 PyErr_SetString(PyExc_TypeError, "an integer is required");
2975 return -1.0;
2976 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002977 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002978 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002979 to double. This improves performance of FP/long operations
2980 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002981 */
2982 return (double)MEDIUM_VALUE((PyLongObject *)v);
2983 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2985 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2986 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002987 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 return -1.0;
2989 }
2990 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002991}
2992
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002993/* Methods */
2994
HongWeipeng42acb7b2019-09-18 23:10:15 +08002995/* if a < b, return a negative number
2996 if a == b, return 0
2997 if a > b, return a positive number */
2998
2999static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003000long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003001{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003002 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
3003 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003004 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08003005 sdigit diff = 0;
3006 while (--i >= 0) {
3007 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
3008 if (diff) {
3009 break;
3010 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003012 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003014 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003015}
3016
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003017static PyObject *
3018long_richcompare(PyObject *self, PyObject *other, int op)
3019{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003020 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 CHECK_BINOP(self, other);
3022 if (self == other)
3023 result = 0;
3024 else
3025 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003026 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003027}
3028
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003029static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003030long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003031{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003032 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 Py_ssize_t i;
3034 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 i = Py_SIZE(v);
3037 switch(i) {
3038 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3039 case 0: return 0;
3040 case 1: return v->ob_digit[0];
3041 }
3042 sign = 1;
3043 x = 0;
3044 if (i < 0) {
3045 sign = -1;
3046 i = -(i);
3047 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003049 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3050 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3051 _PyHASH_MODULUS.
3052
3053 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3054 amounts to a rotation of the bits of x. To see this, write
3055
3056 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3057
3058 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3059 PyLong_SHIFT bits of x (those that are shifted out of the
3060 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3061 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3062 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3063 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3064 congruent to y modulo _PyHASH_MODULUS. So
3065
3066 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3067
3068 The right-hand side is just the result of rotating the
3069 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3070 not all _PyHASH_BITS bits of x are 1s, the same is true
3071 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3072 the reduction of x*2**PyLong_SHIFT modulo
3073 _PyHASH_MODULUS. */
3074 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3075 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003077 if (x >= _PyHASH_MODULUS)
3078 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 }
3080 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003081 if (x == (Py_uhash_t)-1)
3082 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003083 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003084}
3085
3086
Serhiy Storchaka95949422013-08-27 19:40:23 +03003087/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003088
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003089static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003090x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003091{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003092 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 PyLongObject *z;
3094 Py_ssize_t i;
3095 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 /* Ensure a is the larger of the two: */
3098 if (size_a < size_b) {
3099 { PyLongObject *temp = a; a = b; b = temp; }
3100 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003101 size_a = size_b;
3102 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 }
3104 z = _PyLong_New(size_a+1);
3105 if (z == NULL)
3106 return NULL;
3107 for (i = 0; i < size_b; ++i) {
3108 carry += a->ob_digit[i] + b->ob_digit[i];
3109 z->ob_digit[i] = carry & PyLong_MASK;
3110 carry >>= PyLong_SHIFT;
3111 }
3112 for (; i < size_a; ++i) {
3113 carry += a->ob_digit[i];
3114 z->ob_digit[i] = carry & PyLong_MASK;
3115 carry >>= PyLong_SHIFT;
3116 }
3117 z->ob_digit[i] = carry;
3118 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003119}
3120
3121/* Subtract the absolute values of two integers. */
3122
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003123static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003124x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003125{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003126 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 PyLongObject *z;
3128 Py_ssize_t i;
3129 int sign = 1;
3130 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 /* Ensure a is the larger of the two: */
3133 if (size_a < size_b) {
3134 sign = -1;
3135 { PyLongObject *temp = a; a = b; b = temp; }
3136 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003137 size_a = size_b;
3138 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 }
3140 else if (size_a == size_b) {
3141 /* Find highest digit where a and b differ: */
3142 i = size_a;
3143 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3144 ;
3145 if (i < 0)
3146 return (PyLongObject *)PyLong_FromLong(0);
3147 if (a->ob_digit[i] < b->ob_digit[i]) {
3148 sign = -1;
3149 { PyLongObject *temp = a; a = b; b = temp; }
3150 }
3151 size_a = size_b = i+1;
3152 }
3153 z = _PyLong_New(size_a);
3154 if (z == NULL)
3155 return NULL;
3156 for (i = 0; i < size_b; ++i) {
3157 /* The following assumes unsigned arithmetic
3158 works module 2**N for some N>PyLong_SHIFT. */
3159 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3160 z->ob_digit[i] = borrow & PyLong_MASK;
3161 borrow >>= PyLong_SHIFT;
3162 borrow &= 1; /* Keep only one sign bit */
3163 }
3164 for (; i < size_a; ++i) {
3165 borrow = a->ob_digit[i] - borrow;
3166 z->ob_digit[i] = borrow & PyLong_MASK;
3167 borrow >>= PyLong_SHIFT;
3168 borrow &= 1; /* Keep only one sign bit */
3169 }
3170 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003171 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003172 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02003173 }
HongWeipeng036fe852019-11-26 15:54:49 +08003174 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003175}
3176
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003177static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003178long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003183
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003184 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003185 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 }
3187 if (Py_SIZE(a) < 0) {
3188 if (Py_SIZE(b) < 0) {
3189 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003190 if (z != NULL) {
3191 /* x_add received at least one multiple-digit int,
3192 and thus z must be a multiple-digit int.
3193 That also means z is not an element of
3194 small_ints, so negating it in-place is safe. */
3195 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003196 Py_SET_SIZE(z, -(Py_SIZE(z)));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 }
3199 else
3200 z = x_sub(b, a);
3201 }
3202 else {
3203 if (Py_SIZE(b) < 0)
3204 z = x_sub(a, b);
3205 else
3206 z = x_add(a, b);
3207 }
3208 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003209}
3210
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003211static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003212long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003217
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003218 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003219 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 }
3221 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003222 if (Py_SIZE(b) < 0) {
3223 z = x_sub(b, a);
3224 }
3225 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003227 if (z != NULL) {
3228 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003229 Py_SET_SIZE(z, -(Py_SIZE(z)));
HongWeipeng036fe852019-11-26 15:54:49 +08003230 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003231 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 }
3233 else {
3234 if (Py_SIZE(b) < 0)
3235 z = x_add(a, b);
3236 else
3237 z = x_sub(a, b);
3238 }
3239 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003240}
3241
Tim Peters5af4e6c2002-08-12 02:31:19 +00003242/* Grade school multiplication, ignoring the signs.
3243 * Returns the absolute value of the product, or NULL if error.
3244 */
3245static PyLongObject *
3246x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003249 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3250 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 z = _PyLong_New(size_a + size_b);
3254 if (z == NULL)
3255 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3258 if (a == b) {
3259 /* Efficient squaring per HAC, Algorithm 14.16:
3260 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3261 * Gives slightly less than a 2x speedup when a == b,
3262 * via exploiting that each entry in the multiplication
3263 * pyramid appears twice (except for the size_a squares).
3264 */
3265 for (i = 0; i < size_a; ++i) {
3266 twodigits carry;
3267 twodigits f = a->ob_digit[i];
3268 digit *pz = z->ob_digit + (i << 1);
3269 digit *pa = a->ob_digit + i + 1;
3270 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003273 Py_DECREF(z);
3274 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003275 });
Tim Peters0973b992004-08-29 22:16:50 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 carry = *pz + f * f;
3278 *pz++ = (digit)(carry & PyLong_MASK);
3279 carry >>= PyLong_SHIFT;
3280 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 /* Now f is added in twice in each column of the
3283 * pyramid it appears. Same as adding f<<1 once.
3284 */
3285 f <<= 1;
3286 while (pa < paend) {
3287 carry += *pz + *pa++ * f;
3288 *pz++ = (digit)(carry & PyLong_MASK);
3289 carry >>= PyLong_SHIFT;
3290 assert(carry <= (PyLong_MASK << 1));
3291 }
3292 if (carry) {
3293 carry += *pz;
3294 *pz++ = (digit)(carry & PyLong_MASK);
3295 carry >>= PyLong_SHIFT;
3296 }
3297 if (carry)
3298 *pz += (digit)(carry & PyLong_MASK);
3299 assert((carry >> PyLong_SHIFT) == 0);
3300 }
3301 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003302 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 for (i = 0; i < size_a; ++i) {
3304 twodigits carry = 0;
3305 twodigits f = a->ob_digit[i];
3306 digit *pz = z->ob_digit + i;
3307 digit *pb = b->ob_digit;
3308 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003311 Py_DECREF(z);
3312 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003313 });
Tim Peters0973b992004-08-29 22:16:50 +00003314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 while (pb < pbend) {
3316 carry += *pz + *pb++ * f;
3317 *pz++ = (digit)(carry & PyLong_MASK);
3318 carry >>= PyLong_SHIFT;
3319 assert(carry <= PyLong_MASK);
3320 }
3321 if (carry)
3322 *pz += (digit)(carry & PyLong_MASK);
3323 assert((carry >> PyLong_SHIFT) == 0);
3324 }
3325 }
3326 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003327}
3328
3329/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003330 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003331 split, and sets low and high such that abs(n) == (high << size) + low,
3332 viewing the shift as being by digits. The sign bit is ignored, and
3333 the return values are >= 0.
3334 Returns 0 on success, -1 on failure.
3335*/
3336static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003337kmul_split(PyLongObject *n,
3338 Py_ssize_t size,
3339 PyLongObject **high,
3340 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 PyLongObject *hi, *lo;
3343 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003344 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003345
Victor Stinner640c35c2013-06-04 23:14:37 +02003346 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 if ((hi = _PyLong_New(size_hi)) == NULL)
3350 return -1;
3351 if ((lo = _PyLong_New(size_lo)) == NULL) {
3352 Py_DECREF(hi);
3353 return -1;
3354 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3357 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 *high = long_normalize(hi);
3360 *low = long_normalize(lo);
3361 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003362}
3363
Tim Peters60004642002-08-12 22:01:34 +00003364static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3365
Tim Peters5af4e6c2002-08-12 02:31:19 +00003366/* Karatsuba multiplication. Ignores the input signs, and returns the
3367 * absolute value of the product (or NULL if error).
3368 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3369 */
3370static PyLongObject *
3371k_mul(PyLongObject *a, PyLongObject *b)
3372{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003373 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3374 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 PyLongObject *ah = NULL;
3376 PyLongObject *al = NULL;
3377 PyLongObject *bh = NULL;
3378 PyLongObject *bl = NULL;
3379 PyLongObject *ret = NULL;
3380 PyLongObject *t1, *t2, *t3;
3381 Py_ssize_t shift; /* the number of digits we split off */
3382 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3385 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3386 * Then the original product is
3387 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3388 * By picking X to be a power of 2, "*X" is just shifting, and it's
3389 * been reduced to 3 multiplies on numbers half the size.
3390 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 /* We want to split based on the larger number; fiddle so that b
3393 * is largest.
3394 */
3395 if (asize > bsize) {
3396 t1 = a;
3397 a = b;
3398 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 i = asize;
3401 asize = bsize;
3402 bsize = i;
3403 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 /* Use gradeschool math when either number is too small. */
3406 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3407 if (asize <= i) {
3408 if (asize == 0)
3409 return (PyLongObject *)PyLong_FromLong(0);
3410 else
3411 return x_mul(a, b);
3412 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 /* If a is small compared to b, splitting on b gives a degenerate
3415 * case with ah==0, and Karatsuba may be (even much) less efficient
3416 * than "grade school" then. However, we can still win, by viewing
3417 * b as a string of "big digits", each of width a->ob_size. That
3418 * leads to a sequence of balanced calls to k_mul.
3419 */
3420 if (2 * asize <= bsize)
3421 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 /* Split a & b into hi & lo pieces. */
3424 shift = bsize >> 1;
3425 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3426 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 if (a == b) {
3429 bh = ah;
3430 bl = al;
3431 Py_INCREF(bh);
3432 Py_INCREF(bl);
3433 }
3434 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 /* The plan:
3437 * 1. Allocate result space (asize + bsize digits: that's always
3438 * enough).
3439 * 2. Compute ah*bh, and copy into result at 2*shift.
3440 * 3. Compute al*bl, and copy into result at 0. Note that this
3441 * can't overlap with #2.
3442 * 4. Subtract al*bl from the result, starting at shift. This may
3443 * underflow (borrow out of the high digit), but we don't care:
3444 * we're effectively doing unsigned arithmetic mod
3445 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3446 * borrows and carries out of the high digit can be ignored.
3447 * 5. Subtract ah*bh from the result, starting at shift.
3448 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3449 * at shift.
3450 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 /* 1. Allocate result space. */
3453 ret = _PyLong_New(asize + bsize);
3454 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003455#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 /* Fill with trash, to catch reference to uninitialized digits. */
3457 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003458#endif
Tim Peters44121a62002-08-12 06:17:58 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3461 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3462 assert(Py_SIZE(t1) >= 0);
3463 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3464 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3465 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 /* Zero-out the digits higher than the ah*bh copy. */
3468 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3469 if (i)
3470 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3471 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 /* 3. t2 <- al*bl, and copy into the low digits. */
3474 if ((t2 = k_mul(al, bl)) == NULL) {
3475 Py_DECREF(t1);
3476 goto fail;
3477 }
3478 assert(Py_SIZE(t2) >= 0);
3479 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3480 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 /* Zero out remaining digits. */
3483 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3484 if (i)
3485 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3488 * because it's fresher in cache.
3489 */
3490 i = Py_SIZE(ret) - shift; /* # digits after shift */
3491 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3492 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3495 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3498 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3499 Py_DECREF(ah);
3500 Py_DECREF(al);
3501 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 if (a == b) {
3504 t2 = t1;
3505 Py_INCREF(t2);
3506 }
3507 else if ((t2 = x_add(bh, bl)) == NULL) {
3508 Py_DECREF(t1);
3509 goto fail;
3510 }
3511 Py_DECREF(bh);
3512 Py_DECREF(bl);
3513 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 t3 = k_mul(t1, t2);
3516 Py_DECREF(t1);
3517 Py_DECREF(t2);
3518 if (t3 == NULL) goto fail;
3519 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 /* Add t3. It's not obvious why we can't run out of room here.
3522 * See the (*) comment after this function.
3523 */
3524 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3525 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003528
Mark Dickinson22b20182010-05-10 21:27:53 +00003529 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 Py_XDECREF(ret);
3531 Py_XDECREF(ah);
3532 Py_XDECREF(al);
3533 Py_XDECREF(bh);
3534 Py_XDECREF(bl);
3535 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003536}
3537
Tim Petersd6974a52002-08-13 20:37:51 +00003538/* (*) Why adding t3 can't "run out of room" above.
3539
Tim Petersab86c2b2002-08-15 20:06:00 +00003540Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3541to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003542
Tim Petersab86c2b2002-08-15 20:06:00 +000035431. For any integer i, i = c(i/2) + f(i/2). In particular,
3544 bsize = c(bsize/2) + f(bsize/2).
35452. shift = f(bsize/2)
35463. asize <= bsize
35474. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3548 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003549
Tim Petersab86c2b2002-08-15 20:06:00 +00003550We allocated asize + bsize result digits, and add t3 into them at an offset
3551of shift. This leaves asize+bsize-shift allocated digit positions for t3
3552to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3553asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003554
Tim Petersab86c2b2002-08-15 20:06:00 +00003555bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3556at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003557
Tim Petersab86c2b2002-08-15 20:06:00 +00003558If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3559digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3560most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003561
Tim Petersab86c2b2002-08-15 20:06:00 +00003562The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003563
Tim Petersab86c2b2002-08-15 20:06:00 +00003564 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003565
Tim Petersab86c2b2002-08-15 20:06:00 +00003566and we have asize + c(bsize/2) available digit positions. We need to show
3567this is always enough. An instance of c(bsize/2) cancels out in both, so
3568the question reduces to whether asize digits is enough to hold
3569(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3570then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3571asize 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 +00003572digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003573asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003574c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3575is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3576bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003577
Tim Peters48d52c02002-08-14 17:07:32 +00003578Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3579clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3580ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003581*/
3582
Tim Peters60004642002-08-12 22:01:34 +00003583/* b has at least twice the digits of a, and a is big enough that Karatsuba
3584 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3585 * of slices, each with a->ob_size digits, and multiply the slices by a,
3586 * one at a time. This gives k_mul balanced inputs to work with, and is
3587 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003588 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003589 * single-width slice overlap between successive partial sums).
3590 */
3591static PyLongObject *
3592k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3593{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003594 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3595 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 Py_ssize_t nbdone; /* # of b digits already multiplied */
3597 PyLongObject *ret;
3598 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 assert(asize > KARATSUBA_CUTOFF);
3601 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 /* Allocate result space, and zero it out. */
3604 ret = _PyLong_New(asize + bsize);
3605 if (ret == NULL)
3606 return NULL;
3607 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 /* Successive slices of b are copied into bslice. */
3610 bslice = _PyLong_New(asize);
3611 if (bslice == NULL)
3612 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 nbdone = 0;
3615 while (bsize > 0) {
3616 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003617 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 /* Multiply the next slice of b by a. */
3620 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3621 nbtouse * sizeof(digit));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003622 Py_SET_SIZE(bslice, nbtouse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 product = k_mul(a, bslice);
3624 if (product == NULL)
3625 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 /* Add into result. */
3628 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3629 product->ob_digit, Py_SIZE(product));
3630 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 bsize -= nbtouse;
3633 nbdone += nbtouse;
3634 }
Tim Peters60004642002-08-12 22:01:34 +00003635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 Py_DECREF(bslice);
3637 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003638
Mark Dickinson22b20182010-05-10 21:27:53 +00003639 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 Py_DECREF(ret);
3641 Py_XDECREF(bslice);
3642 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003643}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003644
3645static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003646long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003653 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003655 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 z = k_mul(a, b);
3659 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003660 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3661 _PyLong_Negate(&z);
3662 if (z == NULL)
3663 return NULL;
3664 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003666}
3667
Yury Selivanove0b23092016-02-11 10:26:27 -05003668/* Fast modulo division for single-digit longs. */
3669static PyObject *
3670fast_mod(PyLongObject *a, PyLongObject *b)
3671{
3672 sdigit left = a->ob_digit[0];
3673 sdigit right = b->ob_digit[0];
3674 sdigit mod;
3675
3676 assert(Py_ABS(Py_SIZE(a)) == 1);
3677 assert(Py_ABS(Py_SIZE(b)) == 1);
3678
3679 if (Py_SIZE(a) == Py_SIZE(b)) {
3680 /* 'a' and 'b' have the same sign. */
3681 mod = left % right;
3682 }
3683 else {
3684 /* Either 'a' or 'b' is negative. */
3685 mod = right - 1 - (left - 1) % right;
3686 }
3687
Victor Stinnerf963c132016-03-23 18:36:54 +01003688 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003689}
3690
3691/* Fast floor division for single-digit longs. */
3692static PyObject *
3693fast_floor_div(PyLongObject *a, PyLongObject *b)
3694{
3695 sdigit left = a->ob_digit[0];
3696 sdigit right = b->ob_digit[0];
3697 sdigit div;
3698
3699 assert(Py_ABS(Py_SIZE(a)) == 1);
3700 assert(Py_ABS(Py_SIZE(b)) == 1);
3701
3702 if (Py_SIZE(a) == Py_SIZE(b)) {
3703 /* 'a' and 'b' have the same sign. */
3704 div = left / right;
3705 }
3706 else {
3707 /* Either 'a' or 'b' is negative. */
3708 div = -1 - (left - 1) / right;
3709 }
3710
3711 return PyLong_FromLong(div);
3712}
3713
Guido van Rossume32e0141992-01-19 16:31:05 +00003714/* The / and % operators are now defined in terms of divmod().
3715 The expression a mod b has the value a - b*floor(a/b).
3716 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003717 |a| by |b|, with the sign of a. This is also expressed
3718 as a - b*trunc(a/b), if trunc truncates towards zero.
3719 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 a b a rem b a mod b
3721 13 10 3 3
3722 -13 10 -3 7
3723 13 -10 3 -7
3724 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003725 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003726 have different signs. We then subtract one from the 'div'
3727 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003728
Tim Peters47e52ee2004-08-30 02:44:38 +00003729/* Compute
3730 * *pdiv, *pmod = divmod(v, w)
3731 * NULL can be passed for pdiv or pmod, in which case that part of
3732 * the result is simply thrown away. The caller owns a reference to
3733 * each of these it requests (does not pass NULL for).
3734 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003735static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003736l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003740
Yury Selivanove0b23092016-02-11 10:26:27 -05003741 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3742 /* Fast path for single-digit longs */
3743 div = NULL;
3744 if (pdiv != NULL) {
3745 div = (PyLongObject *)fast_floor_div(v, w);
3746 if (div == NULL) {
3747 return -1;
3748 }
3749 }
3750 if (pmod != NULL) {
3751 mod = (PyLongObject *)fast_mod(v, w);
3752 if (mod == NULL) {
3753 Py_XDECREF(div);
3754 return -1;
3755 }
3756 *pmod = mod;
3757 }
3758 if (pdiv != NULL) {
3759 /* We only want to set `*pdiv` when `*pmod` is
3760 set successfully. */
3761 *pdiv = div;
3762 }
3763 return 0;
3764 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 if (long_divrem(v, w, &div, &mod) < 0)
3766 return -1;
3767 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3768 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3769 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 temp = (PyLongObject *) long_add(mod, w);
3771 Py_DECREF(mod);
3772 mod = temp;
3773 if (mod == NULL) {
3774 Py_DECREF(div);
3775 return -1;
3776 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003777 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3778 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 Py_DECREF(mod);
3780 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 return -1;
3782 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 Py_DECREF(div);
3784 div = temp;
3785 }
3786 if (pdiv != NULL)
3787 *pdiv = div;
3788 else
3789 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 if (pmod != NULL)
3792 *pmod = mod;
3793 else
3794 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003797}
3798
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003799static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003800long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003805
3806 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3807 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3808 }
3809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3811 div = NULL;
3812 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003813}
3814
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003815/* PyLong/PyLong -> float, with correctly rounded result. */
3816
3817#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3818#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3819
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003820static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003821long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 PyLongObject *a, *b, *x;
3824 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3825 digit mask, low;
3826 int inexact, negate, a_is_small, b_is_small;
3827 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 CHECK_BINOP(v, w);
3830 a = (PyLongObject *)v;
3831 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 /*
3834 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3837 1. choose a suitable integer 'shift'
3838 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3839 3. adjust x for correct rounding
3840 4. convert x to a double dx with the same value
3841 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3846 returns either 0.0 or -0.0, depending on the sign of b. For a and
3847 b both nonzero, ignore signs of a and b, and add the sign back in
3848 at the end. Now write a_bits and b_bits for the bit lengths of a
3849 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3850 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3855 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3856 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3857 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 1. The integer 'shift' is chosen so that x has the right number of
3862 bits for a double, plus two or three extra bits that will be used
3863 in the rounding decisions. Writing a_bits and b_bits for the
3864 number of significant bits in a and b respectively, a
3865 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 This is fine in the usual case, but if a/b is smaller than the
3870 smallest normal float then it can lead to double rounding on an
3871 IEEE 754 platform, giving incorrectly rounded results. So we
3872 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 2. The quantity x is computed by first shifting a (left -shift bits
3877 if shift <= 0, right shift bits if shift > 0) and then dividing by
3878 b. For both the shift and the division, we keep track of whether
3879 the result is inexact, in a flag 'inexact'; this information is
3880 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 With the choice of shift above, together with our assumption that
3883 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3884 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3887 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 For float representability, we need x/2**extra_bits <
3892 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3893 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 To round, we just modify the bottom digit of x in-place; this can
3898 end up giving a digit with value > PyLONG_MASK, but that's not a
3899 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 With the original choices for shift above, extra_bits will always
3902 be 2 or 3. Then rounding under the round-half-to-even rule, we
3903 round up iff the most significant of the extra bits is 1, and
3904 either: (a) the computation of x in step 2 had an inexact result,
3905 or (b) at least one other of the extra bits is 1, or (c) the least
3906 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 4. Conversion to a double is straightforward; all floating-point
3909 operations involved in the conversion are exact, so there's no
3910 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3913 The result will always be exactly representable as a double, except
3914 in the case that it overflows. To avoid dependence on the exact
3915 behaviour of ldexp on overflow, we check for overflow before
3916 applying ldexp. The result of ldexp is adjusted for sign before
3917 returning.
3918 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003921 a_size = Py_ABS(Py_SIZE(a));
3922 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3924 if (b_size == 0) {
3925 PyErr_SetString(PyExc_ZeroDivisionError,
3926 "division by zero");
3927 goto error;
3928 }
3929 if (a_size == 0)
3930 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 /* Fast path for a and b small (exactly representable in a double).
3933 Relies on floating-point division being correctly rounded; results
3934 may be subject to double rounding on x86 machines that operate with
3935 the x87 FPU set to 64-bit precision. */
3936 a_is_small = a_size <= MANT_DIG_DIGITS ||
3937 (a_size == MANT_DIG_DIGITS+1 &&
3938 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3939 b_is_small = b_size <= MANT_DIG_DIGITS ||
3940 (b_size == MANT_DIG_DIGITS+1 &&
3941 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3942 if (a_is_small && b_is_small) {
3943 double da, db;
3944 da = a->ob_digit[--a_size];
3945 while (a_size > 0)
3946 da = da * PyLong_BASE + a->ob_digit[--a_size];
3947 db = b->ob_digit[--b_size];
3948 while (b_size > 0)
3949 db = db * PyLong_BASE + b->ob_digit[--b_size];
3950 result = da / db;
3951 goto success;
3952 }
Tim Peterse2a60002001-09-04 06:17:36 +00003953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 /* Catch obvious cases of underflow and overflow */
3955 diff = a_size - b_size;
3956 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3957 /* Extreme overflow */
3958 goto overflow;
3959 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3960 /* Extreme underflow */
3961 goto underflow_or_zero;
3962 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01003963 diff = diff * PyLong_SHIFT + _Py_bit_length(a->ob_digit[a_size - 1]) -
3964 _Py_bit_length(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 /* Now diff = a_bits - b_bits. */
3966 if (diff > DBL_MAX_EXP)
3967 goto overflow;
3968 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3969 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003972 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 /* x = abs(a * 2**-shift) */
3977 if (shift <= 0) {
3978 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3979 digit rem;
3980 /* x = a << -shift */
3981 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3982 /* In practice, it's probably impossible to end up
3983 here. Both a and b would have to be enormous,
3984 using close to SIZE_T_MAX bytes of memory each. */
3985 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003986 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 goto error;
3988 }
3989 x = _PyLong_New(a_size + shift_digits + 1);
3990 if (x == NULL)
3991 goto error;
3992 for (i = 0; i < shift_digits; i++)
3993 x->ob_digit[i] = 0;
3994 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3995 a_size, -shift % PyLong_SHIFT);
3996 x->ob_digit[a_size + shift_digits] = rem;
3997 }
3998 else {
3999 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
4000 digit rem;
4001 /* x = a >> shift */
4002 assert(a_size >= shift_digits);
4003 x = _PyLong_New(a_size - shift_digits);
4004 if (x == NULL)
4005 goto error;
4006 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4007 a_size - shift_digits, shift % PyLong_SHIFT);
4008 /* set inexact if any of the bits shifted out is nonzero */
4009 if (rem)
4010 inexact = 1;
4011 while (!inexact && shift_digits > 0)
4012 if (a->ob_digit[--shift_digits])
4013 inexact = 1;
4014 }
4015 long_normalize(x);
4016 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4019 reference to x, so it's safe to modify it in-place. */
4020 if (b_size == 1) {
4021 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4022 b->ob_digit[0]);
4023 long_normalize(x);
4024 if (rem)
4025 inexact = 1;
4026 }
4027 else {
4028 PyLongObject *div, *rem;
4029 div = x_divrem(x, b, &rem);
4030 Py_DECREF(x);
4031 x = div;
4032 if (x == NULL)
4033 goto error;
4034 if (Py_SIZE(rem))
4035 inexact = 1;
4036 Py_DECREF(rem);
4037 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004038 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004040 x_bits = (x_size-1)*PyLong_SHIFT+_Py_bit_length(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004043 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 /* Round by directly modifying the low digit of x. */
4047 mask = (digit)1 << (extra_bits - 1);
4048 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004049 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004051 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 /* Convert x to a double dx; the conversion is exact. */
4054 dx = x->ob_digit[--x_size];
4055 while (x_size > 0)
4056 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4057 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 /* Check whether ldexp result will overflow a double. */
4060 if (shift + x_bits >= DBL_MAX_EXP &&
4061 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4062 goto overflow;
4063 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004064
4065 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004067
4068 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004070
4071 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 PyErr_SetString(PyExc_OverflowError,
4073 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004074 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004075 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004076}
4077
4078static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004079long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 CHECK_BINOP(a, b);
4084
Yury Selivanove0b23092016-02-11 10:26:27 -05004085 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4086 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4087 }
4088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4090 mod = NULL;
4091 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004092}
4093
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004094static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004095long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 PyLongObject *div, *mod;
4098 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4103 return NULL;
4104 }
4105 z = PyTuple_New(2);
4106 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004107 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4108 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 }
4110 else {
4111 Py_DECREF(div);
4112 Py_DECREF(mod);
4113 }
4114 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004115}
4116
Mark Dickinsonc5299672019-06-02 10:24:06 +01004117
4118/* Compute an inverse to a modulo n, or raise ValueError if a is not
4119 invertible modulo n. Assumes n is positive. The inverse returned
4120 is whatever falls out of the extended Euclidean algorithm: it may
4121 be either positive or negative, but will be smaller than n in
4122 absolute value.
4123
4124 Pure Python equivalent for long_invmod:
4125
4126 def invmod(a, n):
4127 b, c = 1, 0
4128 while n:
4129 q, r = divmod(a, n)
4130 a, b, c, n = n, c, b - q*c, r
4131
4132 # at this point a is the gcd of the original inputs
4133 if a == 1:
4134 return b
4135 raise ValueError("Not invertible")
4136*/
4137
4138static PyLongObject *
4139long_invmod(PyLongObject *a, PyLongObject *n)
4140{
4141 PyLongObject *b, *c;
4142
4143 /* Should only ever be called for positive n */
4144 assert(Py_SIZE(n) > 0);
4145
4146 b = (PyLongObject *)PyLong_FromLong(1L);
4147 if (b == NULL) {
4148 return NULL;
4149 }
4150 c = (PyLongObject *)PyLong_FromLong(0L);
4151 if (c == NULL) {
4152 Py_DECREF(b);
4153 return NULL;
4154 }
4155 Py_INCREF(a);
4156 Py_INCREF(n);
4157
4158 /* references now owned: a, b, c, n */
4159 while (Py_SIZE(n) != 0) {
4160 PyLongObject *q, *r, *s, *t;
4161
4162 if (l_divmod(a, n, &q, &r) == -1) {
4163 goto Error;
4164 }
4165 Py_DECREF(a);
4166 a = n;
4167 n = r;
4168 t = (PyLongObject *)long_mul(q, c);
4169 Py_DECREF(q);
4170 if (t == NULL) {
4171 goto Error;
4172 }
4173 s = (PyLongObject *)long_sub(b, t);
4174 Py_DECREF(t);
4175 if (s == NULL) {
4176 goto Error;
4177 }
4178 Py_DECREF(b);
4179 b = c;
4180 c = s;
4181 }
4182 /* references now owned: a, b, c, n */
4183
4184 Py_DECREF(c);
4185 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004186 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004187 /* a != 1; we don't have an inverse. */
4188 Py_DECREF(a);
4189 Py_DECREF(b);
4190 PyErr_SetString(PyExc_ValueError,
4191 "base is not invertible for the given modulus");
4192 return NULL;
4193 }
4194 else {
4195 /* a == 1; b gives an inverse modulo n */
4196 Py_DECREF(a);
4197 return b;
4198 }
4199
4200 Error:
4201 Py_DECREF(a);
4202 Py_DECREF(b);
4203 Py_DECREF(c);
4204 Py_DECREF(n);
4205 return NULL;
4206}
4207
4208
Tim Peters47e52ee2004-08-30 02:44:38 +00004209/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004210static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004211long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4214 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 PyLongObject *z = NULL; /* accumulated result */
4217 Py_ssize_t i, j, k; /* counters */
4218 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 /* 5-ary values. If the exponent is large enough, table is
4221 * precomputed so that table[i] == a**i % c for i in range(32).
4222 */
4223 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4224 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 /* a, b, c = v, w, x */
4227 CHECK_BINOP(v, w);
4228 a = (PyLongObject*)v; Py_INCREF(a);
4229 b = (PyLongObject*)w; Py_INCREF(b);
4230 if (PyLong_Check(x)) {
4231 c = (PyLongObject *)x;
4232 Py_INCREF(x);
4233 }
4234 else if (x == Py_None)
4235 c = NULL;
4236 else {
4237 Py_DECREF(a);
4238 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004239 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004240 }
Tim Peters4c483c42001-09-05 06:24:58 +00004241
Mark Dickinsonc5299672019-06-02 10:24:06 +01004242 if (Py_SIZE(b) < 0 && c == NULL) {
4243 /* if exponent is negative and there's no modulus:
4244 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 that this calls float_pow() which converts its
4246 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004247 Py_DECREF(a);
4248 Py_DECREF(b);
4249 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 if (c) {
4253 /* if modulus == 0:
4254 raise ValueError() */
4255 if (Py_SIZE(c) == 0) {
4256 PyErr_SetString(PyExc_ValueError,
4257 "pow() 3rd argument cannot be 0");
4258 goto Error;
4259 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 /* if modulus < 0:
4262 negativeOutput = True
4263 modulus = -modulus */
4264 if (Py_SIZE(c) < 0) {
4265 negativeOutput = 1;
4266 temp = (PyLongObject *)_PyLong_Copy(c);
4267 if (temp == NULL)
4268 goto Error;
4269 Py_DECREF(c);
4270 c = temp;
4271 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004272 _PyLong_Negate(&c);
4273 if (c == NULL)
4274 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 /* if modulus == 1:
4278 return 0 */
4279 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4280 z = (PyLongObject *)PyLong_FromLong(0L);
4281 goto Done;
4282 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004283
Mark Dickinsonc5299672019-06-02 10:24:06 +01004284 /* if exponent is negative, negate the exponent and
4285 replace the base with a modular inverse */
4286 if (Py_SIZE(b) < 0) {
4287 temp = (PyLongObject *)_PyLong_Copy(b);
4288 if (temp == NULL)
4289 goto Error;
4290 Py_DECREF(b);
4291 b = temp;
4292 temp = NULL;
4293 _PyLong_Negate(&b);
4294 if (b == NULL)
4295 goto Error;
4296
4297 temp = long_invmod(a, c);
4298 if (temp == NULL)
4299 goto Error;
4300 Py_DECREF(a);
4301 a = temp;
4302 }
4303
Tim Peters81a93152013-10-05 16:53:52 -05004304 /* Reduce base by modulus in some cases:
4305 1. If base < 0. Forcing the base non-negative makes things easier.
4306 2. If base is obviously larger than the modulus. The "small
4307 exponent" case later can multiply directly by base repeatedly,
4308 while the "large exponent" case multiplies directly by base 31
4309 times. It can be unboundedly faster to multiply by
4310 base % modulus instead.
4311 We could _always_ do this reduction, but l_divmod() isn't cheap,
4312 so we only do it when it buys something. */
4313 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 if (l_divmod(a, c, NULL, &temp) < 0)
4315 goto Error;
4316 Py_DECREF(a);
4317 a = temp;
4318 temp = NULL;
4319 }
4320 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 /* At this point a, b, and c are guaranteed non-negative UNLESS
4323 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 z = (PyLongObject *)PyLong_FromLong(1L);
4326 if (z == NULL)
4327 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 /* Perform a modular reduction, X = X % c, but leave X alone if c
4330 * is NULL.
4331 */
4332#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004333 do { \
4334 if (c != NULL) { \
4335 if (l_divmod(X, c, NULL, &temp) < 0) \
4336 goto Error; \
4337 Py_XDECREF(X); \
4338 X = temp; \
4339 temp = NULL; \
4340 } \
4341 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 /* Multiply two values, then reduce the result:
4344 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004345#define MULT(X, Y, result) \
4346 do { \
4347 temp = (PyLongObject *)long_mul(X, Y); \
4348 if (temp == NULL) \
4349 goto Error; \
4350 Py_XDECREF(result); \
4351 result = temp; \
4352 temp = NULL; \
4353 REDUCE(result); \
4354 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4357 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4358 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4359 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4360 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004363 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004365 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 }
4367 }
4368 }
4369 else {
4370 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4371 Py_INCREF(z); /* still holds 1L */
4372 table[0] = z;
4373 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004374 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4377 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4380 const int index = (bi >> j) & 0x1f;
4381 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004382 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004384 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 }
4386 }
4387 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 if (negativeOutput && (Py_SIZE(z) != 0)) {
4390 temp = (PyLongObject *)long_sub(z, c);
4391 if (temp == NULL)
4392 goto Error;
4393 Py_DECREF(z);
4394 z = temp;
4395 temp = NULL;
4396 }
4397 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004398
Mark Dickinson22b20182010-05-10 21:27:53 +00004399 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004400 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004402 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4404 for (i = 0; i < 32; ++i)
4405 Py_XDECREF(table[i]);
4406 }
4407 Py_DECREF(a);
4408 Py_DECREF(b);
4409 Py_XDECREF(c);
4410 Py_XDECREF(temp);
4411 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004412}
4413
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004414static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004415long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 /* Implement ~x as -(x+1) */
4418 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004419 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004421 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 if (x == NULL)
4423 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004424 _PyLong_Negate(&x);
4425 /* No need for maybe_small_long here, since any small
4426 longs will have been caught in the Py_SIZE <= 1 fast path. */
4427 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004428}
4429
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004430static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004431long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004434 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 return PyLong_FromLong(-MEDIUM_VALUE(v));
4436 z = (PyLongObject *)_PyLong_Copy(v);
4437 if (z != NULL)
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004438 Py_SET_SIZE(z, -(Py_SIZE(v)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004440}
4441
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004442static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004443long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 if (Py_SIZE(v) < 0)
4446 return long_neg(v);
4447 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004448 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004449}
4450
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004451static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004452long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004455}
4456
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004457/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4458static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004459divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004460{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004461 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004462 assert(Py_SIZE(shiftby) >= 0);
4463 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4464 if (lshiftby >= 0) {
4465 *wordshift = lshiftby / PyLong_SHIFT;
4466 *remshift = lshiftby % PyLong_SHIFT;
4467 return 0;
4468 }
4469 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4470 be that PyLong_AsSsize_t raised an OverflowError. */
4471 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4472 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004473 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004474 if (wordshift_obj == NULL) {
4475 return -1;
4476 }
4477 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4478 Py_DECREF(wordshift_obj);
4479 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4480 return 0;
4481 }
4482 PyErr_Clear();
4483 /* Clip the value. With such large wordshift the right shift
4484 returns 0 and the left shift raises an error in _PyLong_New(). */
4485 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4486 *remshift = 0;
4487 return 0;
4488}
4489
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004490static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004491long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004494 Py_ssize_t newsize, hishift, i, j;
4495 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 if (Py_SIZE(a) < 0) {
4498 /* Right shifting negative numbers is harder */
4499 PyLongObject *a1, *a2;
4500 a1 = (PyLongObject *) long_invert(a);
4501 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004502 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004503 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 Py_DECREF(a1);
4505 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004506 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 z = (PyLongObject *) long_invert(a2);
4508 Py_DECREF(a2);
4509 }
4510 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004511 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 if (newsize <= 0)
4513 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004514 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 lomask = ((digit)1 << hishift) - 1;
4516 himask = PyLong_MASK ^ lomask;
4517 z = _PyLong_New(newsize);
4518 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004519 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004521 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004523 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004525 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004527 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004528}
4529
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004530static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004531long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004532{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004533 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004534 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004537
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004538 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004540 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004542 if (Py_SIZE(a) == 0) {
4543 return PyLong_FromLong(0);
4544 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004545 if (divmod_shift(b, &wordshift, &remshift) < 0)
4546 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004547 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4548}
4549
4550/* Return a >> shiftby. */
4551PyObject *
4552_PyLong_Rshift(PyObject *a, size_t shiftby)
4553{
4554 Py_ssize_t wordshift;
4555 digit remshift;
4556
4557 assert(PyLong_Check(a));
4558 if (Py_SIZE(a) == 0) {
4559 return PyLong_FromLong(0);
4560 }
4561 wordshift = shiftby / PyLong_SHIFT;
4562 remshift = shiftby % PyLong_SHIFT;
4563 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4564}
4565
4566static PyObject *
4567long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4568{
4569 /* This version due to Tim Peters */
4570 PyLongObject *z = NULL;
4571 Py_ssize_t oldsize, newsize, i, j;
4572 twodigits accum;
4573
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004574 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 newsize = oldsize + wordshift;
4576 if (remshift)
4577 ++newsize;
4578 z = _PyLong_New(newsize);
4579 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004580 return NULL;
4581 if (Py_SIZE(a) < 0) {
4582 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004583 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02004584 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 for (i = 0; i < wordshift; i++)
4586 z->ob_digit[i] = 0;
4587 accum = 0;
4588 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4589 accum |= (twodigits)a->ob_digit[j] << remshift;
4590 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4591 accum >>= PyLong_SHIFT;
4592 }
4593 if (remshift)
4594 z->ob_digit[newsize-1] = (digit)accum;
4595 else
4596 assert(!accum);
4597 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004599}
4600
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004601static PyObject *
4602long_lshift(PyObject *a, PyObject *b)
4603{
4604 Py_ssize_t wordshift;
4605 digit remshift;
4606
4607 CHECK_BINOP(a, b);
4608
4609 if (Py_SIZE(b) < 0) {
4610 PyErr_SetString(PyExc_ValueError, "negative shift count");
4611 return NULL;
4612 }
4613 if (Py_SIZE(a) == 0) {
4614 return PyLong_FromLong(0);
4615 }
4616 if (divmod_shift(b, &wordshift, &remshift) < 0)
4617 return NULL;
4618 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4619}
4620
4621/* Return a << shiftby. */
4622PyObject *
4623_PyLong_Lshift(PyObject *a, size_t shiftby)
4624{
4625 Py_ssize_t wordshift;
4626 digit remshift;
4627
4628 assert(PyLong_Check(a));
4629 if (Py_SIZE(a) == 0) {
4630 return PyLong_FromLong(0);
4631 }
4632 wordshift = shiftby / PyLong_SHIFT;
4633 remshift = shiftby % PyLong_SHIFT;
4634 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4635}
4636
Mark Dickinson27a87a22009-10-25 20:43:34 +00004637/* Compute two's complement of digit vector a[0:m], writing result to
4638 z[0:m]. The digit vector a need not be normalized, but should not
4639 be entirely zero. a and z may point to the same digit vector. */
4640
4641static void
4642v_complement(digit *z, digit *a, Py_ssize_t m)
4643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 Py_ssize_t i;
4645 digit carry = 1;
4646 for (i = 0; i < m; ++i) {
4647 carry += a[i] ^ PyLong_MASK;
4648 z[i] = carry & PyLong_MASK;
4649 carry >>= PyLong_SHIFT;
4650 }
4651 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004652}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004653
4654/* Bitwise and/xor/or operations */
4655
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004656static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004657long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004658 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004659 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 int nega, negb, negz;
4662 Py_ssize_t size_a, size_b, size_z, i;
4663 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 /* Bitwise operations for negative numbers operate as though
4666 on a two's complement representation. So convert arguments
4667 from sign-magnitude to two's complement, and convert the
4668 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004671 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 nega = Py_SIZE(a) < 0;
4673 if (nega) {
4674 z = _PyLong_New(size_a);
4675 if (z == NULL)
4676 return NULL;
4677 v_complement(z->ob_digit, a->ob_digit, size_a);
4678 a = z;
4679 }
4680 else
4681 /* Keep reference count consistent. */
4682 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004685 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 negb = Py_SIZE(b) < 0;
4687 if (negb) {
4688 z = _PyLong_New(size_b);
4689 if (z == NULL) {
4690 Py_DECREF(a);
4691 return NULL;
4692 }
4693 v_complement(z->ob_digit, b->ob_digit, size_b);
4694 b = z;
4695 }
4696 else
4697 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 /* Swap a and b if necessary to ensure size_a >= size_b. */
4700 if (size_a < size_b) {
4701 z = a; a = b; b = z;
4702 size_z = size_a; size_a = size_b; size_b = size_z;
4703 negz = nega; nega = negb; negb = negz;
4704 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 /* JRH: The original logic here was to allocate the result value (z)
4707 as the longer of the two operands. However, there are some cases
4708 where the result is guaranteed to be shorter than that: AND of two
4709 positives, OR of two negatives: use the shorter number. AND with
4710 mixed signs: use the positive number. OR with mixed signs: use the
4711 negative number.
4712 */
4713 switch (op) {
4714 case '^':
4715 negz = nega ^ negb;
4716 size_z = size_a;
4717 break;
4718 case '&':
4719 negz = nega & negb;
4720 size_z = negb ? size_a : size_b;
4721 break;
4722 case '|':
4723 negz = nega | negb;
4724 size_z = negb ? size_b : size_a;
4725 break;
4726 default:
stratakisa10d4262019-03-18 18:59:20 +01004727 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 /* We allow an extra digit if z is negative, to make sure that
4731 the final two's complement of z doesn't overflow. */
4732 z = _PyLong_New(size_z + negz);
4733 if (z == NULL) {
4734 Py_DECREF(a);
4735 Py_DECREF(b);
4736 return NULL;
4737 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 /* Compute digits for overlap of a and b. */
4740 switch(op) {
4741 case '&':
4742 for (i = 0; i < size_b; ++i)
4743 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4744 break;
4745 case '|':
4746 for (i = 0; i < size_b; ++i)
4747 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4748 break;
4749 case '^':
4750 for (i = 0; i < size_b; ++i)
4751 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4752 break;
4753 default:
stratakisa10d4262019-03-18 18:59:20 +01004754 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004755 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 /* Copy any remaining digits of a, inverting if necessary. */
4758 if (op == '^' && negb)
4759 for (; i < size_z; ++i)
4760 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4761 else if (i < size_z)
4762 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4763 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 /* Complement result if negative. */
4766 if (negz) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004767 Py_SET_SIZE(z, -(Py_SIZE(z)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 z->ob_digit[size_z] = PyLong_MASK;
4769 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4770 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 Py_DECREF(a);
4773 Py_DECREF(b);
4774 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004775}
4776
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004777static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004778long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 PyObject *c;
4781 CHECK_BINOP(a, b);
4782 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4783 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004784}
4785
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004786static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004787long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 PyObject *c;
4790 CHECK_BINOP(a, b);
4791 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4792 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004793}
4794
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004795static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004796long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 PyObject *c;
4799 CHECK_BINOP(a, b);
4800 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4801 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004802}
4803
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004804static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004805long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 if (PyLong_CheckExact(v))
4808 Py_INCREF(v);
4809 else
4810 v = _PyLong_Copy((PyLongObject *)v);
4811 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004812}
4813
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004814PyObject *
4815_PyLong_GCD(PyObject *aarg, PyObject *barg)
4816{
4817 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4818 stwodigits x, y, q, s, t, c_carry, d_carry;
4819 stwodigits A, B, C, D, T;
4820 int nbits, k;
4821 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4822 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4823
4824 a = (PyLongObject *)aarg;
4825 b = (PyLongObject *)barg;
4826 size_a = Py_SIZE(a);
4827 size_b = Py_SIZE(b);
4828 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4829 Py_INCREF(a);
4830 Py_INCREF(b);
4831 goto simple;
4832 }
4833
4834 /* Initial reduction: make sure that 0 <= b <= a. */
4835 a = (PyLongObject *)long_abs(a);
4836 if (a == NULL)
4837 return NULL;
4838 b = (PyLongObject *)long_abs(b);
4839 if (b == NULL) {
4840 Py_DECREF(a);
4841 return NULL;
4842 }
4843 if (long_compare(a, b) < 0) {
4844 r = a;
4845 a = b;
4846 b = r;
4847 }
4848 /* We now own references to a and b */
4849
4850 alloc_a = Py_SIZE(a);
4851 alloc_b = Py_SIZE(b);
4852 /* reduce until a fits into 2 digits */
4853 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004854 nbits = _Py_bit_length(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004855 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4856 corresponding bits of b into y */
4857 size_b = Py_SIZE(b);
4858 assert(size_b <= size_a);
4859 if (size_b == 0) {
4860 if (size_a < alloc_a) {
4861 r = (PyLongObject *)_PyLong_Copy(a);
4862 Py_DECREF(a);
4863 }
4864 else
4865 r = a;
4866 Py_DECREF(b);
4867 Py_XDECREF(c);
4868 Py_XDECREF(d);
4869 return (PyObject *)r;
4870 }
4871 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4872 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4873 (a->ob_digit[size_a-3] >> nbits));
4874
4875 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4876 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4877 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4878
4879 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4880 larger than PyLong_MASK during the algorithm. */
4881 A = 1; B = 0; C = 0; D = 1;
4882 for (k=0;; k++) {
4883 if (y-C == 0)
4884 break;
4885 q = (x+(A-1))/(y-C);
4886 s = B+q*D;
4887 t = x-q*y;
4888 if (s > t)
4889 break;
4890 x = y; y = t;
4891 t = A+q*C; A = D; B = C; C = s; D = t;
4892 }
4893
4894 if (k == 0) {
4895 /* no progress; do a Euclidean step */
4896 if (l_divmod(a, b, NULL, &r) < 0)
4897 goto error;
4898 Py_DECREF(a);
4899 a = b;
4900 b = r;
4901 alloc_a = alloc_b;
4902 alloc_b = Py_SIZE(b);
4903 continue;
4904 }
4905
4906 /*
4907 a, b = A*b-B*a, D*a-C*b if k is odd
4908 a, b = A*a-B*b, D*b-C*a if k is even
4909 */
4910 if (k&1) {
4911 T = -A; A = -B; B = T;
4912 T = -C; C = -D; D = T;
4913 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004914 if (c != NULL) {
4915 Py_SET_SIZE(c, size_a);
4916 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004917 else if (Py_REFCNT(a) == 1) {
4918 Py_INCREF(a);
4919 c = a;
4920 }
4921 else {
4922 alloc_a = size_a;
4923 c = _PyLong_New(size_a);
4924 if (c == NULL)
4925 goto error;
4926 }
4927
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004928 if (d != NULL) {
4929 Py_SET_SIZE(d, size_a);
4930 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004931 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4932 Py_INCREF(b);
4933 d = b;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004934 Py_SET_SIZE(d, size_a);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004935 }
4936 else {
4937 alloc_b = size_a;
4938 d = _PyLong_New(size_a);
4939 if (d == NULL)
4940 goto error;
4941 }
4942 a_end = a->ob_digit + size_a;
4943 b_end = b->ob_digit + size_b;
4944
4945 /* compute new a and new b in parallel */
4946 a_digit = a->ob_digit;
4947 b_digit = b->ob_digit;
4948 c_digit = c->ob_digit;
4949 d_digit = d->ob_digit;
4950 c_carry = 0;
4951 d_carry = 0;
4952 while (b_digit < b_end) {
4953 c_carry += (A * *a_digit) - (B * *b_digit);
4954 d_carry += (D * *b_digit++) - (C * *a_digit++);
4955 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4956 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4957 c_carry >>= PyLong_SHIFT;
4958 d_carry >>= PyLong_SHIFT;
4959 }
4960 while (a_digit < a_end) {
4961 c_carry += A * *a_digit;
4962 d_carry -= C * *a_digit++;
4963 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4964 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4965 c_carry >>= PyLong_SHIFT;
4966 d_carry >>= PyLong_SHIFT;
4967 }
4968 assert(c_carry == 0);
4969 assert(d_carry == 0);
4970
4971 Py_INCREF(c);
4972 Py_INCREF(d);
4973 Py_DECREF(a);
4974 Py_DECREF(b);
4975 a = long_normalize(c);
4976 b = long_normalize(d);
4977 }
4978 Py_XDECREF(c);
4979 Py_XDECREF(d);
4980
4981simple:
4982 assert(Py_REFCNT(a) > 0);
4983 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004984/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4985 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4986#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004987 /* a fits into a long, so b must too */
4988 x = PyLong_AsLong((PyObject *)a);
4989 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004990#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004991 x = PyLong_AsLongLong((PyObject *)a);
4992 y = PyLong_AsLongLong((PyObject *)b);
4993#else
4994# error "_PyLong_GCD"
4995#endif
4996 x = Py_ABS(x);
4997 y = Py_ABS(y);
4998 Py_DECREF(a);
4999 Py_DECREF(b);
5000
5001 /* usual Euclidean algorithm for longs */
5002 while (y != 0) {
5003 t = y;
5004 y = x % y;
5005 x = t;
5006 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005007#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005008 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05005009#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005010 return PyLong_FromLongLong(x);
5011#else
5012# error "_PyLong_GCD"
5013#endif
5014
5015error:
5016 Py_DECREF(a);
5017 Py_DECREF(b);
5018 Py_XDECREF(c);
5019 Py_XDECREF(d);
5020 return NULL;
5021}
5022
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005023static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005024long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 double result;
5027 result = PyLong_AsDouble(v);
5028 if (result == -1.0 && PyErr_Occurred())
5029 return NULL;
5030 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005031}
5032
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005033static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005034long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5035
5036/*[clinic input]
5037@classmethod
5038int.__new__ as long_new
5039 x: object(c_default="NULL") = 0
5040 /
5041 base as obase: object(c_default="NULL") = 10
5042[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005043
Tim Peters6d6c1a32001-08-02 04:15:00 +00005044static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005045long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5046/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005047{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005048 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005051 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005052 if (x == NULL) {
5053 if (obase != NULL) {
5054 PyErr_SetString(PyExc_TypeError,
5055 "int() missing string argument");
5056 return NULL;
5057 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005059 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005060 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005062
Gregory P. Smitha689e522012-12-25 22:38:32 -08005063 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005064 if (base == -1 && PyErr_Occurred())
5065 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005066 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005067 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305068 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005069 return NULL;
5070 }
5071
5072 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005073 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03005075 const char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 if (PyByteArray_Check(x))
5077 string = PyByteArray_AS_STRING(x);
5078 else
5079 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005080 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005081 }
5082 else {
5083 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005084 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 return NULL;
5086 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005087}
5088
Serhiy Storchaka95949422013-08-27 19:40:23 +03005089/* Wimpy, slow approach to tp_new calls for subtypes of int:
5090 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005091 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005092 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005093*/
5094static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005095long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005097 PyLongObject *tmp, *newobj;
5098 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005100 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005101 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 if (tmp == NULL)
5103 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005104 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 n = Py_SIZE(tmp);
5106 if (n < 0)
5107 n = -n;
5108 newobj = (PyLongObject *)type->tp_alloc(type, n);
5109 if (newobj == NULL) {
5110 Py_DECREF(tmp);
5111 return NULL;
5112 }
5113 assert(PyLong_Check(newobj));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005114 Py_SET_SIZE(newobj, Py_SIZE(tmp));
5115 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 newobj->ob_digit[i] = tmp->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005117 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 Py_DECREF(tmp);
5119 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005120}
5121
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005122/*[clinic input]
5123int.__getnewargs__
5124[clinic start generated code]*/
5125
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005126static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005127int___getnewargs___impl(PyObject *self)
5128/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005129{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005130 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005131}
5132
Guido van Rossumb43daf72007-08-01 18:08:08 +00005133static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005134long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005137}
5138
5139static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005140long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005143}
5144
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005145/*[clinic input]
5146int.__format__
5147
5148 format_spec: unicode
5149 /
5150[clinic start generated code]*/
5151
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005152static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005153int___format___impl(PyObject *self, PyObject *format_spec)
5154/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005155{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005156 _PyUnicodeWriter writer;
5157 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005158
Victor Stinner8f674cc2013-04-17 23:02:17 +02005159 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005160 ret = _PyLong_FormatAdvancedWriter(
5161 &writer,
5162 self,
5163 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5164 if (ret == -1) {
5165 _PyUnicodeWriter_Dealloc(&writer);
5166 return NULL;
5167 }
5168 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005169}
5170
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005171/* Return a pair (q, r) such that a = b * q + r, and
5172 abs(r) <= abs(b)/2, with equality possible only if q is even.
5173 In other words, q == a / b, rounded to the nearest integer using
5174 round-half-to-even. */
5175
5176PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005177_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005178{
5179 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005180 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005181 int quo_is_odd, quo_is_neg;
5182 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005183
5184 /* Equivalent Python code:
5185
5186 def divmod_near(a, b):
5187 q, r = divmod(a, b)
5188 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5189 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5190 # positive, 2 * r < b if b negative.
5191 greater_than_half = 2*r > b if b > 0 else 2*r < b
5192 exactly_half = 2*r == b
5193 if greater_than_half or exactly_half and q % 2 == 1:
5194 q += 1
5195 r -= b
5196 return q, r
5197
5198 */
5199 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5200 PyErr_SetString(PyExc_TypeError,
5201 "non-integer arguments in division");
5202 return NULL;
5203 }
5204
5205 /* Do a and b have different signs? If so, quotient is negative. */
5206 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5207
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005208 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5209 goto error;
5210
5211 /* compare twice the remainder with the divisor, to see
5212 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005213 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005214 if (twice_rem == NULL)
5215 goto error;
5216 if (quo_is_neg) {
5217 temp = long_neg((PyLongObject*)twice_rem);
5218 Py_DECREF(twice_rem);
5219 twice_rem = temp;
5220 if (twice_rem == NULL)
5221 goto error;
5222 }
5223 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5224 Py_DECREF(twice_rem);
5225
5226 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5227 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5228 /* fix up quotient */
5229 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005230 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005231 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005232 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005233 Py_DECREF(quo);
5234 quo = (PyLongObject *)temp;
5235 if (quo == NULL)
5236 goto error;
5237 /* and remainder */
5238 if (quo_is_neg)
5239 temp = long_add(rem, (PyLongObject *)b);
5240 else
5241 temp = long_sub(rem, (PyLongObject *)b);
5242 Py_DECREF(rem);
5243 rem = (PyLongObject *)temp;
5244 if (rem == NULL)
5245 goto error;
5246 }
5247
5248 result = PyTuple_New(2);
5249 if (result == NULL)
5250 goto error;
5251
5252 /* PyTuple_SET_ITEM steals references */
5253 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5254 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005255 return result;
5256
5257 error:
5258 Py_XDECREF(quo);
5259 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005260 return NULL;
5261}
5262
Eric Smith8c663262007-08-25 02:26:07 +00005263static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005264long_round(PyObject *self, PyObject *args)
5265{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005266 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005267
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005268 /* To round an integer m to the nearest 10**n (n positive), we make use of
5269 * the divmod_near operation, defined by:
5270 *
5271 * divmod_near(a, b) = (q, r)
5272 *
5273 * where q is the nearest integer to the quotient a / b (the
5274 * nearest even integer in the case of a tie) and r == a - q * b.
5275 * Hence q * b = a - r is the nearest multiple of b to a,
5276 * preferring even multiples in the case of a tie.
5277 *
5278 * So the nearest multiple of 10**n to m is:
5279 *
5280 * m - divmod_near(m, 10**n)[1].
5281 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5283 return NULL;
5284 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005285 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005286
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005287 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 if (ndigits == NULL)
5289 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005290
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005291 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 if (Py_SIZE(ndigits) >= 0) {
5293 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005294 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005296
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005297 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5298 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005300 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005302 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005303
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005304 result = PyLong_FromLong(10L);
5305 if (result == NULL) {
5306 Py_DECREF(ndigits);
5307 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005309
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005310 temp = long_pow(result, ndigits, Py_None);
5311 Py_DECREF(ndigits);
5312 Py_DECREF(result);
5313 result = temp;
5314 if (result == NULL)
5315 return NULL;
5316
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005317 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005318 Py_DECREF(result);
5319 result = temp;
5320 if (result == NULL)
5321 return NULL;
5322
5323 temp = long_sub((PyLongObject *)self,
5324 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5325 Py_DECREF(result);
5326 result = temp;
5327
5328 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005329}
5330
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005331/*[clinic input]
5332int.__sizeof__ -> Py_ssize_t
5333
5334Returns size in memory, in bytes.
5335[clinic start generated code]*/
5336
5337static Py_ssize_t
5338int___sizeof___impl(PyObject *self)
5339/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005342
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005343 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5344 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005345}
5346
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005347/*[clinic input]
5348int.bit_length
5349
5350Number of bits necessary to represent self in binary.
5351
5352>>> bin(37)
5353'0b100101'
5354>>> (37).bit_length()
53556
5356[clinic start generated code]*/
5357
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005358static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005359int_bit_length_impl(PyObject *self)
5360/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005363 Py_ssize_t ndigits;
5364 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005366
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005367 assert(self != NULL);
5368 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005369
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005370 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 if (ndigits == 0)
5372 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005373
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005374 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekasc5b79002020-01-16 15:09:19 +01005375 msd_bits = _Py_bit_length(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5378 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 /* expression above may overflow; use Python integers instead */
5381 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5382 if (result == NULL)
5383 return NULL;
5384 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5385 if (x == NULL)
5386 goto error;
5387 y = (PyLongObject *)long_mul(result, x);
5388 Py_DECREF(x);
5389 if (y == NULL)
5390 goto error;
5391 Py_DECREF(result);
5392 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5395 if (x == NULL)
5396 goto error;
5397 y = (PyLongObject *)long_add(result, x);
5398 Py_DECREF(x);
5399 if (y == NULL)
5400 goto error;
5401 Py_DECREF(result);
5402 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005405
Mark Dickinson22b20182010-05-10 21:27:53 +00005406 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 Py_DECREF(result);
5408 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005409}
5410
Christian Heimes53876d92008-04-19 00:31:39 +00005411
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005412/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005413int.as_integer_ratio
5414
5415Return integer ratio.
5416
5417Return a pair of integers, whose ratio is exactly equal to the original int
5418and with a positive denominator.
5419
5420>>> (10).as_integer_ratio()
5421(10, 1)
5422>>> (-10).as_integer_ratio()
5423(-10, 1)
5424>>> (0).as_integer_ratio()
5425(0, 1)
5426[clinic start generated code]*/
5427
5428static PyObject *
5429int_as_integer_ratio_impl(PyObject *self)
5430/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5431{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005432 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005433 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005434 if (numerator == NULL) {
5435 return NULL;
5436 }
5437 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5438 Py_DECREF(numerator);
5439 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005440}
5441
5442/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005443int.to_bytes
5444
5445 length: Py_ssize_t
5446 Length of bytes object to use. An OverflowError is raised if the
5447 integer is not representable with the given number of bytes.
5448 byteorder: unicode
5449 The byte order used to represent the integer. If byteorder is 'big',
5450 the most significant byte is at the beginning of the byte array. If
5451 byteorder is 'little', the most significant byte is at the end of the
5452 byte array. To request the native byte order of the host system, use
5453 `sys.byteorder' as the byte order value.
5454 *
5455 signed as is_signed: bool = False
5456 Determines whether two's complement is used to represent the integer.
5457 If signed is False and a negative integer is given, an OverflowError
5458 is raised.
5459
5460Return an array of bytes representing an integer.
5461[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005462
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005463static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005464int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5465 int is_signed)
5466/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005470
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005471 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005472 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005473 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005474 little_endian = 0;
5475 else {
5476 PyErr_SetString(PyExc_ValueError,
5477 "byteorder must be either 'little' or 'big'");
5478 return NULL;
5479 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 if (length < 0) {
5482 PyErr_SetString(PyExc_ValueError,
5483 "length argument must be non-negative");
5484 return NULL;
5485 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 bytes = PyBytes_FromStringAndSize(NULL, length);
5488 if (bytes == NULL)
5489 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005490
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005491 if (_PyLong_AsByteArray((PyLongObject *)self,
5492 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005493 length, little_endian, is_signed) < 0) {
5494 Py_DECREF(bytes);
5495 return NULL;
5496 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005499}
5500
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005501/*[clinic input]
5502@classmethod
5503int.from_bytes
5504
5505 bytes as bytes_obj: object
5506 Holds the array of bytes to convert. The argument must either
5507 support the buffer protocol or be an iterable object producing bytes.
5508 Bytes and bytearray are examples of built-in objects that support the
5509 buffer protocol.
5510 byteorder: unicode
5511 The byte order used to represent the integer. If byteorder is 'big',
5512 the most significant byte is at the beginning of the byte array. If
5513 byteorder is 'little', the most significant byte is at the end of the
5514 byte array. To request the native byte order of the host system, use
5515 `sys.byteorder' as the byte order value.
5516 *
5517 signed as is_signed: bool = False
5518 Indicates whether two's complement is used to represent the integer.
5519
5520Return the integer represented by the given array of bytes.
5521[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005522
5523static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005524int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5525 PyObject *byteorder, int is_signed)
5526/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005529 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005530
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005531 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005533 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 little_endian = 0;
5535 else {
5536 PyErr_SetString(PyExc_ValueError,
5537 "byteorder must be either 'little' or 'big'");
5538 return NULL;
5539 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005540
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005541 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 if (bytes == NULL)
5543 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 long_obj = _PyLong_FromByteArray(
5546 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5547 little_endian, is_signed);
5548 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005549
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005550 if (long_obj != NULL && type != &PyLong_Type) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005551 Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005555}
5556
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005557static PyObject *
5558long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5559{
5560 return long_long(self);
5561}
5562
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005563static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005564 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005566 INT_BIT_LENGTH_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005567 INT_TO_BYTES_METHODDEF
5568 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005569 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005570 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005572 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005573 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005574 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 "Ceiling of an Integral returns itself."},
5576 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5577 "Rounding an Integral returns itself.\n"
5578 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005579 INT___GETNEWARGS___METHODDEF
5580 INT___FORMAT___METHODDEF
5581 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005583};
5584
Guido van Rossumb43daf72007-08-01 18:08:08 +00005585static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005586 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005587 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005588 "the real part of a complex number",
5589 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005590 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005591 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005592 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005593 NULL},
5594 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005595 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005596 "the numerator of a rational number in lowest terms",
5597 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005598 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005599 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005600 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005601 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005602 {NULL} /* Sentinel */
5603};
5604
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005605PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005606"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005607int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005608\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005609Convert a number or string to an integer, or return 0 if no arguments\n\
5610are given. If x is a number, return x.__int__(). For floating point\n\
5611numbers, this truncates towards zero.\n\
5612\n\
5613If x is not a number or if base is given, then x must be a string,\n\
5614bytes, or bytearray instance representing an integer literal in the\n\
5615given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5616by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5617Base 0 means to interpret the base from the string as an integer literal.\n\
5618>>> int('0b100', base=0)\n\
56194");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005620
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005621static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005622 (binaryfunc)long_add, /*nb_add*/
5623 (binaryfunc)long_sub, /*nb_subtract*/
5624 (binaryfunc)long_mul, /*nb_multiply*/
5625 long_mod, /*nb_remainder*/
5626 long_divmod, /*nb_divmod*/
5627 long_pow, /*nb_power*/
5628 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005629 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005630 (unaryfunc)long_abs, /*tp_absolute*/
5631 (inquiry)long_bool, /*tp_bool*/
5632 (unaryfunc)long_invert, /*nb_invert*/
5633 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005634 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005635 long_and, /*nb_and*/
5636 long_xor, /*nb_xor*/
5637 long_or, /*nb_or*/
5638 long_long, /*nb_int*/
5639 0, /*nb_reserved*/
5640 long_float, /*nb_float*/
5641 0, /* nb_inplace_add */
5642 0, /* nb_inplace_subtract */
5643 0, /* nb_inplace_multiply */
5644 0, /* nb_inplace_remainder */
5645 0, /* nb_inplace_power */
5646 0, /* nb_inplace_lshift */
5647 0, /* nb_inplace_rshift */
5648 0, /* nb_inplace_and */
5649 0, /* nb_inplace_xor */
5650 0, /* nb_inplace_or */
5651 long_div, /* nb_floor_divide */
5652 long_true_divide, /* nb_true_divide */
5653 0, /* nb_inplace_floor_divide */
5654 0, /* nb_inplace_true_divide */
5655 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005656};
5657
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005658PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5660 "int", /* tp_name */
5661 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5662 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005663 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005664 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005665 0, /* tp_getattr */
5666 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005667 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 long_to_decimal_string, /* tp_repr */
5669 &long_as_number, /* tp_as_number */
5670 0, /* tp_as_sequence */
5671 0, /* tp_as_mapping */
5672 (hashfunc)long_hash, /* tp_hash */
5673 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005674 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005675 PyObject_GenericGetAttr, /* tp_getattro */
5676 0, /* tp_setattro */
5677 0, /* tp_as_buffer */
5678 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5679 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5680 long_doc, /* tp_doc */
5681 0, /* tp_traverse */
5682 0, /* tp_clear */
5683 long_richcompare, /* tp_richcompare */
5684 0, /* tp_weaklistoffset */
5685 0, /* tp_iter */
5686 0, /* tp_iternext */
5687 long_methods, /* tp_methods */
5688 0, /* tp_members */
5689 long_getset, /* tp_getset */
5690 0, /* tp_base */
5691 0, /* tp_dict */
5692 0, /* tp_descr_get */
5693 0, /* tp_descr_set */
5694 0, /* tp_dictoffset */
5695 0, /* tp_init */
5696 0, /* tp_alloc */
5697 long_new, /* tp_new */
5698 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005699};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005700
Mark Dickinsonbd792642009-03-18 20:06:12 +00005701static PyTypeObject Int_InfoType;
5702
5703PyDoc_STRVAR(int_info__doc__,
5704"sys.int_info\n\
5705\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005706A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005707internal representation of integers. The attributes are read only.");
5708
5709static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005711 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005713};
5714
5715static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 "sys.int_info", /* name */
5717 int_info__doc__, /* doc */
5718 int_info_fields, /* fields */
5719 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005720};
5721
5722PyObject *
5723PyLong_GetInfo(void)
5724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005725 PyObject* int_info;
5726 int field = 0;
5727 int_info = PyStructSequence_New(&Int_InfoType);
5728 if (int_info == NULL)
5729 return NULL;
5730 PyStructSequence_SET_ITEM(int_info, field++,
5731 PyLong_FromLong(PyLong_SHIFT));
5732 PyStructSequence_SET_ITEM(int_info, field++,
5733 PyLong_FromLong(sizeof(digit)));
5734 if (PyErr_Occurred()) {
5735 Py_CLEAR(int_info);
5736 return NULL;
5737 }
5738 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005739}
5740
Guido van Rossumddefaf32007-01-14 03:31:43 +00005741int
Victor Stinner630c8df2019-12-17 13:02:18 +01005742_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005743{
5744#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005745 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5746 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5747 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005748
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005749 PyLongObject *v = _PyLong_New(1);
5750 if (!v) {
5751 return -1;
5752 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005753
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005754 Py_SET_SIZE(v, size);
Victor Stinner12174a52014-08-15 23:17:38 +02005755 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005756
Victor Stinner630c8df2019-12-17 13:02:18 +01005757 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005759#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005760
Victor Stinner630c8df2019-12-17 13:02:18 +01005761 if (_Py_IsMainInterpreter(tstate)) {
5762 _PyLong_Zero = PyLong_FromLong(0);
5763 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005764 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005765 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005766
5767 _PyLong_One = PyLong_FromLong(1);
5768 if (_PyLong_One == NULL) {
5769 return 0;
5770 }
5771
5772 /* initialize int_info */
5773 if (Int_InfoType.tp_name == NULL) {
5774 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5775 return 0;
5776 }
5777 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005778 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005780 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005781}
5782
5783void
Victor Stinner630c8df2019-12-17 13:02:18 +01005784_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005785{
Victor Stinner630c8df2019-12-17 13:02:18 +01005786 if (_Py_IsMainInterpreter(tstate)) {
5787 Py_CLEAR(_PyLong_One);
5788 Py_CLEAR(_PyLong_Zero);
5789 }
5790
Guido van Rossumddefaf32007-01-14 03:31:43 +00005791#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005792 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005793 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005795#endif
5796}