blob: 0ff0e80cd4269686b0330dcaafc010d3c266a797 [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{
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500419 /* Try to get out cheap if this fits in a long. When a finite value of real
420 * floating type is converted to an integer type, the value is truncated
421 * toward zero. If the value of the integral part cannot be represented by
422 * the integer type, the behavior is undefined. Thus, we must check that
423 * value is in range (LONG_MIN - 1, LONG_MAX + 1). If a long has more bits
424 * of precision than a double, casting LONG_MIN - 1 to double may yield an
425 * approximation, but LONG_MAX + 1 is a power of two and can be represented
426 * as double exactly (assuming FLT_RADIX is 2 or 16), so for simplicity
427 * check against [-(LONG_MAX + 1), LONG_MAX + 1).
428 */
429 const double int_max = (unsigned long)LONG_MAX + 1;
430 if (-int_max < dval && dval < int_max) {
431 return PyLong_FromLong((long)dval);
432 }
433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 PyLongObject *v;
435 double frac;
436 int i, ndig, expo, neg;
437 neg = 0;
438 if (Py_IS_INFINITY(dval)) {
439 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000440 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 return NULL;
442 }
443 if (Py_IS_NAN(dval)) {
444 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000445 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 return NULL;
447 }
448 if (dval < 0.0) {
449 neg = 1;
450 dval = -dval;
451 }
452 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
Sergey Fedoseev86a93fd2020-05-10 14:15:57 +0500453 assert(expo > 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
455 v = _PyLong_New(ndig);
456 if (v == NULL)
457 return NULL;
458 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
459 for (i = ndig; --i >= 0; ) {
460 digit bits = (digit)frac;
461 v->ob_digit[i] = bits;
462 frac = frac - (double)bits;
463 frac = ldexp(frac, PyLong_SHIFT);
464 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100465 if (neg) {
466 Py_SET_SIZE(v, -(Py_SIZE(v)));
467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000469}
470
Thomas Wouters89f507f2006-12-13 04:49:30 +0000471/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
472 * anything about what happens when a signed integer operation overflows,
473 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700474 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000475 * (unsigned long)LONG_MAX, and for the smallest negative signed long
476 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
477 * However, some other compilers warn about applying unary minus to an
478 * unsigned operand. Hence the weird "0-".
479 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
481#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000482
Serhiy Storchaka95949422013-08-27 19:40:23 +0300483/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100484 method.
485
486 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
487 the result. Otherwise *overflow is 0.
488
489 For other errors (e.g., TypeError), return -1 and set an error condition.
490 In this case *overflow will be 0.
491*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000492
493long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000494PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200497 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 unsigned long x, prev;
499 long res;
500 Py_ssize_t i;
501 int sign;
502 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 *overflow = 0;
505 if (vv == NULL) {
506 PyErr_BadInternalCall();
507 return -1;
508 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000509
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200510 if (PyLong_Check(vv)) {
511 v = (PyLongObject *)vv;
512 }
513 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200514 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200515 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return -1;
517 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 switch (i) {
524 case -1:
525 res = -(sdigit)v->ob_digit[0];
526 break;
527 case 0:
528 res = 0;
529 break;
530 case 1:
531 res = v->ob_digit[0];
532 break;
533 default:
534 sign = 1;
535 x = 0;
536 if (i < 0) {
537 sign = -1;
538 i = -(i);
539 }
540 while (--i >= 0) {
541 prev = x;
542 x = (x << PyLong_SHIFT) | v->ob_digit[i];
543 if ((x >> PyLong_SHIFT) != prev) {
544 *overflow = sign;
545 goto exit;
546 }
547 }
548 /* Haven't lost any bits, but casting to long requires extra
549 * care (see comment above).
550 */
551 if (x <= (unsigned long)LONG_MAX) {
552 res = (long)x * sign;
553 }
554 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
555 res = LONG_MIN;
556 }
557 else {
558 *overflow = sign;
559 /* res is already set to -1 */
560 }
561 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000562 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200564 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 }
566 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000567}
568
Serhiy Storchaka95949422013-08-27 19:40:23 +0300569/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100570 method. Return -1 and set an error if overflow occurs. */
571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000573PyLong_AsLong(PyObject *obj)
574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 int overflow;
576 long result = PyLong_AsLongAndOverflow(obj, &overflow);
577 if (overflow) {
578 /* XXX: could be cute and give a different
579 message for overflow == -1 */
580 PyErr_SetString(PyExc_OverflowError,
581 "Python int too large to convert to C long");
582 }
583 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000584}
585
Serhiy Storchaka95949422013-08-27 19:40:23 +0300586/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200587 method. Return -1 and set an error if overflow occurs. */
588
589int
590_PyLong_AsInt(PyObject *obj)
591{
592 int overflow;
593 long result = PyLong_AsLongAndOverflow(obj, &overflow);
594 if (overflow || result > INT_MAX || result < INT_MIN) {
595 /* XXX: could be cute and give a different
596 message for overflow == -1 */
597 PyErr_SetString(PyExc_OverflowError,
598 "Python int too large to convert to C int");
599 return -1;
600 }
601 return (int)result;
602}
603
Serhiy Storchaka95949422013-08-27 19:40:23 +0300604/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000605 Returns -1 and sets an error condition if overflow occurs. */
606
607Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000608PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200609 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 size_t x, prev;
611 Py_ssize_t i;
612 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (vv == NULL) {
615 PyErr_BadInternalCall();
616 return -1;
617 }
618 if (!PyLong_Check(vv)) {
619 PyErr_SetString(PyExc_TypeError, "an integer is required");
620 return -1;
621 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 v = (PyLongObject *)vv;
624 i = Py_SIZE(v);
625 switch (i) {
626 case -1: return -(sdigit)v->ob_digit[0];
627 case 0: return 0;
628 case 1: return v->ob_digit[0];
629 }
630 sign = 1;
631 x = 0;
632 if (i < 0) {
633 sign = -1;
634 i = -(i);
635 }
636 while (--i >= 0) {
637 prev = x;
638 x = (x << PyLong_SHIFT) | v->ob_digit[i];
639 if ((x >> PyLong_SHIFT) != prev)
640 goto overflow;
641 }
642 /* Haven't lost any bits, but casting to a signed type requires
643 * extra care (see comment above).
644 */
645 if (x <= (size_t)PY_SSIZE_T_MAX) {
646 return (Py_ssize_t)x * sign;
647 }
648 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
649 return PY_SSIZE_T_MIN;
650 }
651 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000652
Mark Dickinson22b20182010-05-10 21:27:53 +0000653 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyErr_SetString(PyExc_OverflowError,
655 "Python int too large to convert to C ssize_t");
656 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000657}
658
Serhiy Storchaka95949422013-08-27 19:40:23 +0300659/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000660 Returns -1 and sets an error condition if overflow occurs. */
661
662unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000663PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000664{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200665 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 unsigned long x, prev;
667 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (vv == NULL) {
670 PyErr_BadInternalCall();
671 return (unsigned long)-1;
672 }
673 if (!PyLong_Check(vv)) {
674 PyErr_SetString(PyExc_TypeError, "an integer is required");
675 return (unsigned long)-1;
676 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 v = (PyLongObject *)vv;
679 i = Py_SIZE(v);
680 x = 0;
681 if (i < 0) {
682 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000683 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 return (unsigned long) -1;
685 }
686 switch (i) {
687 case 0: return 0;
688 case 1: return v->ob_digit[0];
689 }
690 while (--i >= 0) {
691 prev = x;
692 x = (x << PyLong_SHIFT) | v->ob_digit[i];
693 if ((x >> PyLong_SHIFT) != prev) {
694 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100695 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000696 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 return (unsigned long) -1;
698 }
699 }
700 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000701}
702
Serhiy Storchaka95949422013-08-27 19:40:23 +0300703/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200704 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000705
706size_t
707PyLong_AsSize_t(PyObject *vv)
708{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200709 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 size_t x, prev;
711 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if (vv == NULL) {
714 PyErr_BadInternalCall();
715 return (size_t) -1;
716 }
717 if (!PyLong_Check(vv)) {
718 PyErr_SetString(PyExc_TypeError, "an integer is required");
719 return (size_t)-1;
720 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 v = (PyLongObject *)vv;
723 i = Py_SIZE(v);
724 x = 0;
725 if (i < 0) {
726 PyErr_SetString(PyExc_OverflowError,
727 "can't convert negative value to size_t");
728 return (size_t) -1;
729 }
730 switch (i) {
731 case 0: return 0;
732 case 1: return v->ob_digit[0];
733 }
734 while (--i >= 0) {
735 prev = x;
736 x = (x << PyLong_SHIFT) | v->ob_digit[i];
737 if ((x >> PyLong_SHIFT) != prev) {
738 PyErr_SetString(PyExc_OverflowError,
739 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200740 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 }
742 }
743 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000744}
745
Serhiy Storchaka95949422013-08-27 19:40:23 +0300746/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000747 Returns -1 and sets an error condition if an error occurs. */
748
Guido van Rossumddefaf32007-01-14 03:31:43 +0000749static unsigned long
750_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000751{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200752 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 unsigned long x;
754 Py_ssize_t i;
755 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (vv == NULL || !PyLong_Check(vv)) {
758 PyErr_BadInternalCall();
759 return (unsigned long) -1;
760 }
761 v = (PyLongObject *)vv;
762 i = Py_SIZE(v);
763 switch (i) {
764 case 0: return 0;
765 case 1: return v->ob_digit[0];
766 }
767 sign = 1;
768 x = 0;
769 if (i < 0) {
770 sign = -1;
771 i = -i;
772 }
773 while (--i >= 0) {
774 x = (x << PyLong_SHIFT) | v->ob_digit[i];
775 }
776 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000777}
778
Guido van Rossumddefaf32007-01-14 03:31:43 +0000779unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200780PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyLongObject *lo;
783 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000784
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200785 if (op == NULL) {
786 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 return (unsigned long)-1;
788 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000789
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200790 if (PyLong_Check(op)) {
791 return _PyLong_AsUnsignedLongMask(op);
792 }
793
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200794 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if (lo == NULL)
796 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200797
798 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
799 Py_DECREF(lo);
800 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000801}
802
Tim Peters5b8132f2003-01-31 15:52:05 +0000803int
804_PyLong_Sign(PyObject *vv)
805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 assert(v != NULL);
809 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000812}
813
Tim Petersbaefd9e2003-01-28 20:37:45 +0000814size_t
815_PyLong_NumBits(PyObject *vv)
816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyLongObject *v = (PyLongObject *)vv;
818 size_t result = 0;
819 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200820 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 assert(v != NULL);
823 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200824 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
826 if (ndigits > 0) {
827 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700828 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100830 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Niklas Fiekasc5b79002020-01-16 15:09:19 +0100831 msd_bits = _Py_bit_length(msd);
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200832 if (SIZE_MAX - msd_bits < result)
833 goto Overflow;
834 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 }
836 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000837
Mark Dickinson22b20182010-05-10 21:27:53 +0000838 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
840 "to express in a platform size_t");
841 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000842}
843
Tim Peters2a9b3672001-06-11 21:23:58 +0000844PyObject *
845_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000847{
Mark Dickinson22b20182010-05-10 21:27:53 +0000848 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 int incr; /* direction to move pstartbyte */
850 const unsigned char* pendbyte; /* MSB of bytes */
851 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300852 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyLongObject* v; /* result */
854 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (n == 0)
857 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 if (little_endian) {
860 pstartbyte = bytes;
861 pendbyte = bytes + n - 1;
862 incr = 1;
863 }
864 else {
865 pstartbyte = bytes + n - 1;
866 pendbyte = bytes;
867 incr = -1;
868 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (is_signed)
871 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200874 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 is positive, and leading 0xff bytes if negative. */
876 {
877 size_t i;
878 const unsigned char* p = pendbyte;
879 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000880 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000883 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 break;
885 }
886 numsignificantbytes = n - i;
887 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
888 actually has 2 significant bytes. OTOH, 0xff0001 ==
889 -0x00ffff, so we wouldn't *need* to bump it there; but we
890 do for 0xffff = -0x0001. To be safe without bothering to
891 check every case, bump it regardless. */
892 if (is_signed && numsignificantbytes < n)
893 ++numsignificantbytes;
894 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000895
Serhiy Storchaka95949422013-08-27 19:40:23 +0300896 /* How many Python int digits do we need? We have
897 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
899 /* catch overflow before it happens */
900 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
901 PyErr_SetString(PyExc_OverflowError,
902 "byte array too long to convert to int");
903 return NULL;
904 }
905 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
906 v = _PyLong_New(ndigits);
907 if (v == NULL)
908 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* Copy the bits over. The tricky parts are computing 2's-comp on
911 the fly for signed numbers, and dealing with the mismatch between
912 8-bit bytes and (probably) 15-bit Python digits.*/
913 {
914 size_t i;
915 twodigits carry = 1; /* for 2's-comp calculation */
916 twodigits accum = 0; /* sliding register */
917 unsigned int accumbits = 0; /* number of bits in accum */
918 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
921 twodigits thisbyte = *p;
922 /* Compute correction for 2's comp, if needed. */
923 if (is_signed) {
924 thisbyte = (0xff ^ thisbyte) + carry;
925 carry = thisbyte >> 8;
926 thisbyte &= 0xff;
927 }
928 /* Because we're going LSB to MSB, thisbyte is
929 more significant than what's already in accum,
930 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200931 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 accumbits += 8;
933 if (accumbits >= PyLong_SHIFT) {
934 /* There's enough to fill a Python digit. */
935 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000936 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 ++idigit;
938 accum >>= PyLong_SHIFT;
939 accumbits -= PyLong_SHIFT;
940 assert(accumbits < PyLong_SHIFT);
941 }
942 }
943 assert(accumbits < PyLong_SHIFT);
944 if (accumbits) {
945 assert(idigit < ndigits);
946 v->ob_digit[idigit] = (digit)accum;
947 ++idigit;
948 }
949 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000950
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100951 Py_SET_SIZE(v, is_signed ? -idigit : idigit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000953}
954
955int
956_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 unsigned char* bytes, size_t n,
958 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000961 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000963 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
965 digit carry; /* for computing 2's-comp */
966 size_t j; /* # bytes filled */
967 unsigned char* p; /* pointer to next byte in bytes */
968 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 if (Py_SIZE(v) < 0) {
973 ndigits = -(Py_SIZE(v));
974 if (!is_signed) {
975 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000976 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 return -1;
978 }
979 do_twos_comp = 1;
980 }
981 else {
982 ndigits = Py_SIZE(v);
983 do_twos_comp = 0;
984 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (little_endian) {
987 p = bytes;
988 pincr = 1;
989 }
990 else {
991 p = bytes + n - 1;
992 pincr = -1;
993 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 /* Copy over all the Python digits.
996 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300997 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 normalized. */
999 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
1000 j = 0;
1001 accum = 0;
1002 accumbits = 0;
1003 carry = do_twos_comp ? 1 : 0;
1004 for (i = 0; i < ndigits; ++i) {
1005 digit thisdigit = v->ob_digit[i];
1006 if (do_twos_comp) {
1007 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
1008 carry = thisdigit >> PyLong_SHIFT;
1009 thisdigit &= PyLong_MASK;
1010 }
1011 /* Because we're going LSB to MSB, thisdigit is more
1012 significant than what's already in accum, so needs to be
1013 prepended to accum. */
1014 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 /* The most-significant digit may be (probably is) at least
1017 partly empty. */
1018 if (i == ndigits - 1) {
1019 /* Count # of sign bits -- they needn't be stored,
1020 * although for signed conversion we need later to
1021 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +00001022 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 while (s != 0) {
1024 s >>= 1;
1025 accumbits++;
1026 }
1027 }
1028 else
1029 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 /* Store as many bytes as possible. */
1032 while (accumbits >= 8) {
1033 if (j >= n)
1034 goto Overflow;
1035 ++j;
1036 *p = (unsigned char)(accum & 0xff);
1037 p += pincr;
1038 accumbits -= 8;
1039 accum >>= 8;
1040 }
1041 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 /* Store the straggler (if any). */
1044 assert(accumbits < 8);
1045 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1046 if (accumbits > 0) {
1047 if (j >= n)
1048 goto Overflow;
1049 ++j;
1050 if (do_twos_comp) {
1051 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +03001052 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 infinite supply of sign bits). */
1054 accum |= (~(twodigits)0) << accumbits;
1055 }
1056 *p = (unsigned char)(accum & 0xff);
1057 p += pincr;
1058 }
1059 else if (j == n && n > 0 && is_signed) {
1060 /* The main loop filled the byte array exactly, so the code
1061 just above didn't get to ensure there's a sign bit, and the
1062 loop below wouldn't add one either. Make sure a sign bit
1063 exists. */
1064 unsigned char msb = *(p - pincr);
1065 int sign_bit_set = msb >= 0x80;
1066 assert(accumbits == 0);
1067 if (sign_bit_set == do_twos_comp)
1068 return 0;
1069 else
1070 goto Overflow;
1071 }
Tim Peters05607ad2001-06-13 21:01:27 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 /* Fill remaining bytes with copies of the sign bit. */
1074 {
1075 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1076 for ( ; j < n; ++j, p += pincr)
1077 *p = signbyte;
1078 }
Tim Peters05607ad2001-06-13 21:01:27 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001081
Mark Dickinson22b20182010-05-10 21:27:53 +00001082 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1084 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001085
Tim Peters2a9b3672001-06-11 21:23:58 +00001086}
1087
Serhiy Storchaka95949422013-08-27 19:40:23 +03001088/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001089
1090PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001091PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001092{
Mark Dickinson91044792012-10-18 19:21:43 +01001093#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001094 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001095#else
1096
Tim Peters70128a12001-06-16 08:48:40 +00001097#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001098# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001099#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001100 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001101#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001102
Guido van Rossum78694d91998-09-18 14:14:13 +00001103}
1104
Serhiy Storchaka95949422013-08-27 19:40:23 +03001105/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001106
1107void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001108PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001109{
Tim Peters70128a12001-06-16 08:48:40 +00001110#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1114 x = PyLong_AsLong(vv);
1115 else
1116 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001117#else
Tim Peters70128a12001-06-16 08:48:40 +00001118
Tim Peters70128a12001-06-16 08:48:40 +00001119#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001120# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001121#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001122 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1125 x = PyLong_AsLongLong(vv);
1126 else
1127 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001128
1129#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (x == -1 && PyErr_Occurred())
1132 return NULL;
1133 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001134}
1135
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001136/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001137 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001138 */
1139
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001140#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001141
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001142/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001143
1144PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001145PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001148 unsigned long long abs_ival;
1149 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 int ndigits = 0;
1151 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001152
animalize6b519982019-09-06 14:00:56 +08001153 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001154 return get_small_int((sdigit)ival);
1155 }
1156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (ival < 0) {
1158 /* avoid signed overflow on negation; see comments
1159 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001160 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 negative = 1;
1162 }
1163 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001164 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 /* Count the number of Python digits.
1168 We used to pick 5 ("big enough for anything"), but that's a
1169 waste of time and space given that 5*15 = 75 bits are rarely
1170 needed. */
1171 t = abs_ival;
1172 while (t) {
1173 ++ndigits;
1174 t >>= PyLong_SHIFT;
1175 }
1176 v = _PyLong_New(ndigits);
1177 if (v != NULL) {
1178 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001179 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 t = abs_ival;
1181 while (t) {
1182 *p++ = (digit)(t & PyLong_MASK);
1183 t >>= PyLong_SHIFT;
1184 }
1185 }
1186 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001187}
1188
Serhiy Storchaka95949422013-08-27 19:40:23 +03001189/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001190
1191PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001192PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyLongObject *v;
1195 size_t abs_ival;
1196 size_t t; /* unsigned so >> doesn't propagate sign bit */
1197 int ndigits = 0;
1198 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001199
animalize6b519982019-09-06 14:00:56 +08001200 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001201 return get_small_int((sdigit)ival);
1202 }
1203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 if (ival < 0) {
1205 /* avoid signed overflow when ival = SIZE_T_MIN */
1206 abs_ival = (size_t)(-1-ival)+1;
1207 negative = 1;
1208 }
1209 else {
1210 abs_ival = (size_t)ival;
1211 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 /* Count the number of Python digits. */
1214 t = abs_ival;
1215 while (t) {
1216 ++ndigits;
1217 t >>= PyLong_SHIFT;
1218 }
1219 v = _PyLong_New(ndigits);
1220 if (v != NULL) {
1221 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001222 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 t = abs_ival;
1224 while (t) {
1225 *p++ = (digit)(t & PyLong_MASK);
1226 t >>= PyLong_SHIFT;
1227 }
1228 }
1229 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001230}
1231
Serhiy Storchaka95949422013-08-27 19:40:23 +03001232/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001233 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001234
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001235long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001236PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001239 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001241 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (vv == NULL) {
1244 PyErr_BadInternalCall();
1245 return -1;
1246 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001247
1248 if (PyLong_Check(vv)) {
1249 v = (PyLongObject *)vv;
1250 }
1251 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001252 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001253 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001255 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001257
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001258 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001260 case -1:
1261 bytes = -(sdigit)v->ob_digit[0];
1262 break;
1263 case 0:
1264 bytes = 0;
1265 break;
1266 case 1:
1267 bytes = v->ob_digit[0];
1268 break;
1269 default:
1270 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001271 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001273 if (do_decref) {
1274 Py_DECREF(v);
1275 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001276
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001277 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001279 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 else
1281 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001282}
1283
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001284/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001285 Return -1 and set an error if overflow occurs. */
1286
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001287unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001288PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001291 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001293
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001294 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001296 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001298 if (!PyLong_Check(vv)) {
1299 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001300 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001301 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 v = (PyLongObject*)vv;
1304 switch(Py_SIZE(v)) {
1305 case 0: return 0;
1306 case 1: return v->ob_digit[0];
1307 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001308
Mark Dickinson22b20182010-05-10 21:27:53 +00001309 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001310 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001311
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001312 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001314 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 else
1316 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001317}
Tim Petersd1a7da62001-06-13 00:35:57 +00001318
Serhiy Storchaka95949422013-08-27 19:40:23 +03001319/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001320 Returns -1 and sets an error condition if an error occurs. */
1321
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001322static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001323_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001324{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001325 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001326 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 Py_ssize_t i;
1328 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (vv == NULL || !PyLong_Check(vv)) {
1331 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001332 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 }
1334 v = (PyLongObject *)vv;
1335 switch(Py_SIZE(v)) {
1336 case 0: return 0;
1337 case 1: return v->ob_digit[0];
1338 }
1339 i = Py_SIZE(v);
1340 sign = 1;
1341 x = 0;
1342 if (i < 0) {
1343 sign = -1;
1344 i = -i;
1345 }
1346 while (--i >= 0) {
1347 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1348 }
1349 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001350}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001351
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001352unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001353PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001356 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001357
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001358 if (op == NULL) {
1359 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001360 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001362
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001363 if (PyLong_Check(op)) {
1364 return _PyLong_AsUnsignedLongLongMask(op);
1365 }
1366
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001367 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001369 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001370
1371 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1372 Py_DECREF(lo);
1373 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001374}
Tim Petersd1a7da62001-06-13 00:35:57 +00001375
Serhiy Storchaka95949422013-08-27 19:40:23 +03001376/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001377 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001378
Mark Dickinson8d48b432011-10-23 20:47:14 +01001379 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1380 the result. Otherwise *overflow is 0.
1381
1382 For other errors (e.g., TypeError), return -1 and set an error condition.
1383 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001384*/
1385
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001386long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001387PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001390 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001391 unsigned long long x, prev;
1392 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 Py_ssize_t i;
1394 int sign;
1395 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 *overflow = 0;
1398 if (vv == NULL) {
1399 PyErr_BadInternalCall();
1400 return -1;
1401 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001402
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001403 if (PyLong_Check(vv)) {
1404 v = (PyLongObject *)vv;
1405 }
1406 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001407 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001408 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 return -1;
1410 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 switch (i) {
1417 case -1:
1418 res = -(sdigit)v->ob_digit[0];
1419 break;
1420 case 0:
1421 res = 0;
1422 break;
1423 case 1:
1424 res = v->ob_digit[0];
1425 break;
1426 default:
1427 sign = 1;
1428 x = 0;
1429 if (i < 0) {
1430 sign = -1;
1431 i = -(i);
1432 }
1433 while (--i >= 0) {
1434 prev = x;
1435 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1436 if ((x >> PyLong_SHIFT) != prev) {
1437 *overflow = sign;
1438 goto exit;
1439 }
1440 }
1441 /* Haven't lost any bits, but casting to long requires extra
1442 * care (see comment above).
1443 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001444 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001445 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 }
1447 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001448 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 }
1450 else {
1451 *overflow = sign;
1452 /* res is already set to -1 */
1453 }
1454 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001455 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001457 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 }
1459 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001460}
1461
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001462int
1463_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1464{
1465 unsigned long uval;
1466
1467 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1468 PyErr_SetString(PyExc_ValueError, "value must be positive");
1469 return 0;
1470 }
1471 uval = PyLong_AsUnsignedLong(obj);
1472 if (uval == (unsigned long)-1 && PyErr_Occurred())
1473 return 0;
1474 if (uval > USHRT_MAX) {
1475 PyErr_SetString(PyExc_OverflowError,
1476 "Python int too large for C unsigned short");
1477 return 0;
1478 }
1479
1480 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1481 return 1;
1482}
1483
1484int
1485_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1486{
1487 unsigned long uval;
1488
1489 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1490 PyErr_SetString(PyExc_ValueError, "value must be positive");
1491 return 0;
1492 }
1493 uval = PyLong_AsUnsignedLong(obj);
1494 if (uval == (unsigned long)-1 && PyErr_Occurred())
1495 return 0;
1496 if (uval > UINT_MAX) {
1497 PyErr_SetString(PyExc_OverflowError,
1498 "Python int too large for C unsigned int");
1499 return 0;
1500 }
1501
1502 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1503 return 1;
1504}
1505
1506int
1507_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1508{
1509 unsigned long uval;
1510
1511 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1512 PyErr_SetString(PyExc_ValueError, "value must be positive");
1513 return 0;
1514 }
1515 uval = PyLong_AsUnsignedLong(obj);
1516 if (uval == (unsigned long)-1 && PyErr_Occurred())
1517 return 0;
1518
1519 *(unsigned long *)ptr = uval;
1520 return 1;
1521}
1522
1523int
1524_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1525{
1526 unsigned long long uval;
1527
1528 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1529 PyErr_SetString(PyExc_ValueError, "value must be positive");
1530 return 0;
1531 }
1532 uval = PyLong_AsUnsignedLongLong(obj);
1533 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1534 return 0;
1535
1536 *(unsigned long long *)ptr = uval;
1537 return 1;
1538}
1539
1540int
1541_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1542{
1543 size_t uval;
1544
1545 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1546 PyErr_SetString(PyExc_ValueError, "value must be positive");
1547 return 0;
1548 }
1549 uval = PyLong_AsSize_t(obj);
1550 if (uval == (size_t)-1 && PyErr_Occurred())
1551 return 0;
1552
1553 *(size_t *)ptr = uval;
1554 return 1;
1555}
1556
1557
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001558#define CHECK_BINOP(v,w) \
1559 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001560 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1561 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001562 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001563
Tim Peters877a2122002-08-12 05:09:36 +00001564/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1565 * is modified in place, by adding y to it. Carries are propagated as far as
1566 * x[m-1], and the remaining carry (0 or 1) is returned.
1567 */
1568static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001569v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 Py_ssize_t i;
1572 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 assert(m >= n);
1575 for (i = 0; i < n; ++i) {
1576 carry += x[i] + y[i];
1577 x[i] = carry & PyLong_MASK;
1578 carry >>= PyLong_SHIFT;
1579 assert((carry & 1) == carry);
1580 }
1581 for (; carry && i < m; ++i) {
1582 carry += x[i];
1583 x[i] = carry & PyLong_MASK;
1584 carry >>= PyLong_SHIFT;
1585 assert((carry & 1) == carry);
1586 }
1587 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001588}
1589
1590/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1591 * is modified in place, by subtracting y from it. Borrows are propagated as
1592 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1593 */
1594static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001595v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 Py_ssize_t i;
1598 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 assert(m >= n);
1601 for (i = 0; i < n; ++i) {
1602 borrow = x[i] - y[i] - borrow;
1603 x[i] = borrow & PyLong_MASK;
1604 borrow >>= PyLong_SHIFT;
1605 borrow &= 1; /* keep only 1 sign bit */
1606 }
1607 for (; borrow && i < m; ++i) {
1608 borrow = x[i] - borrow;
1609 x[i] = borrow & PyLong_MASK;
1610 borrow >>= PyLong_SHIFT;
1611 borrow &= 1;
1612 }
1613 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001614}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001615
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001616/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1617 * result in z[0:m], and return the d bits shifted out of the top.
1618 */
1619static digit
1620v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 Py_ssize_t i;
1623 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 assert(0 <= d && d < PyLong_SHIFT);
1626 for (i=0; i < m; i++) {
1627 twodigits acc = (twodigits)a[i] << d | carry;
1628 z[i] = (digit)acc & PyLong_MASK;
1629 carry = (digit)(acc >> PyLong_SHIFT);
1630 }
1631 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001632}
1633
1634/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1635 * result in z[0:m], and return the d bits shifted out of the bottom.
1636 */
1637static digit
1638v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 Py_ssize_t i;
1641 digit carry = 0;
1642 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 assert(0 <= d && d < PyLong_SHIFT);
1645 for (i=m; i-- > 0;) {
1646 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1647 carry = (digit)acc & mask;
1648 z[i] = (digit)(acc >> d);
1649 }
1650 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001651}
1652
Tim Peters212e6142001-07-14 12:23:19 +00001653/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1654 in pout, and returning the remainder. pin and pout point at the LSD.
1655 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001656 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001657 immutable. */
1658
1659static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001660inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 assert(n > 0 && n <= PyLong_MASK);
1665 pin += size;
1666 pout += size;
1667 while (--size >= 0) {
1668 digit hi;
1669 rem = (rem << PyLong_SHIFT) | *--pin;
1670 *--pout = hi = (digit)(rem / n);
1671 rem -= (twodigits)hi * n;
1672 }
1673 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001674}
1675
Serhiy Storchaka95949422013-08-27 19:40:23 +03001676/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001677 (as function result) and the remainder (through *prem).
1678 The sign of a is ignored; n should not be zero. */
1679
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001680static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001681divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001682{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001683 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 assert(n > 0 && n <= PyLong_MASK);
1687 z = _PyLong_New(size);
1688 if (z == NULL)
1689 return NULL;
1690 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1691 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001692}
1693
Serhiy Storchaka95949422013-08-27 19:40:23 +03001694/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001695 string. (Return value is non-shared so that callers can modify the
1696 returned value if necessary.) */
1697
Victor Stinnerd3f08822012-05-29 12:57:52 +02001698static int
1699long_to_decimal_string_internal(PyObject *aa,
1700 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001701 _PyUnicodeWriter *writer,
1702 _PyBytesWriter *bytes_writer,
1703 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001706 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 Py_ssize_t size, strlen, size_a, i, j;
1708 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001710 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001711 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 a = (PyLongObject *)aa;
1714 if (a == NULL || !PyLong_Check(a)) {
1715 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001716 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001718 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 /* quick and dirty upper bound for the number of digits
1722 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 But log2(a) < size_a * PyLong_SHIFT, and
1727 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001728 > 3.3 * _PyLong_DECIMAL_SHIFT
1729
1730 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1731 size_a + size_a / d < size_a + size_a / floor(d),
1732 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1733 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001735 d = (33 * _PyLong_DECIMAL_SHIFT) /
1736 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1737 assert(size_a < PY_SSIZE_T_MAX/2);
1738 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 scratch = _PyLong_New(size);
1740 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001741 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 /* convert array of base _PyLong_BASE digits in pin to an array of
1744 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1745 Volume 2 (3rd edn), section 4.4, Method 1b). */
1746 pin = a->ob_digit;
1747 pout = scratch->ob_digit;
1748 size = 0;
1749 for (i = size_a; --i >= 0; ) {
1750 digit hi = pin[i];
1751 for (j = 0; j < size; j++) {
1752 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1753 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1754 pout[j] = (digit)(z - (twodigits)hi *
1755 _PyLong_DECIMAL_BASE);
1756 }
1757 while (hi) {
1758 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1759 hi /= _PyLong_DECIMAL_BASE;
1760 }
1761 /* check for keyboard interrupt */
1762 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001763 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001764 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001765 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 }
1767 /* pout should have at least one digit, so that the case when a = 0
1768 works correctly */
1769 if (size == 0)
1770 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 /* calculate exact length of output string, and allocate */
1773 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1774 tenpow = 10;
1775 rem = pout[size-1];
1776 while (rem >= tenpow) {
1777 tenpow *= 10;
1778 strlen++;
1779 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001780 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001781 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1782 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001783 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001784 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001785 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001787 else if (bytes_writer) {
1788 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1789 if (*bytes_str == NULL) {
1790 Py_DECREF(scratch);
1791 return -1;
1792 }
1793 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001794 else {
1795 str = PyUnicode_New(strlen, '9');
1796 if (str == NULL) {
1797 Py_DECREF(scratch);
1798 return -1;
1799 }
1800 kind = PyUnicode_KIND(str);
1801 }
1802
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001803#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001804 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001805 /* pout[0] through pout[size-2] contribute exactly \
1806 _PyLong_DECIMAL_SHIFT digits each */ \
1807 for (i=0; i < size - 1; i++) { \
1808 rem = pout[i]; \
1809 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1810 *--p = '0' + rem % 10; \
1811 rem /= 10; \
1812 } \
1813 } \
1814 /* pout[size-1]: always produce at least one decimal digit */ \
1815 rem = pout[i]; \
1816 do { \
1817 *--p = '0' + rem % 10; \
1818 rem /= 10; \
1819 } while (rem != 0); \
1820 \
1821 /* and sign */ \
1822 if (negative) \
1823 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001824 } while (0)
1825
1826#define WRITE_UNICODE_DIGITS(TYPE) \
1827 do { \
1828 if (writer) \
1829 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1830 else \
1831 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1832 \
1833 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001834 \
1835 /* check we've counted correctly */ \
1836 if (writer) \
1837 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1838 else \
1839 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1840 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001843 if (bytes_writer) {
1844 char *p = *bytes_str + strlen;
1845 WRITE_DIGITS(p);
1846 assert(p == *bytes_str);
1847 }
1848 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001849 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001850 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001852 else if (kind == PyUnicode_2BYTE_KIND) {
1853 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001854 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001855 }
1856 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001857 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001858 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001859 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001860 }
1861#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001862#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001865 if (writer) {
1866 writer->pos += strlen;
1867 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001868 else if (bytes_writer) {
1869 (*bytes_str) += strlen;
1870 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001871 else {
1872 assert(_PyUnicode_CheckConsistency(str, 1));
1873 *p_output = (PyObject *)str;
1874 }
1875 return 0;
1876}
1877
1878static PyObject *
1879long_to_decimal_string(PyObject *aa)
1880{
1881 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001882 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001883 return NULL;
1884 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001885}
1886
Serhiy Storchaka95949422013-08-27 19:40:23 +03001887/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001888 which should be one of 2, 8 or 16. Return a string object.
1889 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1890 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001891
Victor Stinnerd3f08822012-05-29 12:57:52 +02001892static int
1893long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001894 PyObject **p_output, _PyUnicodeWriter *writer,
1895 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001896{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001897 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001898 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001899 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001901 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001902 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001904
Victor Stinnerd3f08822012-05-29 12:57:52 +02001905 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 if (a == NULL || !PyLong_Check(a)) {
1907 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001908 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001910 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001911 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 /* Compute a rough upper bound for the length of the string */
1914 switch (base) {
1915 case 16:
1916 bits = 4;
1917 break;
1918 case 8:
1919 bits = 3;
1920 break;
1921 case 2:
1922 bits = 1;
1923 break;
1924 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001925 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001927
Mark Dickinsone2846542012-04-20 21:21:24 +01001928 /* Compute exact length 'sz' of output string. */
1929 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001930 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001931 }
1932 else {
1933 Py_ssize_t size_a_in_bits;
1934 /* Ensure overflow doesn't occur during computation of sz. */
1935 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1936 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001937 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001938 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001939 }
1940 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001941 _Py_bit_length(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001942 /* Allow 1 character for a '-' sign. */
1943 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1944 }
1945 if (alternate) {
1946 /* 2 characters for prefix */
1947 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001948 }
1949
Victor Stinnerd3f08822012-05-29 12:57:52 +02001950 if (writer) {
1951 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1952 return -1;
1953 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001955 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001956 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1957 if (*bytes_str == NULL)
1958 return -1;
1959 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001961 v = PyUnicode_New(sz, 'x');
1962 if (v == NULL)
1963 return -1;
1964 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001966
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001967#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001968 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001969 if (size_a == 0) { \
1970 *--p = '0'; \
1971 } \
1972 else { \
1973 /* JRH: special case for power-of-2 bases */ \
1974 twodigits accum = 0; \
1975 int accumbits = 0; /* # of bits in accum */ \
1976 Py_ssize_t i; \
1977 for (i = 0; i < size_a; ++i) { \
1978 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1979 accumbits += PyLong_SHIFT; \
1980 assert(accumbits >= bits); \
1981 do { \
1982 char cdigit; \
1983 cdigit = (char)(accum & (base - 1)); \
1984 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1985 *--p = cdigit; \
1986 accumbits -= bits; \
1987 accum >>= bits; \
1988 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1989 } \
1990 } \
1991 \
1992 if (alternate) { \
1993 if (base == 16) \
1994 *--p = 'x'; \
1995 else if (base == 8) \
1996 *--p = 'o'; \
1997 else /* (base == 2) */ \
1998 *--p = 'b'; \
1999 *--p = '0'; \
2000 } \
2001 if (negative) \
2002 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002003 } while (0)
2004
2005#define WRITE_UNICODE_DIGITS(TYPE) \
2006 do { \
2007 if (writer) \
2008 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
2009 else \
2010 p = (TYPE*)PyUnicode_DATA(v) + sz; \
2011 \
2012 WRITE_DIGITS(p); \
2013 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002014 if (writer) \
2015 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2016 else \
2017 assert(p == (TYPE*)PyUnicode_DATA(v)); \
2018 } while (0)
2019
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002020 if (bytes_writer) {
2021 char *p = *bytes_str + sz;
2022 WRITE_DIGITS(p);
2023 assert(p == *bytes_str);
2024 }
2025 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002026 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002027 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002028 }
2029 else if (kind == PyUnicode_2BYTE_KIND) {
2030 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002031 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002032 }
2033 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002034 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002035 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002036 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002037 }
2038#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002039#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002040
2041 if (writer) {
2042 writer->pos += sz;
2043 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002044 else if (bytes_writer) {
2045 (*bytes_str) += sz;
2046 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002047 else {
2048 assert(_PyUnicode_CheckConsistency(v, 1));
2049 *p_output = v;
2050 }
2051 return 0;
2052}
2053
2054PyObject *
2055_PyLong_Format(PyObject *obj, int base)
2056{
2057 PyObject *str;
2058 int err;
2059 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002060 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002061 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002062 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002063 if (err == -1)
2064 return NULL;
2065 return str;
2066}
2067
2068int
2069_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2070 PyObject *obj,
2071 int base, int alternate)
2072{
2073 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002074 return long_to_decimal_string_internal(obj, NULL, writer,
2075 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002076 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002077 return long_format_binary(obj, base, alternate, NULL, writer,
2078 NULL, NULL);
2079}
2080
2081char*
2082_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2083 PyObject *obj,
2084 int base, int alternate)
2085{
2086 char *str2;
2087 int res;
2088 str2 = str;
2089 if (base == 10)
2090 res = long_to_decimal_string_internal(obj, NULL, NULL,
2091 writer, &str2);
2092 else
2093 res = long_format_binary(obj, base, alternate, NULL, NULL,
2094 writer, &str2);
2095 if (res < 0)
2096 return NULL;
2097 assert(str2 != NULL);
2098 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002099}
2100
Thomas Wouters477c8d52006-05-27 19:21:47 +00002101/* Table of digit values for 8-bit string -> integer conversion.
2102 * '0' maps to 0, ..., '9' maps to 9.
2103 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2104 * All other indices map to 37.
2105 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002106 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002107 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002108unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2110 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2111 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2112 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2113 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2114 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2115 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2116 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2117 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2118 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2119 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2120 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2121 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2122 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2123 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2124 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002125};
2126
2127/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002128 * 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 +03002129 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002130 * The point to this routine is that it takes time linear in the number of
2131 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002132 *
2133 * Return values:
2134 * -1 on syntax error (exception needs to be set, *res is untouched)
2135 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002136 */
Brett Cannona721aba2016-09-09 14:57:09 -07002137static int
2138long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002139{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002140 const char *p = *str;
2141 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002142 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002143 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 int bits_per_char;
2145 Py_ssize_t n;
2146 PyLongObject *z;
2147 twodigits accum;
2148 int bits_in_accum;
2149 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2152 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002153 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002155 }
2156 /* count digits and set p to end-of-string */
2157 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2158 if (*p == '_') {
2159 if (prev == '_') {
2160 *str = p - 1;
2161 return -1;
2162 }
2163 } else {
2164 ++digits;
2165 }
2166 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002168 }
2169 if (prev == '_') {
2170 /* Trailing underscore not allowed. */
2171 *str = p - 1;
2172 return -1;
2173 }
2174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002176 /* n <- the number of Python digits needed,
2177 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2178 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 PyErr_SetString(PyExc_ValueError,
2180 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002181 *res = NULL;
2182 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002184 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002186 if (z == NULL) {
2187 *res = NULL;
2188 return 0;
2189 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002190 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 * from least to most significant in both.
2192 */
2193 accum = 0;
2194 bits_in_accum = 0;
2195 pdigit = z->ob_digit;
2196 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002197 int k;
2198 if (*p == '_') {
2199 continue;
2200 }
2201 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 assert(k >= 0 && k < base);
2203 accum |= (twodigits)k << bits_in_accum;
2204 bits_in_accum += bits_per_char;
2205 if (bits_in_accum >= PyLong_SHIFT) {
2206 *pdigit++ = (digit)(accum & PyLong_MASK);
2207 assert(pdigit - z->ob_digit <= n);
2208 accum >>= PyLong_SHIFT;
2209 bits_in_accum -= PyLong_SHIFT;
2210 assert(bits_in_accum < PyLong_SHIFT);
2211 }
2212 }
2213 if (bits_in_accum) {
2214 assert(bits_in_accum <= PyLong_SHIFT);
2215 *pdigit++ = (digit)accum;
2216 assert(pdigit - z->ob_digit <= n);
2217 }
2218 while (pdigit - z->ob_digit < n)
2219 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002220 *res = long_normalize(z);
2221 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002222}
2223
Serhiy Storchaka95949422013-08-27 19:40:23 +03002224/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002225 * ignored.
2226 *
2227 * If successful, a PyLong object will be returned and 'pend' will be pointing
2228 * to the first unused byte unless it's NULL.
2229 *
2230 * If unsuccessful, NULL will be returned.
2231 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002232PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002233PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002236 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 PyLongObject *z = NULL;
2238 PyObject *strobj;
2239 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if ((base != 0 && base < 2) || base > 36) {
2242 PyErr_SetString(PyExc_ValueError,
2243 "int() arg 2 must be >= 2 and <= 36");
2244 return NULL;
2245 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002246 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002248 }
2249 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002251 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 else if (*str == '-') {
2253 ++str;
2254 sign = -1;
2255 }
2256 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002257 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002259 }
2260 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002262 }
2263 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002265 }
2266 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002268 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 else {
2270 /* "old" (C-style) octal literal, now invalid.
2271 it might still be zero though */
2272 error_if_nonzero = 1;
2273 base = 10;
2274 }
2275 }
2276 if (str[0] == '0' &&
2277 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2278 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002279 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002281 /* One underscore allowed here. */
2282 if (*str == '_') {
2283 ++str;
2284 }
2285 }
2286 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002287 /* May not start with underscores. */
2288 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002289 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002292 if ((base & (base - 1)) == 0) {
2293 int res = long_from_binary_base(&str, base, &z);
2294 if (res < 0) {
2295 /* Syntax error. */
2296 goto onError;
2297 }
2298 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002300/***
2301Binary bases can be converted in time linear in the number of digits, because
2302Python's representation base is binary. Other bases (including decimal!) use
2303the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002304
Thomas Wouters477c8d52006-05-27 19:21:47 +00002305First some math: the largest integer that can be expressed in N base-B digits
2306is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2307case number of Python digits needed to hold it is the smallest integer n s.t.
2308
2309 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2310 BASE**n >= B**N [taking logs to base BASE]
2311 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2312
2313The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002314this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002315and the result is computed into it.
2316
2317The input string is actually treated as being in base base**i (i.e., i digits
2318are processed at a time), where two more static arrays hold:
2319
2320 convwidth_base[base] = the largest integer i such that base**i <= BASE
2321 convmultmax_base[base] = base ** convwidth_base[base]
2322
2323The first of these is the largest i such that i consecutive input digits
2324must fit in a single Python digit. The second is effectively the input
2325base we're really using.
2326
2327Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2328convmultmax_base[base], the result is "simply"
2329
2330 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2331
2332where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002333
2334Error analysis: as above, the number of Python digits `n` needed is worst-
2335case
2336
2337 n >= N * log(B)/log(BASE)
2338
2339where `N` is the number of input digits in base `B`. This is computed via
2340
2341 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2342
2343below. Two numeric concerns are how much space this can waste, and whether
2344the computed result can be too small. To be concrete, assume BASE = 2**15,
2345which is the default (and it's unlikely anyone changes that).
2346
2347Waste isn't a problem: provided the first input digit isn't 0, the difference
2348between the worst-case input with N digits and the smallest input with N
2349digits is about a factor of B, but B is small compared to BASE so at most
2350one allocated Python digit can remain unused on that count. If
2351N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2352and adding 1 returns a result 1 larger than necessary. However, that can't
2353happen: whenever B is a power of 2, long_from_binary_base() is called
2354instead, and it's impossible for B**i to be an integer power of 2**15 when
2355B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2356an exact integer when B is not a power of 2, since B**i has a prime factor
2357other than 2 in that case, but (2**15)**j's only prime factor is 2).
2358
2359The computed result can be too small if the true value of N*log(B)/log(BASE)
2360is a little bit larger than an exact integer, but due to roundoff errors (in
2361computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2362yields a numeric result a little less than that integer. Unfortunately, "how
2363close can a transcendental function get to an integer over some range?"
2364questions are generally theoretically intractable. Computer analysis via
2365continued fractions is practical: expand log(B)/log(BASE) via continued
2366fractions, giving a sequence i/j of "the best" rational approximations. Then
2367j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2368we can get very close to being in trouble, but very rarely. For example,
236976573 is a denominator in one of the continued-fraction approximations to
2370log(10)/log(2**15), and indeed:
2371
2372 >>> log(10)/log(2**15)*76573
2373 16958.000000654003
2374
2375is very close to an integer. If we were working with IEEE single-precision,
2376rounding errors could kill us. Finding worst cases in IEEE double-precision
2377requires better-than-double-precision log() functions, and Tim didn't bother.
2378Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002379new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002380This should happen extremely rarely, and in fact I don't have a test case
2381that triggers it(!). Instead the code was tested by artificially allocating
2382just 1 digit at the start, so that the copying code was exercised for every
2383digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002384***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002385 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002387 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 int i;
2389 int convwidth;
2390 twodigits convmultmax, convmult;
2391 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002392 const char *scan, *lastdigit;
2393 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 static double log_base_BASE[37] = {0.0e0,};
2396 static int convwidth_base[37] = {0,};
2397 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 if (log_base_BASE[base] == 0.0) {
2400 twodigits convmax = base;
2401 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002402
Mark Dickinson22b20182010-05-10 21:27:53 +00002403 log_base_BASE[base] = (log((double)base) /
2404 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 for (;;) {
2406 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002407 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002409 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 convmax = next;
2411 ++i;
2412 }
2413 convmultmax_base[base] = convmax;
2414 assert(i > 0);
2415 convwidth_base[base] = i;
2416 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 /* Find length of the string of numeric characters. */
2419 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002420 lastdigit = str;
2421
2422 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2423 if (*scan == '_') {
2424 if (prev == '_') {
2425 /* Only one underscore allowed. */
2426 str = lastdigit + 1;
2427 goto onError;
2428 }
2429 }
2430 else {
2431 ++digits;
2432 lastdigit = scan;
2433 }
2434 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002436 }
2437 if (prev == '_') {
2438 /* Trailing underscore not allowed. */
2439 /* Set error pointer to first underscore. */
2440 str = lastdigit + 1;
2441 goto onError;
2442 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002443
Serhiy Storchaka95949422013-08-27 19:40:23 +03002444 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 * integer with this base and length. Note that there's no
2446 * need to initialize z->ob_digit -- no slot is read up before
2447 * being stored into.
2448 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002449 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2450 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002451 /* The same exception as in _PyLong_New(). */
2452 PyErr_SetString(PyExc_OverflowError,
2453 "too many digits in integer");
2454 return NULL;
2455 }
2456 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 /* Uncomment next line to test exceedingly rare copy code */
2458 /* size_z = 1; */
2459 assert(size_z > 0);
2460 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002461 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002463 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002464 Py_SET_SIZE(z, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 /* `convwidth` consecutive input digits are treated as a single
2467 * digit in base `convmultmax`.
2468 */
2469 convwidth = convwidth_base[base];
2470 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* Work ;-) */
2473 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002474 if (*str == '_') {
2475 str++;
2476 continue;
2477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 /* grab up to convwidth digits from the input string */
2479 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002480 for (i = 1; i < convwidth && str != scan; ++str) {
2481 if (*str == '_') {
2482 continue;
2483 }
2484 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002486 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 assert(c < PyLong_BASE);
2488 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 convmult = convmultmax;
2491 /* Calculate the shift only if we couldn't get
2492 * convwidth digits.
2493 */
2494 if (i != convwidth) {
2495 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002496 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002498 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 /* Multiply z by convmult, and add c. */
2502 pz = z->ob_digit;
2503 pzstop = pz + Py_SIZE(z);
2504 for (; pz < pzstop; ++pz) {
2505 c += (twodigits)*pz * convmult;
2506 *pz = (digit)(c & PyLong_MASK);
2507 c >>= PyLong_SHIFT;
2508 }
2509 /* carry off the current end? */
2510 if (c) {
2511 assert(c < PyLong_BASE);
2512 if (Py_SIZE(z) < size_z) {
2513 *pz = (digit)c;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002514 Py_SET_SIZE(z, Py_SIZE(z) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 }
2516 else {
2517 PyLongObject *tmp;
2518 /* Extremely rare. Get more space. */
2519 assert(Py_SIZE(z) == size_z);
2520 tmp = _PyLong_New(size_z + 1);
2521 if (tmp == NULL) {
2522 Py_DECREF(z);
2523 return NULL;
2524 }
2525 memcpy(tmp->ob_digit,
2526 z->ob_digit,
2527 sizeof(digit) * size_z);
2528 Py_DECREF(z);
2529 z = tmp;
2530 z->ob_digit[size_z] = (digit)c;
2531 ++size_z;
2532 }
2533 }
2534 }
2535 }
Brett Cannona721aba2016-09-09 14:57:09 -07002536 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002538 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 if (error_if_nonzero) {
2540 /* reset the base to 0, else the exception message
2541 doesn't make too much sense */
2542 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002543 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002545 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 /* there might still be other problems, therefore base
2547 remains zero here for the same reason */
2548 }
Brett Cannona721aba2016-09-09 14:57:09 -07002549 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002551 }
2552 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002553 Py_SET_SIZE(z, -(Py_SIZE(z)));
Brett Cannona721aba2016-09-09 14:57:09 -07002554 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002555 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002557 }
2558 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002562 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002563 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002564 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002565 }
2566 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002567 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002568 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002569 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002570
Mark Dickinson22b20182010-05-10 21:27:53 +00002571 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002572 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002573 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002574 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 Py_XDECREF(z);
2576 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2577 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002578 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002580 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002582 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 base, strobj);
2584 Py_DECREF(strobj);
2585 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002586}
2587
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002588/* Since PyLong_FromString doesn't have a length parameter,
2589 * check here for possible NULs in the string.
2590 *
2591 * Reports an invalid literal as a bytes object.
2592 */
2593PyObject *
2594_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2595{
2596 PyObject *result, *strobj;
2597 char *end = NULL;
2598
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002599 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002600 if (end == NULL || (result != NULL && end == s + len))
2601 return result;
2602 Py_XDECREF(result);
2603 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2604 if (strobj != NULL) {
2605 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002606 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002607 base, strobj);
2608 Py_DECREF(strobj);
2609 }
2610 return NULL;
2611}
2612
Guido van Rossum9e896b32000-04-05 20:11:21 +00002613PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002614PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002615{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002616 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002617 if (unicode == NULL)
2618 return NULL;
2619 v = PyLong_FromUnicodeObject(unicode, base);
2620 Py_DECREF(unicode);
2621 return v;
2622}
2623
2624PyObject *
2625PyLong_FromUnicodeObject(PyObject *u, int base)
2626{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002627 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002628 const char *buffer;
2629 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002630 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002632 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002633 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002635 assert(PyUnicode_IS_ASCII(asciidig));
2636 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002637 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002638 assert(buffer != NULL);
2639
2640 result = PyLong_FromString(buffer, &end, base);
2641 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002642 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002643 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002645 Py_DECREF(asciidig);
2646 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002647 PyErr_Format(PyExc_ValueError,
2648 "invalid literal for int() with base %d: %.200R",
2649 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002650 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002651}
2652
Tim Peters9f688bf2000-07-07 15:53:28 +00002653/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002654static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002656static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002657
Serhiy Storchaka95949422013-08-27 19:40:23 +03002658/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002659
Guido van Rossume32e0141992-01-19 16:31:05 +00002660static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002661long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002663{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002664 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 if (size_b == 0) {
2668 PyErr_SetString(PyExc_ZeroDivisionError,
2669 "integer division or modulo by zero");
2670 return -1;
2671 }
2672 if (size_a < size_b ||
2673 (size_a == size_b &&
2674 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2675 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002676 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002677 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002678 return -1;
2679 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002680 Py_INCREF(_PyLong_Zero);
2681 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 return 0;
2683 }
2684 if (size_b == 1) {
2685 digit rem = 0;
2686 z = divrem1(a, b->ob_digit[0], &rem);
2687 if (z == NULL)
2688 return -1;
2689 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2690 if (*prem == NULL) {
2691 Py_DECREF(z);
2692 return -1;
2693 }
2694 }
2695 else {
2696 z = x_divrem(a, b, prem);
2697 if (z == NULL)
2698 return -1;
2699 }
2700 /* Set the signs.
2701 The quotient z has the sign of a*b;
2702 the remainder r has the sign of a,
2703 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002704 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2705 _PyLong_Negate(&z);
2706 if (z == NULL) {
2707 Py_CLEAR(*prem);
2708 return -1;
2709 }
2710 }
2711 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2712 _PyLong_Negate(prem);
2713 if (*prem == NULL) {
2714 Py_DECREF(z);
2715 Py_CLEAR(*prem);
2716 return -1;
2717 }
2718 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 *pdiv = maybe_small_long(z);
2720 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002721}
2722
Serhiy Storchaka95949422013-08-27 19:40:23 +03002723/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002724 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002725
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002726static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002727x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 PyLongObject *v, *w, *a;
2730 Py_ssize_t i, k, size_v, size_w;
2731 int d;
2732 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2733 twodigits vv;
2734 sdigit zhi;
2735 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2738 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2739 handle the special case when the initial estimate q for a quotient
2740 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2741 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002744 size_v = Py_ABS(Py_SIZE(v1));
2745 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2747 v = _PyLong_New(size_v+1);
2748 if (v == NULL) {
2749 *prem = NULL;
2750 return NULL;
2751 }
2752 w = _PyLong_New(size_w);
2753 if (w == NULL) {
2754 Py_DECREF(v);
2755 *prem = NULL;
2756 return NULL;
2757 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2760 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002761 d = PyLong_SHIFT - _Py_bit_length(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2763 assert(carry == 0);
2764 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2765 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2766 v->ob_digit[size_v] = carry;
2767 size_v++;
2768 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2771 at most (and usually exactly) k = size_v - size_w digits. */
2772 k = size_v - size_w;
2773 assert(k >= 0);
2774 a = _PyLong_New(k);
2775 if (a == NULL) {
2776 Py_DECREF(w);
2777 Py_DECREF(v);
2778 *prem = NULL;
2779 return NULL;
2780 }
2781 v0 = v->ob_digit;
2782 w0 = w->ob_digit;
2783 wm1 = w0[size_w-1];
2784 wm2 = w0[size_w-2];
2785 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2786 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2787 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002790 Py_DECREF(a);
2791 Py_DECREF(w);
2792 Py_DECREF(v);
2793 *prem = NULL;
2794 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002795 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 /* estimate quotient digit q; may overestimate by 1 (rare) */
2798 vtop = vk[size_w];
2799 assert(vtop <= wm1);
2800 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2801 q = (digit)(vv / wm1);
2802 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2803 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2804 | vk[size_w-2])) {
2805 --q;
2806 r += wm1;
2807 if (r >= PyLong_BASE)
2808 break;
2809 }
2810 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2813 zhi = 0;
2814 for (i = 0; i < size_w; ++i) {
2815 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2816 -PyLong_BASE * q <= z < PyLong_BASE */
2817 z = (sdigit)vk[i] + zhi -
2818 (stwodigits)q * (stwodigits)w0[i];
2819 vk[i] = (digit)z & PyLong_MASK;
2820 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002821 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 /* add w back if q was too large (this branch taken rarely) */
2825 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2826 if ((sdigit)vtop + zhi < 0) {
2827 carry = 0;
2828 for (i = 0; i < size_w; ++i) {
2829 carry += vk[i] + w0[i];
2830 vk[i] = carry & PyLong_MASK;
2831 carry >>= PyLong_SHIFT;
2832 }
2833 --q;
2834 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 /* store quotient digit */
2837 assert(q < PyLong_BASE);
2838 *--ak = q;
2839 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 /* unshift remainder; we reuse w to store the result */
2842 carry = v_rshift(w0, v0, size_w, d);
2843 assert(carry==0);
2844 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 *prem = long_normalize(w);
2847 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002848}
2849
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002850/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2851 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2852 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2853 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2854 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2855 -1.0. */
2856
2857/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2858#if DBL_MANT_DIG == 53
2859#define EXP2_DBL_MANT_DIG 9007199254740992.0
2860#else
2861#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2862#endif
2863
2864double
2865_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2868 /* See below for why x_digits is always large enough. */
Dong-hee Nab88cd582020-05-04 22:32:42 +09002869 digit rem;
2870 digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 double dx;
2872 /* Correction term for round-half-to-even rounding. For a digit x,
2873 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2874 multiple of 4, rounding ties to a multiple of 8. */
2875 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002876
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002877 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 if (a_size == 0) {
2879 /* Special case for 0: significand 0.0, exponent 0. */
2880 *e = 0;
2881 return 0.0;
2882 }
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002883 a_bits = _Py_bit_length(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 /* The following is an overflow-free version of the check
2885 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2886 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2887 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2888 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002889 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2893 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 Number of digits needed for result: write // for floor division.
2896 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2905 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2908 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2909 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 in both cases.
2916 */
2917 if (a_bits <= DBL_MANT_DIG + 2) {
2918 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2919 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
Dong-hee Nab88cd582020-05-04 22:32:42 +09002920 x_size = shift_digits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2922 (int)shift_bits);
2923 x_size += a_size;
2924 x_digits[x_size++] = rem;
2925 }
2926 else {
2927 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2928 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2929 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2930 a_size - shift_digits, (int)shift_bits);
2931 x_size = a_size - shift_digits;
2932 /* For correct rounding below, we need the least significant
2933 bit of x to be 'sticky' for this shift: if any of the bits
2934 shifted out was nonzero, we set the least significant bit
2935 of x. */
2936 if (rem)
2937 x_digits[0] |= 1;
2938 else
2939 while (shift_digits > 0)
2940 if (a->ob_digit[--shift_digits]) {
2941 x_digits[0] |= 1;
2942 break;
2943 }
2944 }
Victor Stinner63941882011-09-29 00:42:28 +02002945 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 /* Round, and convert to double. */
2948 x_digits[0] += half_even_correction[x_digits[0] & 7];
2949 dx = x_digits[--x_size];
2950 while (x_size > 0)
2951 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 /* Rescale; make correction if result is 1.0. */
2954 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2955 if (dx == 1.0) {
2956 if (a_bits == PY_SSIZE_T_MAX)
2957 goto overflow;
2958 dx = 0.5;
2959 a_bits += 1;
2960 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 *e = a_bits;
2963 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002964
2965 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 /* exponent > PY_SSIZE_T_MAX */
2967 PyErr_SetString(PyExc_OverflowError,
2968 "huge integer: number of bits overflows a Py_ssize_t");
2969 *e = 0;
2970 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002971}
2972
Serhiy Storchaka95949422013-08-27 19:40:23 +03002973/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002974 using the round-half-to-even rule in the case of a tie. */
2975
2976double
2977PyLong_AsDouble(PyObject *v)
2978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 Py_ssize_t exponent;
2980 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002981
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002982 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 PyErr_BadInternalCall();
2984 return -1.0;
2985 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002986 if (!PyLong_Check(v)) {
2987 PyErr_SetString(PyExc_TypeError, "an integer is required");
2988 return -1.0;
2989 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002990 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002991 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002992 to double. This improves performance of FP/long operations
2993 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002994 */
2995 return (double)MEDIUM_VALUE((PyLongObject *)v);
2996 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2998 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2999 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01003000 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 return -1.0;
3002 }
3003 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003004}
3005
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003006/* Methods */
3007
HongWeipeng42acb7b2019-09-18 23:10:15 +08003008/* if a < b, return a negative number
3009 if a == b, return 0
3010 if a > b, return a positive number */
3011
3012static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003013long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003014{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003015 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
3016 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003017 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08003018 sdigit diff = 0;
3019 while (--i >= 0) {
3020 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
3021 if (diff) {
3022 break;
3023 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003025 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003027 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003028}
3029
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003030static PyObject *
3031long_richcompare(PyObject *self, PyObject *other, int op)
3032{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003033 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 CHECK_BINOP(self, other);
3035 if (self == other)
3036 result = 0;
3037 else
3038 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003039 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003040}
3041
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003042static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003043long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003044{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003045 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 Py_ssize_t i;
3047 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 i = Py_SIZE(v);
3050 switch(i) {
3051 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3052 case 0: return 0;
3053 case 1: return v->ob_digit[0];
3054 }
3055 sign = 1;
3056 x = 0;
3057 if (i < 0) {
3058 sign = -1;
3059 i = -(i);
3060 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003062 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3063 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3064 _PyHASH_MODULUS.
3065
3066 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3067 amounts to a rotation of the bits of x. To see this, write
3068
3069 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3070
3071 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3072 PyLong_SHIFT bits of x (those that are shifted out of the
3073 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3074 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3075 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3076 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3077 congruent to y modulo _PyHASH_MODULUS. So
3078
3079 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3080
3081 The right-hand side is just the result of rotating the
3082 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3083 not all _PyHASH_BITS bits of x are 1s, the same is true
3084 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3085 the reduction of x*2**PyLong_SHIFT modulo
3086 _PyHASH_MODULUS. */
3087 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3088 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003090 if (x >= _PyHASH_MODULUS)
3091 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 }
3093 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003094 if (x == (Py_uhash_t)-1)
3095 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003096 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003097}
3098
3099
Serhiy Storchaka95949422013-08-27 19:40:23 +03003100/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003101
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003102static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003103x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003104{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003105 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 PyLongObject *z;
3107 Py_ssize_t i;
3108 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 /* Ensure a is the larger of the two: */
3111 if (size_a < size_b) {
3112 { PyLongObject *temp = a; a = b; b = temp; }
3113 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003114 size_a = size_b;
3115 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 }
3117 z = _PyLong_New(size_a+1);
3118 if (z == NULL)
3119 return NULL;
3120 for (i = 0; i < size_b; ++i) {
3121 carry += a->ob_digit[i] + b->ob_digit[i];
3122 z->ob_digit[i] = carry & PyLong_MASK;
3123 carry >>= PyLong_SHIFT;
3124 }
3125 for (; i < size_a; ++i) {
3126 carry += a->ob_digit[i];
3127 z->ob_digit[i] = carry & PyLong_MASK;
3128 carry >>= PyLong_SHIFT;
3129 }
3130 z->ob_digit[i] = carry;
3131 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003132}
3133
3134/* Subtract the absolute values of two integers. */
3135
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003136static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003137x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003138{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003139 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 PyLongObject *z;
3141 Py_ssize_t i;
3142 int sign = 1;
3143 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 /* Ensure a is the larger of the two: */
3146 if (size_a < size_b) {
3147 sign = -1;
3148 { PyLongObject *temp = a; a = b; b = temp; }
3149 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003150 size_a = size_b;
3151 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 }
3153 else if (size_a == size_b) {
3154 /* Find highest digit where a and b differ: */
3155 i = size_a;
3156 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3157 ;
3158 if (i < 0)
3159 return (PyLongObject *)PyLong_FromLong(0);
3160 if (a->ob_digit[i] < b->ob_digit[i]) {
3161 sign = -1;
3162 { PyLongObject *temp = a; a = b; b = temp; }
3163 }
3164 size_a = size_b = i+1;
3165 }
3166 z = _PyLong_New(size_a);
3167 if (z == NULL)
3168 return NULL;
3169 for (i = 0; i < size_b; ++i) {
3170 /* The following assumes unsigned arithmetic
3171 works module 2**N for some N>PyLong_SHIFT. */
3172 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3173 z->ob_digit[i] = borrow & PyLong_MASK;
3174 borrow >>= PyLong_SHIFT;
3175 borrow &= 1; /* Keep only one sign bit */
3176 }
3177 for (; i < size_a; ++i) {
3178 borrow = a->ob_digit[i] - borrow;
3179 z->ob_digit[i] = borrow & PyLong_MASK;
3180 borrow >>= PyLong_SHIFT;
3181 borrow &= 1; /* Keep only one sign bit */
3182 }
3183 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003184 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003185 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02003186 }
HongWeipeng036fe852019-11-26 15:54:49 +08003187 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003188}
3189
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003190static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003191long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003196
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003197 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003198 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 }
3200 if (Py_SIZE(a) < 0) {
3201 if (Py_SIZE(b) < 0) {
3202 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003203 if (z != NULL) {
3204 /* x_add received at least one multiple-digit int,
3205 and thus z must be a multiple-digit int.
3206 That also means z is not an element of
3207 small_ints, so negating it in-place is safe. */
3208 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003209 Py_SET_SIZE(z, -(Py_SIZE(z)));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003210 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 }
3212 else
3213 z = x_sub(b, a);
3214 }
3215 else {
3216 if (Py_SIZE(b) < 0)
3217 z = x_sub(a, b);
3218 else
3219 z = x_add(a, b);
3220 }
3221 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003222}
3223
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003224static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003225long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003230
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003231 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003232 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 }
3234 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003235 if (Py_SIZE(b) < 0) {
3236 z = x_sub(b, a);
3237 }
3238 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003240 if (z != NULL) {
3241 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003242 Py_SET_SIZE(z, -(Py_SIZE(z)));
HongWeipeng036fe852019-11-26 15:54:49 +08003243 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003244 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 }
3246 else {
3247 if (Py_SIZE(b) < 0)
3248 z = x_add(a, b);
3249 else
3250 z = x_sub(a, b);
3251 }
3252 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003253}
3254
Tim Peters5af4e6c2002-08-12 02:31:19 +00003255/* Grade school multiplication, ignoring the signs.
3256 * Returns the absolute value of the product, or NULL if error.
3257 */
3258static PyLongObject *
3259x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003262 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3263 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 z = _PyLong_New(size_a + size_b);
3267 if (z == NULL)
3268 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3271 if (a == b) {
3272 /* Efficient squaring per HAC, Algorithm 14.16:
3273 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3274 * Gives slightly less than a 2x speedup when a == b,
3275 * via exploiting that each entry in the multiplication
3276 * pyramid appears twice (except for the size_a squares).
3277 */
3278 for (i = 0; i < size_a; ++i) {
3279 twodigits carry;
3280 twodigits f = a->ob_digit[i];
3281 digit *pz = z->ob_digit + (i << 1);
3282 digit *pa = a->ob_digit + i + 1;
3283 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003286 Py_DECREF(z);
3287 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003288 });
Tim Peters0973b992004-08-29 22:16:50 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 carry = *pz + f * f;
3291 *pz++ = (digit)(carry & PyLong_MASK);
3292 carry >>= PyLong_SHIFT;
3293 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 /* Now f is added in twice in each column of the
3296 * pyramid it appears. Same as adding f<<1 once.
3297 */
3298 f <<= 1;
3299 while (pa < paend) {
3300 carry += *pz + *pa++ * f;
3301 *pz++ = (digit)(carry & PyLong_MASK);
3302 carry >>= PyLong_SHIFT;
3303 assert(carry <= (PyLong_MASK << 1));
3304 }
3305 if (carry) {
3306 carry += *pz;
3307 *pz++ = (digit)(carry & PyLong_MASK);
3308 carry >>= PyLong_SHIFT;
3309 }
3310 if (carry)
3311 *pz += (digit)(carry & PyLong_MASK);
3312 assert((carry >> PyLong_SHIFT) == 0);
3313 }
3314 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003315 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 for (i = 0; i < size_a; ++i) {
3317 twodigits carry = 0;
3318 twodigits f = a->ob_digit[i];
3319 digit *pz = z->ob_digit + i;
3320 digit *pb = b->ob_digit;
3321 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003324 Py_DECREF(z);
3325 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003326 });
Tim Peters0973b992004-08-29 22:16:50 +00003327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 while (pb < pbend) {
3329 carry += *pz + *pb++ * f;
3330 *pz++ = (digit)(carry & PyLong_MASK);
3331 carry >>= PyLong_SHIFT;
3332 assert(carry <= PyLong_MASK);
3333 }
3334 if (carry)
3335 *pz += (digit)(carry & PyLong_MASK);
3336 assert((carry >> PyLong_SHIFT) == 0);
3337 }
3338 }
3339 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003340}
3341
3342/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003343 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003344 split, and sets low and high such that abs(n) == (high << size) + low,
3345 viewing the shift as being by digits. The sign bit is ignored, and
3346 the return values are >= 0.
3347 Returns 0 on success, -1 on failure.
3348*/
3349static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003350kmul_split(PyLongObject *n,
3351 Py_ssize_t size,
3352 PyLongObject **high,
3353 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 PyLongObject *hi, *lo;
3356 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003357 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003358
Victor Stinner640c35c2013-06-04 23:14:37 +02003359 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 if ((hi = _PyLong_New(size_hi)) == NULL)
3363 return -1;
3364 if ((lo = _PyLong_New(size_lo)) == NULL) {
3365 Py_DECREF(hi);
3366 return -1;
3367 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3370 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 *high = long_normalize(hi);
3373 *low = long_normalize(lo);
3374 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003375}
3376
Tim Peters60004642002-08-12 22:01:34 +00003377static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3378
Tim Peters5af4e6c2002-08-12 02:31:19 +00003379/* Karatsuba multiplication. Ignores the input signs, and returns the
3380 * absolute value of the product (or NULL if error).
3381 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3382 */
3383static PyLongObject *
3384k_mul(PyLongObject *a, PyLongObject *b)
3385{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003386 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3387 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 PyLongObject *ah = NULL;
3389 PyLongObject *al = NULL;
3390 PyLongObject *bh = NULL;
3391 PyLongObject *bl = NULL;
3392 PyLongObject *ret = NULL;
3393 PyLongObject *t1, *t2, *t3;
3394 Py_ssize_t shift; /* the number of digits we split off */
3395 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3398 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3399 * Then the original product is
3400 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3401 * By picking X to be a power of 2, "*X" is just shifting, and it's
3402 * been reduced to 3 multiplies on numbers half the size.
3403 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 /* We want to split based on the larger number; fiddle so that b
3406 * is largest.
3407 */
3408 if (asize > bsize) {
3409 t1 = a;
3410 a = b;
3411 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 i = asize;
3414 asize = bsize;
3415 bsize = i;
3416 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 /* Use gradeschool math when either number is too small. */
3419 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3420 if (asize <= i) {
3421 if (asize == 0)
3422 return (PyLongObject *)PyLong_FromLong(0);
3423 else
3424 return x_mul(a, b);
3425 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 /* If a is small compared to b, splitting on b gives a degenerate
3428 * case with ah==0, and Karatsuba may be (even much) less efficient
3429 * than "grade school" then. However, we can still win, by viewing
3430 * b as a string of "big digits", each of width a->ob_size. That
3431 * leads to a sequence of balanced calls to k_mul.
3432 */
3433 if (2 * asize <= bsize)
3434 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 /* Split a & b into hi & lo pieces. */
3437 shift = bsize >> 1;
3438 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3439 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 if (a == b) {
3442 bh = ah;
3443 bl = al;
3444 Py_INCREF(bh);
3445 Py_INCREF(bl);
3446 }
3447 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 /* The plan:
3450 * 1. Allocate result space (asize + bsize digits: that's always
3451 * enough).
3452 * 2. Compute ah*bh, and copy into result at 2*shift.
3453 * 3. Compute al*bl, and copy into result at 0. Note that this
3454 * can't overlap with #2.
3455 * 4. Subtract al*bl from the result, starting at shift. This may
3456 * underflow (borrow out of the high digit), but we don't care:
3457 * we're effectively doing unsigned arithmetic mod
3458 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3459 * borrows and carries out of the high digit can be ignored.
3460 * 5. Subtract ah*bh from the result, starting at shift.
3461 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3462 * at shift.
3463 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 /* 1. Allocate result space. */
3466 ret = _PyLong_New(asize + bsize);
3467 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003468#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 /* Fill with trash, to catch reference to uninitialized digits. */
3470 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003471#endif
Tim Peters44121a62002-08-12 06:17:58 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3474 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3475 assert(Py_SIZE(t1) >= 0);
3476 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3477 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3478 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 /* Zero-out the digits higher than the ah*bh copy. */
3481 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3482 if (i)
3483 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3484 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 /* 3. t2 <- al*bl, and copy into the low digits. */
3487 if ((t2 = k_mul(al, bl)) == NULL) {
3488 Py_DECREF(t1);
3489 goto fail;
3490 }
3491 assert(Py_SIZE(t2) >= 0);
3492 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3493 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 /* Zero out remaining digits. */
3496 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3497 if (i)
3498 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3501 * because it's fresher in cache.
3502 */
3503 i = Py_SIZE(ret) - shift; /* # digits after shift */
3504 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3505 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3508 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3511 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3512 Py_DECREF(ah);
3513 Py_DECREF(al);
3514 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 if (a == b) {
3517 t2 = t1;
3518 Py_INCREF(t2);
3519 }
3520 else if ((t2 = x_add(bh, bl)) == NULL) {
3521 Py_DECREF(t1);
3522 goto fail;
3523 }
3524 Py_DECREF(bh);
3525 Py_DECREF(bl);
3526 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 t3 = k_mul(t1, t2);
3529 Py_DECREF(t1);
3530 Py_DECREF(t2);
3531 if (t3 == NULL) goto fail;
3532 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 /* Add t3. It's not obvious why we can't run out of room here.
3535 * See the (*) comment after this function.
3536 */
3537 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3538 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003541
Mark Dickinson22b20182010-05-10 21:27:53 +00003542 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 Py_XDECREF(ret);
3544 Py_XDECREF(ah);
3545 Py_XDECREF(al);
3546 Py_XDECREF(bh);
3547 Py_XDECREF(bl);
3548 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003549}
3550
Tim Petersd6974a52002-08-13 20:37:51 +00003551/* (*) Why adding t3 can't "run out of room" above.
3552
Tim Petersab86c2b2002-08-15 20:06:00 +00003553Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3554to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003555
Tim Petersab86c2b2002-08-15 20:06:00 +000035561. For any integer i, i = c(i/2) + f(i/2). In particular,
3557 bsize = c(bsize/2) + f(bsize/2).
35582. shift = f(bsize/2)
35593. asize <= bsize
35604. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3561 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003562
Tim Petersab86c2b2002-08-15 20:06:00 +00003563We allocated asize + bsize result digits, and add t3 into them at an offset
3564of shift. This leaves asize+bsize-shift allocated digit positions for t3
3565to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3566asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003567
Tim Petersab86c2b2002-08-15 20:06:00 +00003568bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3569at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003570
Tim Petersab86c2b2002-08-15 20:06:00 +00003571If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3572digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3573most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003574
Tim Petersab86c2b2002-08-15 20:06:00 +00003575The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003576
Tim Petersab86c2b2002-08-15 20:06:00 +00003577 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003578
Tim Petersab86c2b2002-08-15 20:06:00 +00003579and we have asize + c(bsize/2) available digit positions. We need to show
3580this is always enough. An instance of c(bsize/2) cancels out in both, so
3581the question reduces to whether asize digits is enough to hold
3582(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3583then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3584asize 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 +00003585digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003586asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003587c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3588is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3589bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003590
Tim Peters48d52c02002-08-14 17:07:32 +00003591Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3592clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3593ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003594*/
3595
Tim Peters60004642002-08-12 22:01:34 +00003596/* b has at least twice the digits of a, and a is big enough that Karatsuba
3597 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3598 * of slices, each with a->ob_size digits, and multiply the slices by a,
3599 * one at a time. This gives k_mul balanced inputs to work with, and is
3600 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003601 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003602 * single-width slice overlap between successive partial sums).
3603 */
3604static PyLongObject *
3605k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3606{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003607 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3608 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 Py_ssize_t nbdone; /* # of b digits already multiplied */
3610 PyLongObject *ret;
3611 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 assert(asize > KARATSUBA_CUTOFF);
3614 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 /* Allocate result space, and zero it out. */
3617 ret = _PyLong_New(asize + bsize);
3618 if (ret == NULL)
3619 return NULL;
3620 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 /* Successive slices of b are copied into bslice. */
3623 bslice = _PyLong_New(asize);
3624 if (bslice == NULL)
3625 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 nbdone = 0;
3628 while (bsize > 0) {
3629 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003630 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 /* Multiply the next slice of b by a. */
3633 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3634 nbtouse * sizeof(digit));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003635 Py_SET_SIZE(bslice, nbtouse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 product = k_mul(a, bslice);
3637 if (product == NULL)
3638 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 /* Add into result. */
3641 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3642 product->ob_digit, Py_SIZE(product));
3643 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 bsize -= nbtouse;
3646 nbdone += nbtouse;
3647 }
Tim Peters60004642002-08-12 22:01:34 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 Py_DECREF(bslice);
3650 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003651
Mark Dickinson22b20182010-05-10 21:27:53 +00003652 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 Py_DECREF(ret);
3654 Py_XDECREF(bslice);
3655 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003656}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003657
3658static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003659long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003666 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003668 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 z = k_mul(a, b);
3672 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003673 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3674 _PyLong_Negate(&z);
3675 if (z == NULL)
3676 return NULL;
3677 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003679}
3680
Yury Selivanove0b23092016-02-11 10:26:27 -05003681/* Fast modulo division for single-digit longs. */
3682static PyObject *
3683fast_mod(PyLongObject *a, PyLongObject *b)
3684{
3685 sdigit left = a->ob_digit[0];
3686 sdigit right = b->ob_digit[0];
3687 sdigit mod;
3688
3689 assert(Py_ABS(Py_SIZE(a)) == 1);
3690 assert(Py_ABS(Py_SIZE(b)) == 1);
3691
3692 if (Py_SIZE(a) == Py_SIZE(b)) {
3693 /* 'a' and 'b' have the same sign. */
3694 mod = left % right;
3695 }
3696 else {
3697 /* Either 'a' or 'b' is negative. */
3698 mod = right - 1 - (left - 1) % right;
3699 }
3700
Victor Stinnerf963c132016-03-23 18:36:54 +01003701 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003702}
3703
3704/* Fast floor division for single-digit longs. */
3705static PyObject *
3706fast_floor_div(PyLongObject *a, PyLongObject *b)
3707{
3708 sdigit left = a->ob_digit[0];
3709 sdigit right = b->ob_digit[0];
3710 sdigit div;
3711
3712 assert(Py_ABS(Py_SIZE(a)) == 1);
3713 assert(Py_ABS(Py_SIZE(b)) == 1);
3714
3715 if (Py_SIZE(a) == Py_SIZE(b)) {
3716 /* 'a' and 'b' have the same sign. */
3717 div = left / right;
3718 }
3719 else {
3720 /* Either 'a' or 'b' is negative. */
3721 div = -1 - (left - 1) / right;
3722 }
3723
3724 return PyLong_FromLong(div);
3725}
3726
Guido van Rossume32e0141992-01-19 16:31:05 +00003727/* The / and % operators are now defined in terms of divmod().
3728 The expression a mod b has the value a - b*floor(a/b).
3729 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003730 |a| by |b|, with the sign of a. This is also expressed
3731 as a - b*trunc(a/b), if trunc truncates towards zero.
3732 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 a b a rem b a mod b
3734 13 10 3 3
3735 -13 10 -3 7
3736 13 -10 3 -7
3737 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003738 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003739 have different signs. We then subtract one from the 'div'
3740 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003741
Tim Peters47e52ee2004-08-30 02:44:38 +00003742/* Compute
3743 * *pdiv, *pmod = divmod(v, w)
3744 * NULL can be passed for pdiv or pmod, in which case that part of
3745 * the result is simply thrown away. The caller owns a reference to
3746 * each of these it requests (does not pass NULL for).
3747 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003748static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003749l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003753
Yury Selivanove0b23092016-02-11 10:26:27 -05003754 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3755 /* Fast path for single-digit longs */
3756 div = NULL;
3757 if (pdiv != NULL) {
3758 div = (PyLongObject *)fast_floor_div(v, w);
3759 if (div == NULL) {
3760 return -1;
3761 }
3762 }
3763 if (pmod != NULL) {
3764 mod = (PyLongObject *)fast_mod(v, w);
3765 if (mod == NULL) {
3766 Py_XDECREF(div);
3767 return -1;
3768 }
3769 *pmod = mod;
3770 }
3771 if (pdiv != NULL) {
3772 /* We only want to set `*pdiv` when `*pmod` is
3773 set successfully. */
3774 *pdiv = div;
3775 }
3776 return 0;
3777 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 if (long_divrem(v, w, &div, &mod) < 0)
3779 return -1;
3780 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3781 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3782 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 temp = (PyLongObject *) long_add(mod, w);
3784 Py_DECREF(mod);
3785 mod = temp;
3786 if (mod == NULL) {
3787 Py_DECREF(div);
3788 return -1;
3789 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003790 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3791 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 Py_DECREF(mod);
3793 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 return -1;
3795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 Py_DECREF(div);
3797 div = temp;
3798 }
3799 if (pdiv != NULL)
3800 *pdiv = div;
3801 else
3802 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 if (pmod != NULL)
3805 *pmod = mod;
3806 else
3807 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003810}
3811
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003812static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003813long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003818
3819 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3820 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3821 }
3822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3824 div = NULL;
3825 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003826}
3827
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003828/* PyLong/PyLong -> float, with correctly rounded result. */
3829
3830#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3831#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3832
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003833static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003834long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 PyLongObject *a, *b, *x;
3837 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3838 digit mask, low;
3839 int inexact, negate, a_is_small, b_is_small;
3840 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 CHECK_BINOP(v, w);
3843 a = (PyLongObject *)v;
3844 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 /*
3847 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3850 1. choose a suitable integer 'shift'
3851 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3852 3. adjust x for correct rounding
3853 4. convert x to a double dx with the same value
3854 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3859 returns either 0.0 or -0.0, depending on the sign of b. For a and
3860 b both nonzero, ignore signs of a and b, and add the sign back in
3861 at the end. Now write a_bits and b_bits for the bit lengths of a
3862 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3863 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3868 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3869 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3870 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 1. The integer 'shift' is chosen so that x has the right number of
3875 bits for a double, plus two or three extra bits that will be used
3876 in the rounding decisions. Writing a_bits and b_bits for the
3877 number of significant bits in a and b respectively, a
3878 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 This is fine in the usual case, but if a/b is smaller than the
3883 smallest normal float then it can lead to double rounding on an
3884 IEEE 754 platform, giving incorrectly rounded results. So we
3885 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 2. The quantity x is computed by first shifting a (left -shift bits
3890 if shift <= 0, right shift bits if shift > 0) and then dividing by
3891 b. For both the shift and the division, we keep track of whether
3892 the result is inexact, in a flag 'inexact'; this information is
3893 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 With the choice of shift above, together with our assumption that
3896 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3897 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3900 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 For float representability, we need x/2**extra_bits <
3905 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3906 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 To round, we just modify the bottom digit of x in-place; this can
3911 end up giving a digit with value > PyLONG_MASK, but that's not a
3912 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 With the original choices for shift above, extra_bits will always
3915 be 2 or 3. Then rounding under the round-half-to-even rule, we
3916 round up iff the most significant of the extra bits is 1, and
3917 either: (a) the computation of x in step 2 had an inexact result,
3918 or (b) at least one other of the extra bits is 1, or (c) the least
3919 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 4. Conversion to a double is straightforward; all floating-point
3922 operations involved in the conversion are exact, so there's no
3923 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3926 The result will always be exactly representable as a double, except
3927 in the case that it overflows. To avoid dependence on the exact
3928 behaviour of ldexp on overflow, we check for overflow before
3929 applying ldexp. The result of ldexp is adjusted for sign before
3930 returning.
3931 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003934 a_size = Py_ABS(Py_SIZE(a));
3935 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3937 if (b_size == 0) {
3938 PyErr_SetString(PyExc_ZeroDivisionError,
3939 "division by zero");
3940 goto error;
3941 }
3942 if (a_size == 0)
3943 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 /* Fast path for a and b small (exactly representable in a double).
3946 Relies on floating-point division being correctly rounded; results
3947 may be subject to double rounding on x86 machines that operate with
3948 the x87 FPU set to 64-bit precision. */
3949 a_is_small = a_size <= MANT_DIG_DIGITS ||
3950 (a_size == MANT_DIG_DIGITS+1 &&
3951 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3952 b_is_small = b_size <= MANT_DIG_DIGITS ||
3953 (b_size == MANT_DIG_DIGITS+1 &&
3954 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3955 if (a_is_small && b_is_small) {
3956 double da, db;
3957 da = a->ob_digit[--a_size];
3958 while (a_size > 0)
3959 da = da * PyLong_BASE + a->ob_digit[--a_size];
3960 db = b->ob_digit[--b_size];
3961 while (b_size > 0)
3962 db = db * PyLong_BASE + b->ob_digit[--b_size];
3963 result = da / db;
3964 goto success;
3965 }
Tim Peterse2a60002001-09-04 06:17:36 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 /* Catch obvious cases of underflow and overflow */
3968 diff = a_size - b_size;
3969 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3970 /* Extreme overflow */
3971 goto overflow;
3972 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3973 /* Extreme underflow */
3974 goto underflow_or_zero;
3975 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01003976 diff = diff * PyLong_SHIFT + _Py_bit_length(a->ob_digit[a_size - 1]) -
3977 _Py_bit_length(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 /* Now diff = a_bits - b_bits. */
3979 if (diff > DBL_MAX_EXP)
3980 goto overflow;
3981 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3982 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003985 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 /* x = abs(a * 2**-shift) */
3990 if (shift <= 0) {
3991 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3992 digit rem;
3993 /* x = a << -shift */
3994 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3995 /* In practice, it's probably impossible to end up
3996 here. Both a and b would have to be enormous,
3997 using close to SIZE_T_MAX bytes of memory each. */
3998 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003999 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 goto error;
4001 }
4002 x = _PyLong_New(a_size + shift_digits + 1);
4003 if (x == NULL)
4004 goto error;
4005 for (i = 0; i < shift_digits; i++)
4006 x->ob_digit[i] = 0;
4007 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
4008 a_size, -shift % PyLong_SHIFT);
4009 x->ob_digit[a_size + shift_digits] = rem;
4010 }
4011 else {
4012 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
4013 digit rem;
4014 /* x = a >> shift */
4015 assert(a_size >= shift_digits);
4016 x = _PyLong_New(a_size - shift_digits);
4017 if (x == NULL)
4018 goto error;
4019 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4020 a_size - shift_digits, shift % PyLong_SHIFT);
4021 /* set inexact if any of the bits shifted out is nonzero */
4022 if (rem)
4023 inexact = 1;
4024 while (!inexact && shift_digits > 0)
4025 if (a->ob_digit[--shift_digits])
4026 inexact = 1;
4027 }
4028 long_normalize(x);
4029 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4032 reference to x, so it's safe to modify it in-place. */
4033 if (b_size == 1) {
4034 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4035 b->ob_digit[0]);
4036 long_normalize(x);
4037 if (rem)
4038 inexact = 1;
4039 }
4040 else {
4041 PyLongObject *div, *rem;
4042 div = x_divrem(x, b, &rem);
4043 Py_DECREF(x);
4044 x = div;
4045 if (x == NULL)
4046 goto error;
4047 if (Py_SIZE(rem))
4048 inexact = 1;
4049 Py_DECREF(rem);
4050 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004051 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004053 x_bits = (x_size-1)*PyLong_SHIFT+_Py_bit_length(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004056 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 /* Round by directly modifying the low digit of x. */
4060 mask = (digit)1 << (extra_bits - 1);
4061 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004062 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004064 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 /* Convert x to a double dx; the conversion is exact. */
4067 dx = x->ob_digit[--x_size];
4068 while (x_size > 0)
4069 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4070 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 /* Check whether ldexp result will overflow a double. */
4073 if (shift + x_bits >= DBL_MAX_EXP &&
4074 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4075 goto overflow;
4076 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004077
4078 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004080
4081 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004083
4084 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 PyErr_SetString(PyExc_OverflowError,
4086 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004087 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004089}
4090
4091static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004092long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 CHECK_BINOP(a, b);
4097
Yury Selivanove0b23092016-02-11 10:26:27 -05004098 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4099 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4100 }
4101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4103 mod = NULL;
4104 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004105}
4106
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004107static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004108long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 PyLongObject *div, *mod;
4111 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4116 return NULL;
4117 }
4118 z = PyTuple_New(2);
4119 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004120 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4121 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 }
4123 else {
4124 Py_DECREF(div);
4125 Py_DECREF(mod);
4126 }
4127 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004128}
4129
Mark Dickinsonc5299672019-06-02 10:24:06 +01004130
4131/* Compute an inverse to a modulo n, or raise ValueError if a is not
4132 invertible modulo n. Assumes n is positive. The inverse returned
4133 is whatever falls out of the extended Euclidean algorithm: it may
4134 be either positive or negative, but will be smaller than n in
4135 absolute value.
4136
4137 Pure Python equivalent for long_invmod:
4138
4139 def invmod(a, n):
4140 b, c = 1, 0
4141 while n:
4142 q, r = divmod(a, n)
4143 a, b, c, n = n, c, b - q*c, r
4144
4145 # at this point a is the gcd of the original inputs
4146 if a == 1:
4147 return b
4148 raise ValueError("Not invertible")
4149*/
4150
4151static PyLongObject *
4152long_invmod(PyLongObject *a, PyLongObject *n)
4153{
4154 PyLongObject *b, *c;
4155
4156 /* Should only ever be called for positive n */
4157 assert(Py_SIZE(n) > 0);
4158
4159 b = (PyLongObject *)PyLong_FromLong(1L);
4160 if (b == NULL) {
4161 return NULL;
4162 }
4163 c = (PyLongObject *)PyLong_FromLong(0L);
4164 if (c == NULL) {
4165 Py_DECREF(b);
4166 return NULL;
4167 }
4168 Py_INCREF(a);
4169 Py_INCREF(n);
4170
4171 /* references now owned: a, b, c, n */
4172 while (Py_SIZE(n) != 0) {
4173 PyLongObject *q, *r, *s, *t;
4174
4175 if (l_divmod(a, n, &q, &r) == -1) {
4176 goto Error;
4177 }
4178 Py_DECREF(a);
4179 a = n;
4180 n = r;
4181 t = (PyLongObject *)long_mul(q, c);
4182 Py_DECREF(q);
4183 if (t == NULL) {
4184 goto Error;
4185 }
4186 s = (PyLongObject *)long_sub(b, t);
4187 Py_DECREF(t);
4188 if (s == NULL) {
4189 goto Error;
4190 }
4191 Py_DECREF(b);
4192 b = c;
4193 c = s;
4194 }
4195 /* references now owned: a, b, c, n */
4196
4197 Py_DECREF(c);
4198 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004199 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004200 /* a != 1; we don't have an inverse. */
4201 Py_DECREF(a);
4202 Py_DECREF(b);
4203 PyErr_SetString(PyExc_ValueError,
4204 "base is not invertible for the given modulus");
4205 return NULL;
4206 }
4207 else {
4208 /* a == 1; b gives an inverse modulo n */
4209 Py_DECREF(a);
4210 return b;
4211 }
4212
4213 Error:
4214 Py_DECREF(a);
4215 Py_DECREF(b);
4216 Py_DECREF(c);
4217 Py_DECREF(n);
4218 return NULL;
4219}
4220
4221
Tim Peters47e52ee2004-08-30 02:44:38 +00004222/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004223static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004224long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4227 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 PyLongObject *z = NULL; /* accumulated result */
4230 Py_ssize_t i, j, k; /* counters */
4231 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 /* 5-ary values. If the exponent is large enough, table is
4234 * precomputed so that table[i] == a**i % c for i in range(32).
4235 */
4236 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4237 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 /* a, b, c = v, w, x */
4240 CHECK_BINOP(v, w);
4241 a = (PyLongObject*)v; Py_INCREF(a);
4242 b = (PyLongObject*)w; Py_INCREF(b);
4243 if (PyLong_Check(x)) {
4244 c = (PyLongObject *)x;
4245 Py_INCREF(x);
4246 }
4247 else if (x == Py_None)
4248 c = NULL;
4249 else {
4250 Py_DECREF(a);
4251 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004252 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 }
Tim Peters4c483c42001-09-05 06:24:58 +00004254
Mark Dickinsonc5299672019-06-02 10:24:06 +01004255 if (Py_SIZE(b) < 0 && c == NULL) {
4256 /* if exponent is negative and there's no modulus:
4257 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 that this calls float_pow() which converts its
4259 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004260 Py_DECREF(a);
4261 Py_DECREF(b);
4262 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 if (c) {
4266 /* if modulus == 0:
4267 raise ValueError() */
4268 if (Py_SIZE(c) == 0) {
4269 PyErr_SetString(PyExc_ValueError,
4270 "pow() 3rd argument cannot be 0");
4271 goto Error;
4272 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 /* if modulus < 0:
4275 negativeOutput = True
4276 modulus = -modulus */
4277 if (Py_SIZE(c) < 0) {
4278 negativeOutput = 1;
4279 temp = (PyLongObject *)_PyLong_Copy(c);
4280 if (temp == NULL)
4281 goto Error;
4282 Py_DECREF(c);
4283 c = temp;
4284 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004285 _PyLong_Negate(&c);
4286 if (c == NULL)
4287 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 /* if modulus == 1:
4291 return 0 */
4292 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4293 z = (PyLongObject *)PyLong_FromLong(0L);
4294 goto Done;
4295 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004296
Mark Dickinsonc5299672019-06-02 10:24:06 +01004297 /* if exponent is negative, negate the exponent and
4298 replace the base with a modular inverse */
4299 if (Py_SIZE(b) < 0) {
4300 temp = (PyLongObject *)_PyLong_Copy(b);
4301 if (temp == NULL)
4302 goto Error;
4303 Py_DECREF(b);
4304 b = temp;
4305 temp = NULL;
4306 _PyLong_Negate(&b);
4307 if (b == NULL)
4308 goto Error;
4309
4310 temp = long_invmod(a, c);
4311 if (temp == NULL)
4312 goto Error;
4313 Py_DECREF(a);
4314 a = temp;
4315 }
4316
Tim Peters81a93152013-10-05 16:53:52 -05004317 /* Reduce base by modulus in some cases:
4318 1. If base < 0. Forcing the base non-negative makes things easier.
4319 2. If base is obviously larger than the modulus. The "small
4320 exponent" case later can multiply directly by base repeatedly,
4321 while the "large exponent" case multiplies directly by base 31
4322 times. It can be unboundedly faster to multiply by
4323 base % modulus instead.
4324 We could _always_ do this reduction, but l_divmod() isn't cheap,
4325 so we only do it when it buys something. */
4326 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 if (l_divmod(a, c, NULL, &temp) < 0)
4328 goto Error;
4329 Py_DECREF(a);
4330 a = temp;
4331 temp = NULL;
4332 }
4333 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 /* At this point a, b, and c are guaranteed non-negative UNLESS
4336 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 z = (PyLongObject *)PyLong_FromLong(1L);
4339 if (z == NULL)
4340 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 /* Perform a modular reduction, X = X % c, but leave X alone if c
4343 * is NULL.
4344 */
4345#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004346 do { \
4347 if (c != NULL) { \
4348 if (l_divmod(X, c, NULL, &temp) < 0) \
4349 goto Error; \
4350 Py_XDECREF(X); \
4351 X = temp; \
4352 temp = NULL; \
4353 } \
4354 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 /* Multiply two values, then reduce the result:
4357 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004358#define MULT(X, Y, result) \
4359 do { \
4360 temp = (PyLongObject *)long_mul(X, Y); \
4361 if (temp == NULL) \
4362 goto Error; \
4363 Py_XDECREF(result); \
4364 result = temp; \
4365 temp = NULL; \
4366 REDUCE(result); \
4367 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4370 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4371 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4372 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4373 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004376 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004378 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 }
4380 }
4381 }
4382 else {
4383 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4384 Py_INCREF(z); /* still holds 1L */
4385 table[0] = z;
4386 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004387 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4390 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4393 const int index = (bi >> j) & 0x1f;
4394 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004395 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004397 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 }
4399 }
4400 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 if (negativeOutput && (Py_SIZE(z) != 0)) {
4403 temp = (PyLongObject *)long_sub(z, c);
4404 if (temp == NULL)
4405 goto Error;
4406 Py_DECREF(z);
4407 z = temp;
4408 temp = NULL;
4409 }
4410 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004411
Mark Dickinson22b20182010-05-10 21:27:53 +00004412 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004413 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004415 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4417 for (i = 0; i < 32; ++i)
4418 Py_XDECREF(table[i]);
4419 }
4420 Py_DECREF(a);
4421 Py_DECREF(b);
4422 Py_XDECREF(c);
4423 Py_XDECREF(temp);
4424 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004425}
4426
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004427static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004428long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 /* Implement ~x as -(x+1) */
4431 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004432 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004434 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 if (x == NULL)
4436 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004437 _PyLong_Negate(&x);
4438 /* No need for maybe_small_long here, since any small
4439 longs will have been caught in the Py_SIZE <= 1 fast path. */
4440 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004441}
4442
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004443static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004444long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004447 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 return PyLong_FromLong(-MEDIUM_VALUE(v));
4449 z = (PyLongObject *)_PyLong_Copy(v);
4450 if (z != NULL)
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004451 Py_SET_SIZE(z, -(Py_SIZE(v)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004453}
4454
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004455static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004456long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 if (Py_SIZE(v) < 0)
4459 return long_neg(v);
4460 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004461 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004462}
4463
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004464static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004465long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004468}
4469
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004470/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4471static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004472divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004473{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004474 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004475 assert(Py_SIZE(shiftby) >= 0);
4476 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4477 if (lshiftby >= 0) {
4478 *wordshift = lshiftby / PyLong_SHIFT;
4479 *remshift = lshiftby % PyLong_SHIFT;
4480 return 0;
4481 }
4482 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4483 be that PyLong_AsSsize_t raised an OverflowError. */
4484 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4485 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004486 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004487 if (wordshift_obj == NULL) {
4488 return -1;
4489 }
4490 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4491 Py_DECREF(wordshift_obj);
4492 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4493 return 0;
4494 }
4495 PyErr_Clear();
4496 /* Clip the value. With such large wordshift the right shift
4497 returns 0 and the left shift raises an error in _PyLong_New(). */
4498 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4499 *remshift = 0;
4500 return 0;
4501}
4502
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004503static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004504long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004507 Py_ssize_t newsize, hishift, i, j;
4508 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 if (Py_SIZE(a) < 0) {
4511 /* Right shifting negative numbers is harder */
4512 PyLongObject *a1, *a2;
4513 a1 = (PyLongObject *) long_invert(a);
4514 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004515 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004516 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 Py_DECREF(a1);
4518 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004519 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 z = (PyLongObject *) long_invert(a2);
4521 Py_DECREF(a2);
4522 }
4523 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004524 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 if (newsize <= 0)
4526 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004527 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 lomask = ((digit)1 << hishift) - 1;
4529 himask = PyLong_MASK ^ lomask;
4530 z = _PyLong_New(newsize);
4531 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004532 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004534 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004536 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004538 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004540 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004541}
4542
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004543static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004544long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004545{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004546 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004547 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004550
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004551 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004553 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004555 if (Py_SIZE(a) == 0) {
4556 return PyLong_FromLong(0);
4557 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004558 if (divmod_shift(b, &wordshift, &remshift) < 0)
4559 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004560 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4561}
4562
4563/* Return a >> shiftby. */
4564PyObject *
4565_PyLong_Rshift(PyObject *a, size_t shiftby)
4566{
4567 Py_ssize_t wordshift;
4568 digit remshift;
4569
4570 assert(PyLong_Check(a));
4571 if (Py_SIZE(a) == 0) {
4572 return PyLong_FromLong(0);
4573 }
4574 wordshift = shiftby / PyLong_SHIFT;
4575 remshift = shiftby % PyLong_SHIFT;
4576 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4577}
4578
4579static PyObject *
4580long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4581{
4582 /* This version due to Tim Peters */
4583 PyLongObject *z = NULL;
4584 Py_ssize_t oldsize, newsize, i, j;
4585 twodigits accum;
4586
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004587 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 newsize = oldsize + wordshift;
4589 if (remshift)
4590 ++newsize;
4591 z = _PyLong_New(newsize);
4592 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004593 return NULL;
4594 if (Py_SIZE(a) < 0) {
4595 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004596 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02004597 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 for (i = 0; i < wordshift; i++)
4599 z->ob_digit[i] = 0;
4600 accum = 0;
4601 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4602 accum |= (twodigits)a->ob_digit[j] << remshift;
4603 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4604 accum >>= PyLong_SHIFT;
4605 }
4606 if (remshift)
4607 z->ob_digit[newsize-1] = (digit)accum;
4608 else
4609 assert(!accum);
4610 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004612}
4613
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004614static PyObject *
4615long_lshift(PyObject *a, PyObject *b)
4616{
4617 Py_ssize_t wordshift;
4618 digit remshift;
4619
4620 CHECK_BINOP(a, b);
4621
4622 if (Py_SIZE(b) < 0) {
4623 PyErr_SetString(PyExc_ValueError, "negative shift count");
4624 return NULL;
4625 }
4626 if (Py_SIZE(a) == 0) {
4627 return PyLong_FromLong(0);
4628 }
4629 if (divmod_shift(b, &wordshift, &remshift) < 0)
4630 return NULL;
4631 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4632}
4633
4634/* Return a << shiftby. */
4635PyObject *
4636_PyLong_Lshift(PyObject *a, size_t shiftby)
4637{
4638 Py_ssize_t wordshift;
4639 digit remshift;
4640
4641 assert(PyLong_Check(a));
4642 if (Py_SIZE(a) == 0) {
4643 return PyLong_FromLong(0);
4644 }
4645 wordshift = shiftby / PyLong_SHIFT;
4646 remshift = shiftby % PyLong_SHIFT;
4647 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4648}
4649
Mark Dickinson27a87a22009-10-25 20:43:34 +00004650/* Compute two's complement of digit vector a[0:m], writing result to
4651 z[0:m]. The digit vector a need not be normalized, but should not
4652 be entirely zero. a and z may point to the same digit vector. */
4653
4654static void
4655v_complement(digit *z, digit *a, Py_ssize_t m)
4656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 Py_ssize_t i;
4658 digit carry = 1;
4659 for (i = 0; i < m; ++i) {
4660 carry += a[i] ^ PyLong_MASK;
4661 z[i] = carry & PyLong_MASK;
4662 carry >>= PyLong_SHIFT;
4663 }
4664 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004665}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004666
4667/* Bitwise and/xor/or operations */
4668
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004669static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004670long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004671 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004672 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 int nega, negb, negz;
4675 Py_ssize_t size_a, size_b, size_z, i;
4676 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 /* Bitwise operations for negative numbers operate as though
4679 on a two's complement representation. So convert arguments
4680 from sign-magnitude to two's complement, and convert the
4681 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004684 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 nega = Py_SIZE(a) < 0;
4686 if (nega) {
4687 z = _PyLong_New(size_a);
4688 if (z == NULL)
4689 return NULL;
4690 v_complement(z->ob_digit, a->ob_digit, size_a);
4691 a = z;
4692 }
4693 else
4694 /* Keep reference count consistent. */
4695 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004698 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 negb = Py_SIZE(b) < 0;
4700 if (negb) {
4701 z = _PyLong_New(size_b);
4702 if (z == NULL) {
4703 Py_DECREF(a);
4704 return NULL;
4705 }
4706 v_complement(z->ob_digit, b->ob_digit, size_b);
4707 b = z;
4708 }
4709 else
4710 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 /* Swap a and b if necessary to ensure size_a >= size_b. */
4713 if (size_a < size_b) {
4714 z = a; a = b; b = z;
4715 size_z = size_a; size_a = size_b; size_b = size_z;
4716 negz = nega; nega = negb; negb = negz;
4717 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 /* JRH: The original logic here was to allocate the result value (z)
4720 as the longer of the two operands. However, there are some cases
4721 where the result is guaranteed to be shorter than that: AND of two
4722 positives, OR of two negatives: use the shorter number. AND with
4723 mixed signs: use the positive number. OR with mixed signs: use the
4724 negative number.
4725 */
4726 switch (op) {
4727 case '^':
4728 negz = nega ^ negb;
4729 size_z = size_a;
4730 break;
4731 case '&':
4732 negz = nega & negb;
4733 size_z = negb ? size_a : size_b;
4734 break;
4735 case '|':
4736 negz = nega | negb;
4737 size_z = negb ? size_b : size_a;
4738 break;
4739 default:
stratakisa10d4262019-03-18 18:59:20 +01004740 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 /* We allow an extra digit if z is negative, to make sure that
4744 the final two's complement of z doesn't overflow. */
4745 z = _PyLong_New(size_z + negz);
4746 if (z == NULL) {
4747 Py_DECREF(a);
4748 Py_DECREF(b);
4749 return NULL;
4750 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 /* Compute digits for overlap of a and b. */
4753 switch(op) {
4754 case '&':
4755 for (i = 0; i < size_b; ++i)
4756 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4757 break;
4758 case '|':
4759 for (i = 0; i < size_b; ++i)
4760 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4761 break;
4762 case '^':
4763 for (i = 0; i < size_b; ++i)
4764 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4765 break;
4766 default:
stratakisa10d4262019-03-18 18:59:20 +01004767 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770 /* Copy any remaining digits of a, inverting if necessary. */
4771 if (op == '^' && negb)
4772 for (; i < size_z; ++i)
4773 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4774 else if (i < size_z)
4775 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4776 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778 /* Complement result if negative. */
4779 if (negz) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004780 Py_SET_SIZE(z, -(Py_SIZE(z)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 z->ob_digit[size_z] = PyLong_MASK;
4782 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4783 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 Py_DECREF(a);
4786 Py_DECREF(b);
4787 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004788}
4789
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004790static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004791long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 PyObject *c;
4794 CHECK_BINOP(a, b);
4795 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4796 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004797}
4798
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004799static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004800long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 PyObject *c;
4803 CHECK_BINOP(a, b);
4804 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4805 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004806}
4807
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004808static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004809long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 PyObject *c;
4812 CHECK_BINOP(a, b);
4813 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4814 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004815}
4816
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004817static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004818long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004820 if (PyLong_CheckExact(v))
4821 Py_INCREF(v);
4822 else
4823 v = _PyLong_Copy((PyLongObject *)v);
4824 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004825}
4826
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004827PyObject *
4828_PyLong_GCD(PyObject *aarg, PyObject *barg)
4829{
4830 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4831 stwodigits x, y, q, s, t, c_carry, d_carry;
4832 stwodigits A, B, C, D, T;
4833 int nbits, k;
4834 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4835 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4836
4837 a = (PyLongObject *)aarg;
4838 b = (PyLongObject *)barg;
4839 size_a = Py_SIZE(a);
4840 size_b = Py_SIZE(b);
4841 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4842 Py_INCREF(a);
4843 Py_INCREF(b);
4844 goto simple;
4845 }
4846
4847 /* Initial reduction: make sure that 0 <= b <= a. */
4848 a = (PyLongObject *)long_abs(a);
4849 if (a == NULL)
4850 return NULL;
4851 b = (PyLongObject *)long_abs(b);
4852 if (b == NULL) {
4853 Py_DECREF(a);
4854 return NULL;
4855 }
4856 if (long_compare(a, b) < 0) {
4857 r = a;
4858 a = b;
4859 b = r;
4860 }
4861 /* We now own references to a and b */
4862
4863 alloc_a = Py_SIZE(a);
4864 alloc_b = Py_SIZE(b);
4865 /* reduce until a fits into 2 digits */
4866 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004867 nbits = _Py_bit_length(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004868 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4869 corresponding bits of b into y */
4870 size_b = Py_SIZE(b);
4871 assert(size_b <= size_a);
4872 if (size_b == 0) {
4873 if (size_a < alloc_a) {
4874 r = (PyLongObject *)_PyLong_Copy(a);
4875 Py_DECREF(a);
4876 }
4877 else
4878 r = a;
4879 Py_DECREF(b);
4880 Py_XDECREF(c);
4881 Py_XDECREF(d);
4882 return (PyObject *)r;
4883 }
4884 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4885 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4886 (a->ob_digit[size_a-3] >> nbits));
4887
4888 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4889 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4890 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4891
4892 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4893 larger than PyLong_MASK during the algorithm. */
4894 A = 1; B = 0; C = 0; D = 1;
4895 for (k=0;; k++) {
4896 if (y-C == 0)
4897 break;
4898 q = (x+(A-1))/(y-C);
4899 s = B+q*D;
4900 t = x-q*y;
4901 if (s > t)
4902 break;
4903 x = y; y = t;
4904 t = A+q*C; A = D; B = C; C = s; D = t;
4905 }
4906
4907 if (k == 0) {
4908 /* no progress; do a Euclidean step */
4909 if (l_divmod(a, b, NULL, &r) < 0)
4910 goto error;
4911 Py_DECREF(a);
4912 a = b;
4913 b = r;
4914 alloc_a = alloc_b;
4915 alloc_b = Py_SIZE(b);
4916 continue;
4917 }
4918
4919 /*
4920 a, b = A*b-B*a, D*a-C*b if k is odd
4921 a, b = A*a-B*b, D*b-C*a if k is even
4922 */
4923 if (k&1) {
4924 T = -A; A = -B; B = T;
4925 T = -C; C = -D; D = T;
4926 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004927 if (c != NULL) {
4928 Py_SET_SIZE(c, size_a);
4929 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004930 else if (Py_REFCNT(a) == 1) {
4931 Py_INCREF(a);
4932 c = a;
4933 }
4934 else {
4935 alloc_a = size_a;
4936 c = _PyLong_New(size_a);
4937 if (c == NULL)
4938 goto error;
4939 }
4940
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004941 if (d != NULL) {
4942 Py_SET_SIZE(d, size_a);
4943 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004944 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4945 Py_INCREF(b);
4946 d = b;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004947 Py_SET_SIZE(d, size_a);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004948 }
4949 else {
4950 alloc_b = size_a;
4951 d = _PyLong_New(size_a);
4952 if (d == NULL)
4953 goto error;
4954 }
4955 a_end = a->ob_digit + size_a;
4956 b_end = b->ob_digit + size_b;
4957
4958 /* compute new a and new b in parallel */
4959 a_digit = a->ob_digit;
4960 b_digit = b->ob_digit;
4961 c_digit = c->ob_digit;
4962 d_digit = d->ob_digit;
4963 c_carry = 0;
4964 d_carry = 0;
4965 while (b_digit < b_end) {
4966 c_carry += (A * *a_digit) - (B * *b_digit);
4967 d_carry += (D * *b_digit++) - (C * *a_digit++);
4968 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4969 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4970 c_carry >>= PyLong_SHIFT;
4971 d_carry >>= PyLong_SHIFT;
4972 }
4973 while (a_digit < a_end) {
4974 c_carry += A * *a_digit;
4975 d_carry -= C * *a_digit++;
4976 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4977 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4978 c_carry >>= PyLong_SHIFT;
4979 d_carry >>= PyLong_SHIFT;
4980 }
4981 assert(c_carry == 0);
4982 assert(d_carry == 0);
4983
4984 Py_INCREF(c);
4985 Py_INCREF(d);
4986 Py_DECREF(a);
4987 Py_DECREF(b);
4988 a = long_normalize(c);
4989 b = long_normalize(d);
4990 }
4991 Py_XDECREF(c);
4992 Py_XDECREF(d);
4993
4994simple:
4995 assert(Py_REFCNT(a) > 0);
4996 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004997/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4998 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4999#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005000 /* a fits into a long, so b must too */
5001 x = PyLong_AsLong((PyObject *)a);
5002 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05005003#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005004 x = PyLong_AsLongLong((PyObject *)a);
5005 y = PyLong_AsLongLong((PyObject *)b);
5006#else
5007# error "_PyLong_GCD"
5008#endif
5009 x = Py_ABS(x);
5010 y = Py_ABS(y);
5011 Py_DECREF(a);
5012 Py_DECREF(b);
5013
5014 /* usual Euclidean algorithm for longs */
5015 while (y != 0) {
5016 t = y;
5017 y = x % y;
5018 x = t;
5019 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005020#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005021 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05005022#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005023 return PyLong_FromLongLong(x);
5024#else
5025# error "_PyLong_GCD"
5026#endif
5027
5028error:
5029 Py_DECREF(a);
5030 Py_DECREF(b);
5031 Py_XDECREF(c);
5032 Py_XDECREF(d);
5033 return NULL;
5034}
5035
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005036static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005037long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 double result;
5040 result = PyLong_AsDouble(v);
5041 if (result == -1.0 && PyErr_Occurred())
5042 return NULL;
5043 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005044}
5045
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005046static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005047long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5048
5049/*[clinic input]
5050@classmethod
5051int.__new__ as long_new
5052 x: object(c_default="NULL") = 0
5053 /
5054 base as obase: object(c_default="NULL") = 10
5055[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005056
Tim Peters6d6c1a32001-08-02 04:15:00 +00005057static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005058long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5059/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005060{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005061 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005064 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005065 if (x == NULL) {
5066 if (obase != NULL) {
5067 PyErr_SetString(PyExc_TypeError,
5068 "int() missing string argument");
5069 return NULL;
5070 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005072 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005073 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005075
Gregory P. Smitha689e522012-12-25 22:38:32 -08005076 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005077 if (base == -1 && PyErr_Occurred())
5078 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005079 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005080 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305081 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005082 return NULL;
5083 }
5084
5085 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005086 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03005088 const char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 if (PyByteArray_Check(x))
5090 string = PyByteArray_AS_STRING(x);
5091 else
5092 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005093 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 }
5095 else {
5096 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005097 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 return NULL;
5099 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005100}
5101
Serhiy Storchaka95949422013-08-27 19:40:23 +03005102/* Wimpy, slow approach to tp_new calls for subtypes of int:
5103 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005104 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005105 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005106*/
5107static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005108long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005110 PyLongObject *tmp, *newobj;
5111 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005114 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 if (tmp == NULL)
5116 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005117 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 n = Py_SIZE(tmp);
5119 if (n < 0)
5120 n = -n;
5121 newobj = (PyLongObject *)type->tp_alloc(type, n);
5122 if (newobj == NULL) {
5123 Py_DECREF(tmp);
5124 return NULL;
5125 }
5126 assert(PyLong_Check(newobj));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005127 Py_SET_SIZE(newobj, Py_SIZE(tmp));
5128 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 newobj->ob_digit[i] = tmp->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005130 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005131 Py_DECREF(tmp);
5132 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005133}
5134
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005135/*[clinic input]
5136int.__getnewargs__
5137[clinic start generated code]*/
5138
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005139static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005140int___getnewargs___impl(PyObject *self)
5141/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005142{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005143 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005144}
5145
Guido van Rossumb43daf72007-08-01 18:08:08 +00005146static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005147long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005150}
5151
5152static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005153long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005155 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005156}
5157
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005158/*[clinic input]
5159int.__format__
5160
5161 format_spec: unicode
5162 /
5163[clinic start generated code]*/
5164
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005165static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005166int___format___impl(PyObject *self, PyObject *format_spec)
5167/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005168{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005169 _PyUnicodeWriter writer;
5170 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005171
Victor Stinner8f674cc2013-04-17 23:02:17 +02005172 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005173 ret = _PyLong_FormatAdvancedWriter(
5174 &writer,
5175 self,
5176 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5177 if (ret == -1) {
5178 _PyUnicodeWriter_Dealloc(&writer);
5179 return NULL;
5180 }
5181 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005182}
5183
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005184/* Return a pair (q, r) such that a = b * q + r, and
5185 abs(r) <= abs(b)/2, with equality possible only if q is even.
5186 In other words, q == a / b, rounded to the nearest integer using
5187 round-half-to-even. */
5188
5189PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005190_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005191{
5192 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005193 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005194 int quo_is_odd, quo_is_neg;
5195 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005196
5197 /* Equivalent Python code:
5198
5199 def divmod_near(a, b):
5200 q, r = divmod(a, b)
5201 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5202 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5203 # positive, 2 * r < b if b negative.
5204 greater_than_half = 2*r > b if b > 0 else 2*r < b
5205 exactly_half = 2*r == b
5206 if greater_than_half or exactly_half and q % 2 == 1:
5207 q += 1
5208 r -= b
5209 return q, r
5210
5211 */
5212 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5213 PyErr_SetString(PyExc_TypeError,
5214 "non-integer arguments in division");
5215 return NULL;
5216 }
5217
5218 /* Do a and b have different signs? If so, quotient is negative. */
5219 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5220
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005221 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5222 goto error;
5223
5224 /* compare twice the remainder with the divisor, to see
5225 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005226 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005227 if (twice_rem == NULL)
5228 goto error;
5229 if (quo_is_neg) {
5230 temp = long_neg((PyLongObject*)twice_rem);
5231 Py_DECREF(twice_rem);
5232 twice_rem = temp;
5233 if (twice_rem == NULL)
5234 goto error;
5235 }
5236 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5237 Py_DECREF(twice_rem);
5238
5239 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5240 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5241 /* fix up quotient */
5242 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005243 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005244 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005245 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005246 Py_DECREF(quo);
5247 quo = (PyLongObject *)temp;
5248 if (quo == NULL)
5249 goto error;
5250 /* and remainder */
5251 if (quo_is_neg)
5252 temp = long_add(rem, (PyLongObject *)b);
5253 else
5254 temp = long_sub(rem, (PyLongObject *)b);
5255 Py_DECREF(rem);
5256 rem = (PyLongObject *)temp;
5257 if (rem == NULL)
5258 goto error;
5259 }
5260
5261 result = PyTuple_New(2);
5262 if (result == NULL)
5263 goto error;
5264
5265 /* PyTuple_SET_ITEM steals references */
5266 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5267 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005268 return result;
5269
5270 error:
5271 Py_XDECREF(quo);
5272 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005273 return NULL;
5274}
5275
Eric Smith8c663262007-08-25 02:26:07 +00005276static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005277long_round(PyObject *self, PyObject *args)
5278{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005279 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005280
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005281 /* To round an integer m to the nearest 10**n (n positive), we make use of
5282 * the divmod_near operation, defined by:
5283 *
5284 * divmod_near(a, b) = (q, r)
5285 *
5286 * where q is the nearest integer to the quotient a / b (the
5287 * nearest even integer in the case of a tie) and r == a - q * b.
5288 * Hence q * b = a - r is the nearest multiple of b to a,
5289 * preferring even multiples in the case of a tie.
5290 *
5291 * So the nearest multiple of 10**n to m is:
5292 *
5293 * m - divmod_near(m, 10**n)[1].
5294 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5296 return NULL;
5297 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005298 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005299
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005300 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 if (ndigits == NULL)
5302 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005303
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005304 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 if (Py_SIZE(ndigits) >= 0) {
5306 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005307 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005309
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005310 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5311 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005313 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005314 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005315 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005316
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005317 result = PyLong_FromLong(10L);
5318 if (result == NULL) {
5319 Py_DECREF(ndigits);
5320 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005321 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005322
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005323 temp = long_pow(result, ndigits, Py_None);
5324 Py_DECREF(ndigits);
5325 Py_DECREF(result);
5326 result = temp;
5327 if (result == NULL)
5328 return NULL;
5329
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005330 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005331 Py_DECREF(result);
5332 result = temp;
5333 if (result == NULL)
5334 return NULL;
5335
5336 temp = long_sub((PyLongObject *)self,
5337 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5338 Py_DECREF(result);
5339 result = temp;
5340
5341 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005342}
5343
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005344/*[clinic input]
5345int.__sizeof__ -> Py_ssize_t
5346
5347Returns size in memory, in bytes.
5348[clinic start generated code]*/
5349
5350static Py_ssize_t
5351int___sizeof___impl(PyObject *self)
5352/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005355
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005356 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5357 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005358}
5359
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005360/*[clinic input]
5361int.bit_length
5362
5363Number of bits necessary to represent self in binary.
5364
5365>>> bin(37)
5366'0b100101'
5367>>> (37).bit_length()
53686
5369[clinic start generated code]*/
5370
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005371static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005372int_bit_length_impl(PyObject *self)
5373/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005376 Py_ssize_t ndigits;
5377 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005379
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005380 assert(self != NULL);
5381 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005382
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005383 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005384 if (ndigits == 0)
5385 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005386
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005387 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekasc5b79002020-01-16 15:09:19 +01005388 msd_bits = _Py_bit_length(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5391 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 /* expression above may overflow; use Python integers instead */
5394 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5395 if (result == NULL)
5396 return NULL;
5397 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5398 if (x == NULL)
5399 goto error;
5400 y = (PyLongObject *)long_mul(result, x);
5401 Py_DECREF(x);
5402 if (y == NULL)
5403 goto error;
5404 Py_DECREF(result);
5405 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5408 if (x == NULL)
5409 goto error;
5410 y = (PyLongObject *)long_add(result, x);
5411 Py_DECREF(x);
5412 if (y == NULL)
5413 goto error;
5414 Py_DECREF(result);
5415 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005418
Mark Dickinson22b20182010-05-10 21:27:53 +00005419 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 Py_DECREF(result);
5421 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005422}
5423
Christian Heimes53876d92008-04-19 00:31:39 +00005424
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005425/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005426int.as_integer_ratio
5427
5428Return integer ratio.
5429
5430Return a pair of integers, whose ratio is exactly equal to the original int
5431and with a positive denominator.
5432
5433>>> (10).as_integer_ratio()
5434(10, 1)
5435>>> (-10).as_integer_ratio()
5436(-10, 1)
5437>>> (0).as_integer_ratio()
5438(0, 1)
5439[clinic start generated code]*/
5440
5441static PyObject *
5442int_as_integer_ratio_impl(PyObject *self)
5443/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5444{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005445 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005446 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005447 if (numerator == NULL) {
5448 return NULL;
5449 }
5450 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5451 Py_DECREF(numerator);
5452 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005453}
5454
5455/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005456int.to_bytes
5457
5458 length: Py_ssize_t
5459 Length of bytes object to use. An OverflowError is raised if the
5460 integer is not representable with the given number of bytes.
5461 byteorder: unicode
5462 The byte order used to represent the integer. If byteorder is 'big',
5463 the most significant byte is at the beginning of the byte array. If
5464 byteorder is 'little', the most significant byte is at the end of the
5465 byte array. To request the native byte order of the host system, use
5466 `sys.byteorder' as the byte order value.
5467 *
5468 signed as is_signed: bool = False
5469 Determines whether two's complement is used to represent the integer.
5470 If signed is False and a negative integer is given, an OverflowError
5471 is raised.
5472
5473Return an array of bytes representing an integer.
5474[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005475
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005476static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005477int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5478 int is_signed)
5479/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005482 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005483
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005484 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005485 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005486 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 little_endian = 0;
5488 else {
5489 PyErr_SetString(PyExc_ValueError,
5490 "byteorder must be either 'little' or 'big'");
5491 return NULL;
5492 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 if (length < 0) {
5495 PyErr_SetString(PyExc_ValueError,
5496 "length argument must be non-negative");
5497 return NULL;
5498 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005500 bytes = PyBytes_FromStringAndSize(NULL, length);
5501 if (bytes == NULL)
5502 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005503
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005504 if (_PyLong_AsByteArray((PyLongObject *)self,
5505 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 length, little_endian, is_signed) < 0) {
5507 Py_DECREF(bytes);
5508 return NULL;
5509 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005512}
5513
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005514/*[clinic input]
5515@classmethod
5516int.from_bytes
5517
5518 bytes as bytes_obj: object
5519 Holds the array of bytes to convert. The argument must either
5520 support the buffer protocol or be an iterable object producing bytes.
5521 Bytes and bytearray are examples of built-in objects that support the
5522 buffer protocol.
5523 byteorder: unicode
5524 The byte order used to represent the integer. If byteorder is 'big',
5525 the most significant byte is at the beginning of the byte array. If
5526 byteorder is 'little', the most significant byte is at the end of the
5527 byte array. To request the native byte order of the host system, use
5528 `sys.byteorder' as the byte order value.
5529 *
5530 signed as is_signed: bool = False
5531 Indicates whether two's complement is used to represent the integer.
5532
5533Return the integer represented by the given array of bytes.
5534[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005535
5536static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005537int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5538 PyObject *byteorder, int is_signed)
5539/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005542 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005543
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005544 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005546 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 little_endian = 0;
5548 else {
5549 PyErr_SetString(PyExc_ValueError,
5550 "byteorder must be either 'little' or 'big'");
5551 return NULL;
5552 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005553
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005554 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 if (bytes == NULL)
5556 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 long_obj = _PyLong_FromByteArray(
5559 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5560 little_endian, is_signed);
5561 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005562
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005563 if (long_obj != NULL && type != &PyLong_Type) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005564 Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005568}
5569
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005570static PyObject *
5571long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5572{
5573 return long_long(self);
5574}
5575
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005576static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005577 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005578 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005579 INT_BIT_LENGTH_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005580 INT_TO_BYTES_METHODDEF
5581 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005582 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005583 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005585 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005586 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005587 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 "Ceiling of an Integral returns itself."},
5589 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5590 "Rounding an Integral returns itself.\n"
5591 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005592 INT___GETNEWARGS___METHODDEF
5593 INT___FORMAT___METHODDEF
5594 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005596};
5597
Guido van Rossumb43daf72007-08-01 18:08:08 +00005598static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005599 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005600 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005601 "the real part of a complex number",
5602 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005603 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005604 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005605 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005606 NULL},
5607 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005608 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005609 "the numerator of a rational number in lowest terms",
5610 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005611 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005612 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005613 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005614 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005615 {NULL} /* Sentinel */
5616};
5617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005618PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005619"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005620int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005621\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005622Convert a number or string to an integer, or return 0 if no arguments\n\
5623are given. If x is a number, return x.__int__(). For floating point\n\
5624numbers, this truncates towards zero.\n\
5625\n\
5626If x is not a number or if base is given, then x must be a string,\n\
5627bytes, or bytearray instance representing an integer literal in the\n\
5628given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5629by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5630Base 0 means to interpret the base from the string as an integer literal.\n\
5631>>> int('0b100', base=0)\n\
56324");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005633
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005634static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005635 (binaryfunc)long_add, /*nb_add*/
5636 (binaryfunc)long_sub, /*nb_subtract*/
5637 (binaryfunc)long_mul, /*nb_multiply*/
5638 long_mod, /*nb_remainder*/
5639 long_divmod, /*nb_divmod*/
5640 long_pow, /*nb_power*/
5641 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005642 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005643 (unaryfunc)long_abs, /*tp_absolute*/
5644 (inquiry)long_bool, /*tp_bool*/
5645 (unaryfunc)long_invert, /*nb_invert*/
5646 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005647 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005648 long_and, /*nb_and*/
5649 long_xor, /*nb_xor*/
5650 long_or, /*nb_or*/
5651 long_long, /*nb_int*/
5652 0, /*nb_reserved*/
5653 long_float, /*nb_float*/
5654 0, /* nb_inplace_add */
5655 0, /* nb_inplace_subtract */
5656 0, /* nb_inplace_multiply */
5657 0, /* nb_inplace_remainder */
5658 0, /* nb_inplace_power */
5659 0, /* nb_inplace_lshift */
5660 0, /* nb_inplace_rshift */
5661 0, /* nb_inplace_and */
5662 0, /* nb_inplace_xor */
5663 0, /* nb_inplace_or */
5664 long_div, /* nb_floor_divide */
5665 long_true_divide, /* nb_true_divide */
5666 0, /* nb_inplace_floor_divide */
5667 0, /* nb_inplace_true_divide */
5668 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005669};
5670
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005671PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005672 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5673 "int", /* tp_name */
5674 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5675 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005676 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005677 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 0, /* tp_getattr */
5679 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005680 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 long_to_decimal_string, /* tp_repr */
5682 &long_as_number, /* tp_as_number */
5683 0, /* tp_as_sequence */
5684 0, /* tp_as_mapping */
5685 (hashfunc)long_hash, /* tp_hash */
5686 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005687 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 PyObject_GenericGetAttr, /* tp_getattro */
5689 0, /* tp_setattro */
5690 0, /* tp_as_buffer */
5691 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5692 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5693 long_doc, /* tp_doc */
5694 0, /* tp_traverse */
5695 0, /* tp_clear */
5696 long_richcompare, /* tp_richcompare */
5697 0, /* tp_weaklistoffset */
5698 0, /* tp_iter */
5699 0, /* tp_iternext */
5700 long_methods, /* tp_methods */
5701 0, /* tp_members */
5702 long_getset, /* tp_getset */
5703 0, /* tp_base */
5704 0, /* tp_dict */
5705 0, /* tp_descr_get */
5706 0, /* tp_descr_set */
5707 0, /* tp_dictoffset */
5708 0, /* tp_init */
5709 0, /* tp_alloc */
5710 long_new, /* tp_new */
5711 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005712};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005713
Mark Dickinsonbd792642009-03-18 20:06:12 +00005714static PyTypeObject Int_InfoType;
5715
5716PyDoc_STRVAR(int_info__doc__,
5717"sys.int_info\n\
5718\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005719A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005720internal representation of integers. The attributes are read only.");
5721
5722static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005724 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005725 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005726};
5727
5728static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005729 "sys.int_info", /* name */
5730 int_info__doc__, /* doc */
5731 int_info_fields, /* fields */
5732 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005733};
5734
5735PyObject *
5736PyLong_GetInfo(void)
5737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 PyObject* int_info;
5739 int field = 0;
5740 int_info = PyStructSequence_New(&Int_InfoType);
5741 if (int_info == NULL)
5742 return NULL;
5743 PyStructSequence_SET_ITEM(int_info, field++,
5744 PyLong_FromLong(PyLong_SHIFT));
5745 PyStructSequence_SET_ITEM(int_info, field++,
5746 PyLong_FromLong(sizeof(digit)));
5747 if (PyErr_Occurred()) {
5748 Py_CLEAR(int_info);
5749 return NULL;
5750 }
5751 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005752}
5753
Guido van Rossumddefaf32007-01-14 03:31:43 +00005754int
Victor Stinner630c8df2019-12-17 13:02:18 +01005755_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005756{
5757#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005758 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5759 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5760 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005761
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005762 PyLongObject *v = _PyLong_New(1);
5763 if (!v) {
5764 return -1;
5765 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005766
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005767 Py_SET_SIZE(v, size);
Victor Stinner12174a52014-08-15 23:17:38 +02005768 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005769
Victor Stinner630c8df2019-12-17 13:02:18 +01005770 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005771 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005772#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005773
Victor Stinner630c8df2019-12-17 13:02:18 +01005774 if (_Py_IsMainInterpreter(tstate)) {
5775 _PyLong_Zero = PyLong_FromLong(0);
5776 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005777 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005778 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005779
5780 _PyLong_One = PyLong_FromLong(1);
5781 if (_PyLong_One == NULL) {
5782 return 0;
5783 }
5784
5785 /* initialize int_info */
5786 if (Int_InfoType.tp_name == NULL) {
5787 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5788 return 0;
5789 }
5790 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005791 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005794}
5795
5796void
Victor Stinner630c8df2019-12-17 13:02:18 +01005797_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005798{
Victor Stinner630c8df2019-12-17 13:02:18 +01005799 if (_Py_IsMainInterpreter(tstate)) {
5800 Py_CLEAR(_PyLong_One);
5801 Py_CLEAR(_PyLong_Zero);
5802 }
5803
Guido van Rossumddefaf32007-01-14 03:31:43 +00005804#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005805 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005806 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005808#endif
5809}