blob: 5d225cbd2fbdea395f093fc85dd98f43400ded2d [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Victor Stinner630c8df2019-12-17 13:02:18 +01006#include "pycore_pystate.h" /* _Py_IsMainInterpreter() */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00007#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Mark Dickinsonc6300392009-04-20 21:38:00 +00009#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000011#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000012
Serhiy Storchaka495e8802017-02-01 23:12:20 +020013#include "clinic/longobject.c.h"
14/*[clinic input]
15class int "PyObject *" "&PyLong_Type"
16[clinic start generated code]*/
17/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
18
Victor Stinner630c8df2019-12-17 13:02:18 +010019#define NSMALLPOSINTS _PY_NSMALLPOSINTS
20#define NSMALLNEGINTS _PY_NSMALLNEGINTS
Facundo Batista6e6f59b2008-07-24 18:57:11 +000021
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020022_Py_IDENTIFIER(little);
23_Py_IDENTIFIER(big);
24
Mark Dickinsone4416742009-02-15 15:14:57 +000025/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020026#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
27 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 (Py_SIZE(x) == 0 ? (sdigit)0 : \
29 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000030
Serhiy Storchakaba85d692017-03-30 09:09:41 +030031PyObject *_PyLong_Zero = NULL;
32PyObject *_PyLong_One = NULL;
33
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#if NSMALLNEGINTS + NSMALLPOSINTS > 0
animalize6b519982019-09-06 14:00:56 +080035#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050036#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070037
Guido van Rossum7eaf8222007-06-18 17:58:50 +000038static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000039get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000040{
animalize6b519982019-09-06 14:00:56 +080041 assert(IS_SMALL_INT(ival));
Victor Stinner630c8df2019-12-17 13:02:18 +010042 PyThreadState *tstate = _PyThreadState_GET();
43 PyObject *v = (PyObject*)tstate->interp->small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046}
Guido van Rossumddefaf32007-01-14 03:31:43 +000047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000049maybe_small_long(PyLongObject *v)
50{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020051 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080053 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 Py_DECREF(v);
55 return (PyLongObject *)get_small_int(ival);
56 }
57 }
58 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000059}
Guido van Rossumddefaf32007-01-14 03:31:43 +000060#else
animalize6b519982019-09-06 14:00:56 +080061#define IS_SMALL_INT(ival) 0
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050062#define IS_SMALL_UINT(ival) 0
animalize6b519982019-09-06 14:00:56 +080063#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000064#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000065#endif
66
Serhiy Storchaka95949422013-08-27 19:40:23 +030067/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000068 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020069Py_LOCAL_INLINE(void)
70_PyLong_Negate(PyLongObject **x_p)
71{
72 PyLongObject *x;
73
74 x = (PyLongObject *)*x_p;
75 if (Py_REFCNT(x) == 1) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +010076 Py_SET_SIZE(x, -Py_SIZE(x));
Victor Stinner8aed6f12013-07-17 22:31:17 +020077 return;
78 }
79
80 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
81 Py_DECREF(x);
82}
83
Serhiy Storchaka95949422013-08-27 19:40:23 +030084/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000085 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030086 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000087 */
Tim Peters0973b992004-08-29 22:16:50 +000088#define KARATSUBA_CUTOFF 70
89#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000090
Tim Peters47e52ee2004-08-30 02:44:38 +000091/* For exponentiation, use the binary left-to-right algorithm
92 * unless the exponent contains more than FIVEARY_CUTOFF digits.
93 * In that case, do 5 bits at a time. The potential drawback is that
94 * a table of 2**5 intermediate results is computed.
95 */
96#define FIVEARY_CUTOFF 8
97
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000098#define SIGCHECK(PyTryBlock) \
99 do { \
100 if (PyErr_CheckSignals()) PyTryBlock \
101 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000102
Serhiy Storchaka95949422013-08-27 19:40:23 +0300103/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000104 Doesn't attempt to free the storage--in most cases, due to the nature
105 of the algorithms used, this could save at most be one word anyway. */
106
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000107static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200108long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000109{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200110 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 while (i > 0 && v->ob_digit[i-1] == 0)
114 --i;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100115 if (i != j) {
116 Py_SET_SIZE(v, (Py_SIZE(v) < 0) ? -(i) : i);
117 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000119}
120
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200121/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
122 using the nb_int slot, if available. Raise TypeError if either the
123 nb_int slot is not available or the result of the call to nb_int
124 returns something not of type int.
125*/
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200126PyObject *
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200127_PyLong_FromNbInt(PyObject *integral)
128{
129 PyNumberMethods *nb;
130 PyObject *result;
131
132 /* Fast path for the case that we already have an int. */
133 if (PyLong_CheckExact(integral)) {
134 Py_INCREF(integral);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200135 return integral;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200136 }
137
138 nb = Py_TYPE(integral)->tp_as_number;
139 if (nb == NULL || nb->nb_int == NULL) {
140 PyErr_Format(PyExc_TypeError,
141 "an integer is required (got type %.200s)",
142 Py_TYPE(integral)->tp_name);
143 return NULL;
144 }
145
146 /* Convert using the nb_int slot, which should return something
147 of exact type int. */
148 result = nb->nb_int(integral);
149 if (!result || PyLong_CheckExact(result))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200150 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200151 if (!PyLong_Check(result)) {
152 PyErr_Format(PyExc_TypeError,
153 "__int__ returned non-int (type %.200s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100154 Py_TYPE(result)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200155 Py_DECREF(result);
156 return NULL;
157 }
158 /* Issue #17576: warn if 'result' not of exact type int. */
159 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
160 "__int__ returned non-int (type %.200s). "
161 "The ability to return an instance of a strict subclass of int "
162 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100163 Py_TYPE(result)->tp_name)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200164 Py_DECREF(result);
165 return NULL;
166 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200167 return result;
168}
169
170/* Convert the given object to a PyLongObject using the nb_index or
171 nb_int slots, if available (the latter is deprecated).
172 Raise TypeError if either nb_index and nb_int slots are not
173 available or the result of the call to nb_index or nb_int
174 returns something not of type int.
175 Should be replaced with PyNumber_Index after the end of the
176 deprecation period.
177*/
178PyObject *
179_PyLong_FromNbIndexOrNbInt(PyObject *integral)
180{
181 PyNumberMethods *nb;
182 PyObject *result;
183
184 /* Fast path for the case that we already have an int. */
185 if (PyLong_CheckExact(integral)) {
186 Py_INCREF(integral);
187 return integral;
188 }
189
190 nb = Py_TYPE(integral)->tp_as_number;
191 if (nb == NULL || (nb->nb_index == NULL && nb->nb_int == NULL)) {
192 PyErr_Format(PyExc_TypeError,
193 "an integer is required (got type %.200s)",
194 Py_TYPE(integral)->tp_name);
195 return NULL;
196 }
197
198 if (nb->nb_index) {
199 /* Convert using the nb_index slot, which should return something
200 of exact type int. */
201 result = nb->nb_index(integral);
202 if (!result || PyLong_CheckExact(result))
203 return result;
204 if (!PyLong_Check(result)) {
205 PyErr_Format(PyExc_TypeError,
206 "__index__ returned non-int (type %.200s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100207 Py_TYPE(result)->tp_name);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200208 Py_DECREF(result);
209 return NULL;
210 }
211 /* Issue #17576: warn if 'result' not of exact type int. */
212 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
213 "__index__ returned non-int (type %.200s). "
214 "The ability to return an instance of a strict subclass of int "
215 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100216 Py_TYPE(result)->tp_name))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200217 {
218 Py_DECREF(result);
219 return NULL;
220 }
221 return result;
222 }
223
224 result = _PyLong_FromNbInt(integral);
225 if (result && PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
226 "an integer is required (got type %.200s). "
227 "Implicit conversion to integers using __int__ is deprecated, "
228 "and may be removed in a future version of Python.",
229 Py_TYPE(integral)->tp_name))
230 {
231 Py_DECREF(result);
232 return NULL;
233 }
234 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200235}
236
237
Serhiy Storchaka95949422013-08-27 19:40:23 +0300238/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000239 Return NULL and set exception if we run out of memory. */
240
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000241#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000243
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000245_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyLongObject *result;
248 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
249 sizeof(digit)*size. Previous incarnations of this code used
250 sizeof(PyVarObject) instead of the offsetof, but this risks being
251 incorrect in the presence of padding between the PyVarObject header
252 and the digits. */
253 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
254 PyErr_SetString(PyExc_OverflowError,
255 "too many digits in integer");
256 return NULL;
257 }
258 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
259 size*sizeof(digit));
260 if (!result) {
261 PyErr_NoMemory();
262 return NULL;
263 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100264 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000265}
266
Tim Peters64b5ce32001-09-10 20:52:51 +0000267PyObject *
268_PyLong_Copy(PyLongObject *src)
269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 PyLongObject *result;
271 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 assert(src != NULL);
274 i = Py_SIZE(src);
275 if (i < 0)
276 i = -(i);
277 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100278 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800279 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700280 return get_small_int(ival);
281 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 }
283 result = _PyLong_New(i);
284 if (result != NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100285 Py_SET_SIZE(result, Py_SIZE(src));
286 while (--i >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 result->ob_digit[i] = src->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100288 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 }
290 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000291}
292
Serhiy Storchaka95949422013-08-27 19:40:23 +0300293/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000294
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000295PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000296PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 PyLongObject *v;
299 unsigned long abs_ival;
300 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
301 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100302 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000303
animalize6b519982019-09-06 14:00:56 +0800304 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700305 return get_small_int((sdigit)ival);
306 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 if (ival < 0) {
309 /* negate: can't write this as abs_ival = -ival since that
310 invokes undefined behaviour when ival is LONG_MIN */
311 abs_ival = 0U-(unsigned long)ival;
312 sign = -1;
313 }
314 else {
315 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100316 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 /* Fast path for single-digit ints */
320 if (!(abs_ival >> PyLong_SHIFT)) {
321 v = _PyLong_New(1);
322 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100323 Py_SET_SIZE(v, sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 v->ob_digit[0] = Py_SAFE_DOWNCAST(
325 abs_ival, unsigned long, digit);
326 }
327 return (PyObject*)v;
328 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000329
Mark Dickinson249b8982009-04-27 19:41:00 +0000330#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 /* 2 digits */
332 if (!(abs_ival >> 2*PyLong_SHIFT)) {
333 v = _PyLong_New(2);
334 if (v) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100335 Py_SET_SIZE(v, 2 * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 v->ob_digit[0] = Py_SAFE_DOWNCAST(
337 abs_ival & PyLong_MASK, unsigned long, digit);
338 v->ob_digit[1] = Py_SAFE_DOWNCAST(
339 abs_ival >> PyLong_SHIFT, unsigned long, digit);
340 }
341 return (PyObject*)v;
342 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000343#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 /* Larger numbers: loop to determine number of digits */
346 t = abs_ival;
347 while (t) {
348 ++ndigits;
349 t >>= PyLong_SHIFT;
350 }
351 v = _PyLong_New(ndigits);
352 if (v != NULL) {
353 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100354 Py_SET_SIZE(v, ndigits * sign);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 t = abs_ival;
356 while (t) {
357 *p++ = Py_SAFE_DOWNCAST(
358 t & PyLong_MASK, unsigned long, digit);
359 t >>= PyLong_SHIFT;
360 }
361 }
362 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000363}
364
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500365#define PYLONG_FROM_UINT(INT_TYPE, ival) \
366 do { \
367 if (IS_SMALL_UINT(ival)) { \
Victor Stinner6314abc2019-10-01 13:29:53 +0200368 return get_small_int((sdigit)(ival)); \
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500369 } \
370 /* Count the number of Python digits. */ \
371 Py_ssize_t ndigits = 0; \
372 INT_TYPE t = (ival); \
373 while (t) { \
374 ++ndigits; \
375 t >>= PyLong_SHIFT; \
376 } \
377 PyLongObject *v = _PyLong_New(ndigits); \
378 if (v == NULL) { \
379 return NULL; \
380 } \
381 digit *p = v->ob_digit; \
382 while ((ival)) { \
383 *p++ = (digit)((ival) & PyLong_MASK); \
384 (ival) >>= PyLong_SHIFT; \
385 } \
386 return (PyObject *)v; \
387 } while(0)
388
Serhiy Storchaka95949422013-08-27 19:40:23 +0300389/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000390
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000391PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000392PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000393{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500394 PYLONG_FROM_UINT(unsigned long, ival);
395}
Tim Petersce9de2f2001-06-14 04:56:19 +0000396
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500397/* Create a new int object from a C unsigned long long int. */
398
399PyObject *
400PyLong_FromUnsignedLongLong(unsigned long long ival)
401{
402 PYLONG_FROM_UINT(unsigned long long, ival);
403}
404
405/* Create a new int object from a C size_t. */
406
407PyObject *
408PyLong_FromSize_t(size_t ival)
409{
410 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000411}
412
Serhiy Storchaka95949422013-08-27 19:40:23 +0300413/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000414
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 PyLongObject *v;
419 double frac;
420 int i, ndig, expo, neg;
421 neg = 0;
422 if (Py_IS_INFINITY(dval)) {
423 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000424 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 return NULL;
426 }
427 if (Py_IS_NAN(dval)) {
428 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000429 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 return NULL;
431 }
432 if (dval < 0.0) {
433 neg = 1;
434 dval = -dval;
435 }
436 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
437 if (expo <= 0)
438 return PyLong_FromLong(0L);
439 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
440 v = _PyLong_New(ndig);
441 if (v == NULL)
442 return NULL;
443 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
444 for (i = ndig; --i >= 0; ) {
445 digit bits = (digit)frac;
446 v->ob_digit[i] = bits;
447 frac = frac - (double)bits;
448 frac = ldexp(frac, PyLong_SHIFT);
449 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100450 if (neg) {
451 Py_SET_SIZE(v, -(Py_SIZE(v)));
452 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000454}
455
Thomas Wouters89f507f2006-12-13 04:49:30 +0000456/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
457 * anything about what happens when a signed integer operation overflows,
458 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700459 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460 * (unsigned long)LONG_MAX, and for the smallest negative signed long
461 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
462 * However, some other compilers warn about applying unary minus to an
463 * unsigned operand. Hence the weird "0-".
464 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
466#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000467
Serhiy Storchaka95949422013-08-27 19:40:23 +0300468/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100469 method.
470
471 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
472 the result. Otherwise *overflow is 0.
473
474 For other errors (e.g., TypeError), return -1 and set an error condition.
475 In this case *overflow will be 0.
476*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000477
478long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000479PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200482 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 unsigned long x, prev;
484 long res;
485 Py_ssize_t i;
486 int sign;
487 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 *overflow = 0;
490 if (vv == NULL) {
491 PyErr_BadInternalCall();
492 return -1;
493 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000494
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200495 if (PyLong_Check(vv)) {
496 v = (PyLongObject *)vv;
497 }
498 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200499 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200500 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return -1;
502 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 switch (i) {
509 case -1:
510 res = -(sdigit)v->ob_digit[0];
511 break;
512 case 0:
513 res = 0;
514 break;
515 case 1:
516 res = v->ob_digit[0];
517 break;
518 default:
519 sign = 1;
520 x = 0;
521 if (i < 0) {
522 sign = -1;
523 i = -(i);
524 }
525 while (--i >= 0) {
526 prev = x;
527 x = (x << PyLong_SHIFT) | v->ob_digit[i];
528 if ((x >> PyLong_SHIFT) != prev) {
529 *overflow = sign;
530 goto exit;
531 }
532 }
533 /* Haven't lost any bits, but casting to long requires extra
534 * care (see comment above).
535 */
536 if (x <= (unsigned long)LONG_MAX) {
537 res = (long)x * sign;
538 }
539 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
540 res = LONG_MIN;
541 }
542 else {
543 *overflow = sign;
544 /* res is already set to -1 */
545 }
546 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000547 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200549 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 }
551 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000552}
553
Serhiy Storchaka95949422013-08-27 19:40:23 +0300554/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100555 method. Return -1 and set an error if overflow occurs. */
556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000558PyLong_AsLong(PyObject *obj)
559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 int overflow;
561 long result = PyLong_AsLongAndOverflow(obj, &overflow);
562 if (overflow) {
563 /* XXX: could be cute and give a different
564 message for overflow == -1 */
565 PyErr_SetString(PyExc_OverflowError,
566 "Python int too large to convert to C long");
567 }
568 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000569}
570
Serhiy Storchaka95949422013-08-27 19:40:23 +0300571/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200572 method. Return -1 and set an error if overflow occurs. */
573
574int
575_PyLong_AsInt(PyObject *obj)
576{
577 int overflow;
578 long result = PyLong_AsLongAndOverflow(obj, &overflow);
579 if (overflow || result > INT_MAX || result < INT_MIN) {
580 /* XXX: could be cute and give a different
581 message for overflow == -1 */
582 PyErr_SetString(PyExc_OverflowError,
583 "Python int too large to convert to C int");
584 return -1;
585 }
586 return (int)result;
587}
588
Serhiy Storchaka95949422013-08-27 19:40:23 +0300589/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000590 Returns -1 and sets an error condition if overflow occurs. */
591
592Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000593PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200594 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 size_t x, prev;
596 Py_ssize_t i;
597 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (vv == NULL) {
600 PyErr_BadInternalCall();
601 return -1;
602 }
603 if (!PyLong_Check(vv)) {
604 PyErr_SetString(PyExc_TypeError, "an integer is required");
605 return -1;
606 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 v = (PyLongObject *)vv;
609 i = Py_SIZE(v);
610 switch (i) {
611 case -1: return -(sdigit)v->ob_digit[0];
612 case 0: return 0;
613 case 1: return v->ob_digit[0];
614 }
615 sign = 1;
616 x = 0;
617 if (i < 0) {
618 sign = -1;
619 i = -(i);
620 }
621 while (--i >= 0) {
622 prev = x;
623 x = (x << PyLong_SHIFT) | v->ob_digit[i];
624 if ((x >> PyLong_SHIFT) != prev)
625 goto overflow;
626 }
627 /* Haven't lost any bits, but casting to a signed type requires
628 * extra care (see comment above).
629 */
630 if (x <= (size_t)PY_SSIZE_T_MAX) {
631 return (Py_ssize_t)x * sign;
632 }
633 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
634 return PY_SSIZE_T_MIN;
635 }
636 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000637
Mark Dickinson22b20182010-05-10 21:27:53 +0000638 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyErr_SetString(PyExc_OverflowError,
640 "Python int too large to convert to C ssize_t");
641 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000642}
643
Serhiy Storchaka95949422013-08-27 19:40:23 +0300644/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000645 Returns -1 and sets an error condition if overflow occurs. */
646
647unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000648PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000649{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200650 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 unsigned long x, prev;
652 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (vv == NULL) {
655 PyErr_BadInternalCall();
656 return (unsigned long)-1;
657 }
658 if (!PyLong_Check(vv)) {
659 PyErr_SetString(PyExc_TypeError, "an integer is required");
660 return (unsigned long)-1;
661 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 v = (PyLongObject *)vv;
664 i = Py_SIZE(v);
665 x = 0;
666 if (i < 0) {
667 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000668 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 return (unsigned long) -1;
670 }
671 switch (i) {
672 case 0: return 0;
673 case 1: return v->ob_digit[0];
674 }
675 while (--i >= 0) {
676 prev = x;
677 x = (x << PyLong_SHIFT) | v->ob_digit[i];
678 if ((x >> PyLong_SHIFT) != prev) {
679 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100680 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000681 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 return (unsigned long) -1;
683 }
684 }
685 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000686}
687
Serhiy Storchaka95949422013-08-27 19:40:23 +0300688/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200689 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000690
691size_t
692PyLong_AsSize_t(PyObject *vv)
693{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200694 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 size_t x, prev;
696 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (vv == NULL) {
699 PyErr_BadInternalCall();
700 return (size_t) -1;
701 }
702 if (!PyLong_Check(vv)) {
703 PyErr_SetString(PyExc_TypeError, "an integer is required");
704 return (size_t)-1;
705 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 v = (PyLongObject *)vv;
708 i = Py_SIZE(v);
709 x = 0;
710 if (i < 0) {
711 PyErr_SetString(PyExc_OverflowError,
712 "can't convert negative value to size_t");
713 return (size_t) -1;
714 }
715 switch (i) {
716 case 0: return 0;
717 case 1: return v->ob_digit[0];
718 }
719 while (--i >= 0) {
720 prev = x;
721 x = (x << PyLong_SHIFT) | v->ob_digit[i];
722 if ((x >> PyLong_SHIFT) != prev) {
723 PyErr_SetString(PyExc_OverflowError,
724 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200725 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 }
727 }
728 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000729}
730
Serhiy Storchaka95949422013-08-27 19:40:23 +0300731/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000732 Returns -1 and sets an error condition if an error occurs. */
733
Guido van Rossumddefaf32007-01-14 03:31:43 +0000734static unsigned long
735_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000736{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200737 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 unsigned long x;
739 Py_ssize_t i;
740 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 if (vv == NULL || !PyLong_Check(vv)) {
743 PyErr_BadInternalCall();
744 return (unsigned long) -1;
745 }
746 v = (PyLongObject *)vv;
747 i = Py_SIZE(v);
748 switch (i) {
749 case 0: return 0;
750 case 1: return v->ob_digit[0];
751 }
752 sign = 1;
753 x = 0;
754 if (i < 0) {
755 sign = -1;
756 i = -i;
757 }
758 while (--i >= 0) {
759 x = (x << PyLong_SHIFT) | v->ob_digit[i];
760 }
761 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000762}
763
Guido van Rossumddefaf32007-01-14 03:31:43 +0000764unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200765PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 PyLongObject *lo;
768 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000769
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200770 if (op == NULL) {
771 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 return (unsigned long)-1;
773 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000774
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200775 if (PyLong_Check(op)) {
776 return _PyLong_AsUnsignedLongMask(op);
777 }
778
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200779 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (lo == NULL)
781 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200782
783 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
784 Py_DECREF(lo);
785 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000786}
787
Tim Peters5b8132f2003-01-31 15:52:05 +0000788int
789_PyLong_Sign(PyObject *vv)
790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 assert(v != NULL);
794 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000797}
798
Tim Petersbaefd9e2003-01-28 20:37:45 +0000799size_t
800_PyLong_NumBits(PyObject *vv)
801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 PyLongObject *v = (PyLongObject *)vv;
803 size_t result = 0;
804 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200805 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 assert(v != NULL);
808 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200809 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
811 if (ndigits > 0) {
812 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700813 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100815 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Niklas Fiekasc5b79002020-01-16 15:09:19 +0100816 msd_bits = _Py_bit_length(msd);
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200817 if (SIZE_MAX - msd_bits < result)
818 goto Overflow;
819 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 }
821 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000822
Mark Dickinson22b20182010-05-10 21:27:53 +0000823 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
825 "to express in a platform size_t");
826 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000827}
828
Tim Peters2a9b3672001-06-11 21:23:58 +0000829PyObject *
830_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000832{
Mark Dickinson22b20182010-05-10 21:27:53 +0000833 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 int incr; /* direction to move pstartbyte */
835 const unsigned char* pendbyte; /* MSB of bytes */
836 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300837 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyLongObject* v; /* result */
839 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (n == 0)
842 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (little_endian) {
845 pstartbyte = bytes;
846 pendbyte = bytes + n - 1;
847 incr = 1;
848 }
849 else {
850 pstartbyte = bytes + n - 1;
851 pendbyte = bytes;
852 incr = -1;
853 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (is_signed)
856 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200859 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 is positive, and leading 0xff bytes if negative. */
861 {
862 size_t i;
863 const unsigned char* p = pendbyte;
864 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000865 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000868 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 break;
870 }
871 numsignificantbytes = n - i;
872 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
873 actually has 2 significant bytes. OTOH, 0xff0001 ==
874 -0x00ffff, so we wouldn't *need* to bump it there; but we
875 do for 0xffff = -0x0001. To be safe without bothering to
876 check every case, bump it regardless. */
877 if (is_signed && numsignificantbytes < n)
878 ++numsignificantbytes;
879 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000880
Serhiy Storchaka95949422013-08-27 19:40:23 +0300881 /* How many Python int digits do we need? We have
882 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
884 /* catch overflow before it happens */
885 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
886 PyErr_SetString(PyExc_OverflowError,
887 "byte array too long to convert to int");
888 return NULL;
889 }
890 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
891 v = _PyLong_New(ndigits);
892 if (v == NULL)
893 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* Copy the bits over. The tricky parts are computing 2's-comp on
896 the fly for signed numbers, and dealing with the mismatch between
897 8-bit bytes and (probably) 15-bit Python digits.*/
898 {
899 size_t i;
900 twodigits carry = 1; /* for 2's-comp calculation */
901 twodigits accum = 0; /* sliding register */
902 unsigned int accumbits = 0; /* number of bits in accum */
903 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
906 twodigits thisbyte = *p;
907 /* Compute correction for 2's comp, if needed. */
908 if (is_signed) {
909 thisbyte = (0xff ^ thisbyte) + carry;
910 carry = thisbyte >> 8;
911 thisbyte &= 0xff;
912 }
913 /* Because we're going LSB to MSB, thisbyte is
914 more significant than what's already in accum,
915 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200916 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 accumbits += 8;
918 if (accumbits >= PyLong_SHIFT) {
919 /* There's enough to fill a Python digit. */
920 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000921 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 ++idigit;
923 accum >>= PyLong_SHIFT;
924 accumbits -= PyLong_SHIFT;
925 assert(accumbits < PyLong_SHIFT);
926 }
927 }
928 assert(accumbits < PyLong_SHIFT);
929 if (accumbits) {
930 assert(idigit < ndigits);
931 v->ob_digit[idigit] = (digit)accum;
932 ++idigit;
933 }
934 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000935
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100936 Py_SET_SIZE(v, is_signed ? -idigit : idigit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000938}
939
940int
941_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 unsigned char* bytes, size_t n,
943 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000946 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000948 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
950 digit carry; /* for computing 2's-comp */
951 size_t j; /* # bytes filled */
952 unsigned char* p; /* pointer to next byte in bytes */
953 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 if (Py_SIZE(v) < 0) {
958 ndigits = -(Py_SIZE(v));
959 if (!is_signed) {
960 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000961 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return -1;
963 }
964 do_twos_comp = 1;
965 }
966 else {
967 ndigits = Py_SIZE(v);
968 do_twos_comp = 0;
969 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (little_endian) {
972 p = bytes;
973 pincr = 1;
974 }
975 else {
976 p = bytes + n - 1;
977 pincr = -1;
978 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 /* Copy over all the Python digits.
981 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300982 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 normalized. */
984 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
985 j = 0;
986 accum = 0;
987 accumbits = 0;
988 carry = do_twos_comp ? 1 : 0;
989 for (i = 0; i < ndigits; ++i) {
990 digit thisdigit = v->ob_digit[i];
991 if (do_twos_comp) {
992 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
993 carry = thisdigit >> PyLong_SHIFT;
994 thisdigit &= PyLong_MASK;
995 }
996 /* Because we're going LSB to MSB, thisdigit is more
997 significant than what's already in accum, so needs to be
998 prepended to accum. */
999 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 /* The most-significant digit may be (probably is) at least
1002 partly empty. */
1003 if (i == ndigits - 1) {
1004 /* Count # of sign bits -- they needn't be stored,
1005 * although for signed conversion we need later to
1006 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +00001007 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 while (s != 0) {
1009 s >>= 1;
1010 accumbits++;
1011 }
1012 }
1013 else
1014 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 /* Store as many bytes as possible. */
1017 while (accumbits >= 8) {
1018 if (j >= n)
1019 goto Overflow;
1020 ++j;
1021 *p = (unsigned char)(accum & 0xff);
1022 p += pincr;
1023 accumbits -= 8;
1024 accum >>= 8;
1025 }
1026 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* Store the straggler (if any). */
1029 assert(accumbits < 8);
1030 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1031 if (accumbits > 0) {
1032 if (j >= n)
1033 goto Overflow;
1034 ++j;
1035 if (do_twos_comp) {
1036 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +03001037 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 infinite supply of sign bits). */
1039 accum |= (~(twodigits)0) << accumbits;
1040 }
1041 *p = (unsigned char)(accum & 0xff);
1042 p += pincr;
1043 }
1044 else if (j == n && n > 0 && is_signed) {
1045 /* The main loop filled the byte array exactly, so the code
1046 just above didn't get to ensure there's a sign bit, and the
1047 loop below wouldn't add one either. Make sure a sign bit
1048 exists. */
1049 unsigned char msb = *(p - pincr);
1050 int sign_bit_set = msb >= 0x80;
1051 assert(accumbits == 0);
1052 if (sign_bit_set == do_twos_comp)
1053 return 0;
1054 else
1055 goto Overflow;
1056 }
Tim Peters05607ad2001-06-13 21:01:27 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 /* Fill remaining bytes with copies of the sign bit. */
1059 {
1060 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1061 for ( ; j < n; ++j, p += pincr)
1062 *p = signbyte;
1063 }
Tim Peters05607ad2001-06-13 21:01:27 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001066
Mark Dickinson22b20182010-05-10 21:27:53 +00001067 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1069 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001070
Tim Peters2a9b3672001-06-11 21:23:58 +00001071}
1072
Serhiy Storchaka95949422013-08-27 19:40:23 +03001073/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001074
1075PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001076PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001077{
Mark Dickinson91044792012-10-18 19:21:43 +01001078#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001079 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001080#else
1081
Tim Peters70128a12001-06-16 08:48:40 +00001082#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001083# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001084#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001085 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001086#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001087
Guido van Rossum78694d91998-09-18 14:14:13 +00001088}
1089
Serhiy Storchaka95949422013-08-27 19:40:23 +03001090/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001091
1092void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001093PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001094{
Tim Peters70128a12001-06-16 08:48:40 +00001095#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1099 x = PyLong_AsLong(vv);
1100 else
1101 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001102#else
Tim Peters70128a12001-06-16 08:48:40 +00001103
Tim Peters70128a12001-06-16 08:48:40 +00001104#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001105# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001106#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001107 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1110 x = PyLong_AsLongLong(vv);
1111 else
1112 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001113
1114#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (x == -1 && PyErr_Occurred())
1117 return NULL;
1118 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001119}
1120
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001121/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001122 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001123 */
1124
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001125#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001126
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001127/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001128
1129PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001130PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001133 unsigned long long abs_ival;
1134 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 int ndigits = 0;
1136 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001137
animalize6b519982019-09-06 14:00:56 +08001138 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001139 return get_small_int((sdigit)ival);
1140 }
1141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (ival < 0) {
1143 /* avoid signed overflow on negation; see comments
1144 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001145 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 negative = 1;
1147 }
1148 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001149 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 /* Count the number of Python digits.
1153 We used to pick 5 ("big enough for anything"), but that's a
1154 waste of time and space given that 5*15 = 75 bits are rarely
1155 needed. */
1156 t = abs_ival;
1157 while (t) {
1158 ++ndigits;
1159 t >>= PyLong_SHIFT;
1160 }
1161 v = _PyLong_New(ndigits);
1162 if (v != NULL) {
1163 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001164 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 t = abs_ival;
1166 while (t) {
1167 *p++ = (digit)(t & PyLong_MASK);
1168 t >>= PyLong_SHIFT;
1169 }
1170 }
1171 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001172}
1173
Serhiy Storchaka95949422013-08-27 19:40:23 +03001174/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175
1176PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001177PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 PyLongObject *v;
1180 size_t abs_ival;
1181 size_t t; /* unsigned so >> doesn't propagate sign bit */
1182 int ndigits = 0;
1183 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001184
animalize6b519982019-09-06 14:00:56 +08001185 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001186 return get_small_int((sdigit)ival);
1187 }
1188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (ival < 0) {
1190 /* avoid signed overflow when ival = SIZE_T_MIN */
1191 abs_ival = (size_t)(-1-ival)+1;
1192 negative = 1;
1193 }
1194 else {
1195 abs_ival = (size_t)ival;
1196 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 /* Count the number of Python digits. */
1199 t = abs_ival;
1200 while (t) {
1201 ++ndigits;
1202 t >>= PyLong_SHIFT;
1203 }
1204 v = _PyLong_New(ndigits);
1205 if (v != NULL) {
1206 digit *p = v->ob_digit;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01001207 Py_SET_SIZE(v, negative ? -ndigits : ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 t = abs_ival;
1209 while (t) {
1210 *p++ = (digit)(t & PyLong_MASK);
1211 t >>= PyLong_SHIFT;
1212 }
1213 }
1214 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001215}
1216
Serhiy Storchaka95949422013-08-27 19:40:23 +03001217/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001218 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001219
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001220long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001221PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001224 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001226 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (vv == NULL) {
1229 PyErr_BadInternalCall();
1230 return -1;
1231 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001232
1233 if (PyLong_Check(vv)) {
1234 v = (PyLongObject *)vv;
1235 }
1236 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001237 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001238 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001240 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001242
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001243 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001245 case -1:
1246 bytes = -(sdigit)v->ob_digit[0];
1247 break;
1248 case 0:
1249 bytes = 0;
1250 break;
1251 case 1:
1252 bytes = v->ob_digit[0];
1253 break;
1254 default:
1255 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001256 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001258 if (do_decref) {
1259 Py_DECREF(v);
1260 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001261
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001262 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001264 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 else
1266 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001267}
1268
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001269/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001270 Return -1 and set an error if overflow occurs. */
1271
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001272unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001273PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001276 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001278
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001279 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001281 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001283 if (!PyLong_Check(vv)) {
1284 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001285 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001286 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 v = (PyLongObject*)vv;
1289 switch(Py_SIZE(v)) {
1290 case 0: return 0;
1291 case 1: return v->ob_digit[0];
1292 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001293
Mark Dickinson22b20182010-05-10 21:27:53 +00001294 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001295 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001296
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001297 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001299 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 else
1301 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001302}
Tim Petersd1a7da62001-06-13 00:35:57 +00001303
Serhiy Storchaka95949422013-08-27 19:40:23 +03001304/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001305 Returns -1 and sets an error condition if an error occurs. */
1306
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001307static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001308_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001309{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001310 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001311 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 Py_ssize_t i;
1313 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 if (vv == NULL || !PyLong_Check(vv)) {
1316 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001317 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 }
1319 v = (PyLongObject *)vv;
1320 switch(Py_SIZE(v)) {
1321 case 0: return 0;
1322 case 1: return v->ob_digit[0];
1323 }
1324 i = Py_SIZE(v);
1325 sign = 1;
1326 x = 0;
1327 if (i < 0) {
1328 sign = -1;
1329 i = -i;
1330 }
1331 while (--i >= 0) {
1332 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1333 }
1334 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001335}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001336
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001337unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001338PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001341 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001342
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001343 if (op == NULL) {
1344 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001345 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001347
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001348 if (PyLong_Check(op)) {
1349 return _PyLong_AsUnsignedLongLongMask(op);
1350 }
1351
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001352 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001354 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001355
1356 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1357 Py_DECREF(lo);
1358 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001359}
Tim Petersd1a7da62001-06-13 00:35:57 +00001360
Serhiy Storchaka95949422013-08-27 19:40:23 +03001361/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001362 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001363
Mark Dickinson8d48b432011-10-23 20:47:14 +01001364 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1365 the result. Otherwise *overflow is 0.
1366
1367 For other errors (e.g., TypeError), return -1 and set an error condition.
1368 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001369*/
1370
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001371long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001372PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001375 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001376 unsigned long long x, prev;
1377 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 Py_ssize_t i;
1379 int sign;
1380 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 *overflow = 0;
1383 if (vv == NULL) {
1384 PyErr_BadInternalCall();
1385 return -1;
1386 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001387
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001388 if (PyLong_Check(vv)) {
1389 v = (PyLongObject *)vv;
1390 }
1391 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001392 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001393 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 return -1;
1395 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 switch (i) {
1402 case -1:
1403 res = -(sdigit)v->ob_digit[0];
1404 break;
1405 case 0:
1406 res = 0;
1407 break;
1408 case 1:
1409 res = v->ob_digit[0];
1410 break;
1411 default:
1412 sign = 1;
1413 x = 0;
1414 if (i < 0) {
1415 sign = -1;
1416 i = -(i);
1417 }
1418 while (--i >= 0) {
1419 prev = x;
1420 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1421 if ((x >> PyLong_SHIFT) != prev) {
1422 *overflow = sign;
1423 goto exit;
1424 }
1425 }
1426 /* Haven't lost any bits, but casting to long requires extra
1427 * care (see comment above).
1428 */
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001429 if (x <= (unsigned long long)LLONG_MAX) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001430 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 }
1432 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05001433 res = LLONG_MIN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 }
1435 else {
1436 *overflow = sign;
1437 /* res is already set to -1 */
1438 }
1439 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001440 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001442 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 }
1444 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001445}
1446
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001447int
1448_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1449{
1450 unsigned long uval;
1451
1452 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1453 PyErr_SetString(PyExc_ValueError, "value must be positive");
1454 return 0;
1455 }
1456 uval = PyLong_AsUnsignedLong(obj);
1457 if (uval == (unsigned long)-1 && PyErr_Occurred())
1458 return 0;
1459 if (uval > USHRT_MAX) {
1460 PyErr_SetString(PyExc_OverflowError,
1461 "Python int too large for C unsigned short");
1462 return 0;
1463 }
1464
1465 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1466 return 1;
1467}
1468
1469int
1470_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1471{
1472 unsigned long uval;
1473
1474 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1475 PyErr_SetString(PyExc_ValueError, "value must be positive");
1476 return 0;
1477 }
1478 uval = PyLong_AsUnsignedLong(obj);
1479 if (uval == (unsigned long)-1 && PyErr_Occurred())
1480 return 0;
1481 if (uval > UINT_MAX) {
1482 PyErr_SetString(PyExc_OverflowError,
1483 "Python int too large for C unsigned int");
1484 return 0;
1485 }
1486
1487 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1488 return 1;
1489}
1490
1491int
1492_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1493{
1494 unsigned long uval;
1495
1496 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1497 PyErr_SetString(PyExc_ValueError, "value must be positive");
1498 return 0;
1499 }
1500 uval = PyLong_AsUnsignedLong(obj);
1501 if (uval == (unsigned long)-1 && PyErr_Occurred())
1502 return 0;
1503
1504 *(unsigned long *)ptr = uval;
1505 return 1;
1506}
1507
1508int
1509_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1510{
1511 unsigned long long uval;
1512
1513 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1514 PyErr_SetString(PyExc_ValueError, "value must be positive");
1515 return 0;
1516 }
1517 uval = PyLong_AsUnsignedLongLong(obj);
1518 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1519 return 0;
1520
1521 *(unsigned long long *)ptr = uval;
1522 return 1;
1523}
1524
1525int
1526_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1527{
1528 size_t uval;
1529
1530 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1531 PyErr_SetString(PyExc_ValueError, "value must be positive");
1532 return 0;
1533 }
1534 uval = PyLong_AsSize_t(obj);
1535 if (uval == (size_t)-1 && PyErr_Occurred())
1536 return 0;
1537
1538 *(size_t *)ptr = uval;
1539 return 1;
1540}
1541
1542
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001543#define CHECK_BINOP(v,w) \
1544 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001545 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1546 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001547 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001548
Tim Peters877a2122002-08-12 05:09:36 +00001549/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1550 * is modified in place, by adding y to it. Carries are propagated as far as
1551 * x[m-1], and the remaining carry (0 or 1) is returned.
1552 */
1553static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001554v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 Py_ssize_t i;
1557 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 assert(m >= n);
1560 for (i = 0; i < n; ++i) {
1561 carry += x[i] + y[i];
1562 x[i] = carry & PyLong_MASK;
1563 carry >>= PyLong_SHIFT;
1564 assert((carry & 1) == carry);
1565 }
1566 for (; carry && i < m; ++i) {
1567 carry += x[i];
1568 x[i] = carry & PyLong_MASK;
1569 carry >>= PyLong_SHIFT;
1570 assert((carry & 1) == carry);
1571 }
1572 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001573}
1574
1575/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1576 * is modified in place, by subtracting y from it. Borrows are propagated as
1577 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1578 */
1579static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001580v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 Py_ssize_t i;
1583 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 assert(m >= n);
1586 for (i = 0; i < n; ++i) {
1587 borrow = x[i] - y[i] - borrow;
1588 x[i] = borrow & PyLong_MASK;
1589 borrow >>= PyLong_SHIFT;
1590 borrow &= 1; /* keep only 1 sign bit */
1591 }
1592 for (; borrow && i < m; ++i) {
1593 borrow = x[i] - borrow;
1594 x[i] = borrow & PyLong_MASK;
1595 borrow >>= PyLong_SHIFT;
1596 borrow &= 1;
1597 }
1598 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001599}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001600
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001601/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1602 * result in z[0:m], and return the d bits shifted out of the top.
1603 */
1604static digit
1605v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 Py_ssize_t i;
1608 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 assert(0 <= d && d < PyLong_SHIFT);
1611 for (i=0; i < m; i++) {
1612 twodigits acc = (twodigits)a[i] << d | carry;
1613 z[i] = (digit)acc & PyLong_MASK;
1614 carry = (digit)(acc >> PyLong_SHIFT);
1615 }
1616 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001617}
1618
1619/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1620 * result in z[0:m], and return the d bits shifted out of the bottom.
1621 */
1622static digit
1623v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 Py_ssize_t i;
1626 digit carry = 0;
1627 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 assert(0 <= d && d < PyLong_SHIFT);
1630 for (i=m; i-- > 0;) {
1631 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1632 carry = (digit)acc & mask;
1633 z[i] = (digit)(acc >> d);
1634 }
1635 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001636}
1637
Tim Peters212e6142001-07-14 12:23:19 +00001638/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1639 in pout, and returning the remainder. pin and pout point at the LSD.
1640 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001641 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001642 immutable. */
1643
1644static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001645inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 assert(n > 0 && n <= PyLong_MASK);
1650 pin += size;
1651 pout += size;
1652 while (--size >= 0) {
1653 digit hi;
1654 rem = (rem << PyLong_SHIFT) | *--pin;
1655 *--pout = hi = (digit)(rem / n);
1656 rem -= (twodigits)hi * n;
1657 }
1658 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001659}
1660
Serhiy Storchaka95949422013-08-27 19:40:23 +03001661/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001662 (as function result) and the remainder (through *prem).
1663 The sign of a is ignored; n should not be zero. */
1664
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001665static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001666divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001667{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001668 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 assert(n > 0 && n <= PyLong_MASK);
1672 z = _PyLong_New(size);
1673 if (z == NULL)
1674 return NULL;
1675 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1676 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001677}
1678
Serhiy Storchaka95949422013-08-27 19:40:23 +03001679/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001680 string. (Return value is non-shared so that callers can modify the
1681 returned value if necessary.) */
1682
Victor Stinnerd3f08822012-05-29 12:57:52 +02001683static int
1684long_to_decimal_string_internal(PyObject *aa,
1685 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001686 _PyUnicodeWriter *writer,
1687 _PyBytesWriter *bytes_writer,
1688 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001691 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 Py_ssize_t size, strlen, size_a, i, j;
1693 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001695 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001696 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 a = (PyLongObject *)aa;
1699 if (a == NULL || !PyLong_Check(a)) {
1700 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001701 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001703 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 /* quick and dirty upper bound for the number of digits
1707 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 But log2(a) < size_a * PyLong_SHIFT, and
1712 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001713 > 3.3 * _PyLong_DECIMAL_SHIFT
1714
1715 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1716 size_a + size_a / d < size_a + size_a / floor(d),
1717 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1718 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001720 d = (33 * _PyLong_DECIMAL_SHIFT) /
1721 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1722 assert(size_a < PY_SSIZE_T_MAX/2);
1723 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 scratch = _PyLong_New(size);
1725 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001726 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 /* convert array of base _PyLong_BASE digits in pin to an array of
1729 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1730 Volume 2 (3rd edn), section 4.4, Method 1b). */
1731 pin = a->ob_digit;
1732 pout = scratch->ob_digit;
1733 size = 0;
1734 for (i = size_a; --i >= 0; ) {
1735 digit hi = pin[i];
1736 for (j = 0; j < size; j++) {
1737 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1738 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1739 pout[j] = (digit)(z - (twodigits)hi *
1740 _PyLong_DECIMAL_BASE);
1741 }
1742 while (hi) {
1743 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1744 hi /= _PyLong_DECIMAL_BASE;
1745 }
1746 /* check for keyboard interrupt */
1747 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001748 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001749 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001750 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 }
1752 /* pout should have at least one digit, so that the case when a = 0
1753 works correctly */
1754 if (size == 0)
1755 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 /* calculate exact length of output string, and allocate */
1758 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1759 tenpow = 10;
1760 rem = pout[size-1];
1761 while (rem >= tenpow) {
1762 tenpow *= 10;
1763 strlen++;
1764 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001765 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001766 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1767 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001768 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001769 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001770 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001772 else if (bytes_writer) {
1773 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1774 if (*bytes_str == NULL) {
1775 Py_DECREF(scratch);
1776 return -1;
1777 }
1778 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001779 else {
1780 str = PyUnicode_New(strlen, '9');
1781 if (str == NULL) {
1782 Py_DECREF(scratch);
1783 return -1;
1784 }
1785 kind = PyUnicode_KIND(str);
1786 }
1787
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001788#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001789 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001790 /* pout[0] through pout[size-2] contribute exactly \
1791 _PyLong_DECIMAL_SHIFT digits each */ \
1792 for (i=0; i < size - 1; i++) { \
1793 rem = pout[i]; \
1794 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1795 *--p = '0' + rem % 10; \
1796 rem /= 10; \
1797 } \
1798 } \
1799 /* pout[size-1]: always produce at least one decimal digit */ \
1800 rem = pout[i]; \
1801 do { \
1802 *--p = '0' + rem % 10; \
1803 rem /= 10; \
1804 } while (rem != 0); \
1805 \
1806 /* and sign */ \
1807 if (negative) \
1808 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001809 } while (0)
1810
1811#define WRITE_UNICODE_DIGITS(TYPE) \
1812 do { \
1813 if (writer) \
1814 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1815 else \
1816 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1817 \
1818 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001819 \
1820 /* check we've counted correctly */ \
1821 if (writer) \
1822 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1823 else \
1824 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1825 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001828 if (bytes_writer) {
1829 char *p = *bytes_str + strlen;
1830 WRITE_DIGITS(p);
1831 assert(p == *bytes_str);
1832 }
1833 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001834 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001835 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001837 else if (kind == PyUnicode_2BYTE_KIND) {
1838 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001839 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001840 }
1841 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001842 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001843 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001844 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001845 }
1846#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001847#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001850 if (writer) {
1851 writer->pos += strlen;
1852 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001853 else if (bytes_writer) {
1854 (*bytes_str) += strlen;
1855 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001856 else {
1857 assert(_PyUnicode_CheckConsistency(str, 1));
1858 *p_output = (PyObject *)str;
1859 }
1860 return 0;
1861}
1862
1863static PyObject *
1864long_to_decimal_string(PyObject *aa)
1865{
1866 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001867 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001868 return NULL;
1869 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001870}
1871
Serhiy Storchaka95949422013-08-27 19:40:23 +03001872/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001873 which should be one of 2, 8 or 16. Return a string object.
1874 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1875 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001876
Victor Stinnerd3f08822012-05-29 12:57:52 +02001877static int
1878long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001879 PyObject **p_output, _PyUnicodeWriter *writer,
1880 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001881{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001882 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001883 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001884 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001886 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001887 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001889
Victor Stinnerd3f08822012-05-29 12:57:52 +02001890 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 if (a == NULL || !PyLong_Check(a)) {
1892 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001893 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001895 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001896 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 /* Compute a rough upper bound for the length of the string */
1899 switch (base) {
1900 case 16:
1901 bits = 4;
1902 break;
1903 case 8:
1904 bits = 3;
1905 break;
1906 case 2:
1907 bits = 1;
1908 break;
1909 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001910 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001912
Mark Dickinsone2846542012-04-20 21:21:24 +01001913 /* Compute exact length 'sz' of output string. */
1914 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001915 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001916 }
1917 else {
1918 Py_ssize_t size_a_in_bits;
1919 /* Ensure overflow doesn't occur during computation of sz. */
1920 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1921 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001922 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001923 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001924 }
1925 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001926 _Py_bit_length(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001927 /* Allow 1 character for a '-' sign. */
1928 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1929 }
1930 if (alternate) {
1931 /* 2 characters for prefix */
1932 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001933 }
1934
Victor Stinnerd3f08822012-05-29 12:57:52 +02001935 if (writer) {
1936 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1937 return -1;
1938 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001940 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001941 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1942 if (*bytes_str == NULL)
1943 return -1;
1944 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001946 v = PyUnicode_New(sz, 'x');
1947 if (v == NULL)
1948 return -1;
1949 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001951
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001952#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001953 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001954 if (size_a == 0) { \
1955 *--p = '0'; \
1956 } \
1957 else { \
1958 /* JRH: special case for power-of-2 bases */ \
1959 twodigits accum = 0; \
1960 int accumbits = 0; /* # of bits in accum */ \
1961 Py_ssize_t i; \
1962 for (i = 0; i < size_a; ++i) { \
1963 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1964 accumbits += PyLong_SHIFT; \
1965 assert(accumbits >= bits); \
1966 do { \
1967 char cdigit; \
1968 cdigit = (char)(accum & (base - 1)); \
1969 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1970 *--p = cdigit; \
1971 accumbits -= bits; \
1972 accum >>= bits; \
1973 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1974 } \
1975 } \
1976 \
1977 if (alternate) { \
1978 if (base == 16) \
1979 *--p = 'x'; \
1980 else if (base == 8) \
1981 *--p = 'o'; \
1982 else /* (base == 2) */ \
1983 *--p = 'b'; \
1984 *--p = '0'; \
1985 } \
1986 if (negative) \
1987 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001988 } while (0)
1989
1990#define WRITE_UNICODE_DIGITS(TYPE) \
1991 do { \
1992 if (writer) \
1993 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1994 else \
1995 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1996 \
1997 WRITE_DIGITS(p); \
1998 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001999 if (writer) \
2000 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2001 else \
2002 assert(p == (TYPE*)PyUnicode_DATA(v)); \
2003 } while (0)
2004
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002005 if (bytes_writer) {
2006 char *p = *bytes_str + sz;
2007 WRITE_DIGITS(p);
2008 assert(p == *bytes_str);
2009 }
2010 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002011 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002012 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002013 }
2014 else if (kind == PyUnicode_2BYTE_KIND) {
2015 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002016 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002017 }
2018 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002019 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002020 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002021 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002022 }
2023#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002024#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002025
2026 if (writer) {
2027 writer->pos += sz;
2028 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002029 else if (bytes_writer) {
2030 (*bytes_str) += sz;
2031 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002032 else {
2033 assert(_PyUnicode_CheckConsistency(v, 1));
2034 *p_output = v;
2035 }
2036 return 0;
2037}
2038
2039PyObject *
2040_PyLong_Format(PyObject *obj, int base)
2041{
2042 PyObject *str;
2043 int err;
2044 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002045 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002046 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002047 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002048 if (err == -1)
2049 return NULL;
2050 return str;
2051}
2052
2053int
2054_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2055 PyObject *obj,
2056 int base, int alternate)
2057{
2058 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002059 return long_to_decimal_string_internal(obj, NULL, writer,
2060 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002061 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002062 return long_format_binary(obj, base, alternate, NULL, writer,
2063 NULL, NULL);
2064}
2065
2066char*
2067_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2068 PyObject *obj,
2069 int base, int alternate)
2070{
2071 char *str2;
2072 int res;
2073 str2 = str;
2074 if (base == 10)
2075 res = long_to_decimal_string_internal(obj, NULL, NULL,
2076 writer, &str2);
2077 else
2078 res = long_format_binary(obj, base, alternate, NULL, NULL,
2079 writer, &str2);
2080 if (res < 0)
2081 return NULL;
2082 assert(str2 != NULL);
2083 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084}
2085
Thomas Wouters477c8d52006-05-27 19:21:47 +00002086/* Table of digit values for 8-bit string -> integer conversion.
2087 * '0' maps to 0, ..., '9' maps to 9.
2088 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2089 * All other indices map to 37.
2090 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002091 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002092 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002093unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2095 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2096 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2097 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2098 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2099 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2100 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2101 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2102 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2103 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2104 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2105 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2106 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2107 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2108 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2109 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002110};
2111
2112/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002113 * 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 +03002114 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002115 * The point to this routine is that it takes time linear in the number of
2116 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002117 *
2118 * Return values:
2119 * -1 on syntax error (exception needs to be set, *res is untouched)
2120 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002121 */
Brett Cannona721aba2016-09-09 14:57:09 -07002122static int
2123long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002124{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002125 const char *p = *str;
2126 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002127 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002128 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 int bits_per_char;
2130 Py_ssize_t n;
2131 PyLongObject *z;
2132 twodigits accum;
2133 int bits_in_accum;
2134 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2137 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002138 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002140 }
2141 /* count digits and set p to end-of-string */
2142 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2143 if (*p == '_') {
2144 if (prev == '_') {
2145 *str = p - 1;
2146 return -1;
2147 }
2148 } else {
2149 ++digits;
2150 }
2151 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002153 }
2154 if (prev == '_') {
2155 /* Trailing underscore not allowed. */
2156 *str = p - 1;
2157 return -1;
2158 }
2159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002161 /* n <- the number of Python digits needed,
2162 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2163 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyErr_SetString(PyExc_ValueError,
2165 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002166 *res = NULL;
2167 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002169 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002171 if (z == NULL) {
2172 *res = NULL;
2173 return 0;
2174 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002175 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 * from least to most significant in both.
2177 */
2178 accum = 0;
2179 bits_in_accum = 0;
2180 pdigit = z->ob_digit;
2181 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002182 int k;
2183 if (*p == '_') {
2184 continue;
2185 }
2186 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 assert(k >= 0 && k < base);
2188 accum |= (twodigits)k << bits_in_accum;
2189 bits_in_accum += bits_per_char;
2190 if (bits_in_accum >= PyLong_SHIFT) {
2191 *pdigit++ = (digit)(accum & PyLong_MASK);
2192 assert(pdigit - z->ob_digit <= n);
2193 accum >>= PyLong_SHIFT;
2194 bits_in_accum -= PyLong_SHIFT;
2195 assert(bits_in_accum < PyLong_SHIFT);
2196 }
2197 }
2198 if (bits_in_accum) {
2199 assert(bits_in_accum <= PyLong_SHIFT);
2200 *pdigit++ = (digit)accum;
2201 assert(pdigit - z->ob_digit <= n);
2202 }
2203 while (pdigit - z->ob_digit < n)
2204 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002205 *res = long_normalize(z);
2206 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002207}
2208
Serhiy Storchaka95949422013-08-27 19:40:23 +03002209/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002210 * ignored.
2211 *
2212 * If successful, a PyLong object will be returned and 'pend' will be pointing
2213 * to the first unused byte unless it's NULL.
2214 *
2215 * If unsuccessful, NULL will be returned.
2216 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002217PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002218PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002221 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 PyLongObject *z = NULL;
2223 PyObject *strobj;
2224 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 if ((base != 0 && base < 2) || base > 36) {
2227 PyErr_SetString(PyExc_ValueError,
2228 "int() arg 2 must be >= 2 and <= 36");
2229 return NULL;
2230 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002231 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002233 }
2234 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002236 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 else if (*str == '-') {
2238 ++str;
2239 sign = -1;
2240 }
2241 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002242 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002244 }
2245 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002247 }
2248 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002250 }
2251 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002253 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 else {
2255 /* "old" (C-style) octal literal, now invalid.
2256 it might still be zero though */
2257 error_if_nonzero = 1;
2258 base = 10;
2259 }
2260 }
2261 if (str[0] == '0' &&
2262 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2263 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002264 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002266 /* One underscore allowed here. */
2267 if (*str == '_') {
2268 ++str;
2269 }
2270 }
2271 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002272 /* May not start with underscores. */
2273 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002274 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002277 if ((base & (base - 1)) == 0) {
2278 int res = long_from_binary_base(&str, base, &z);
2279 if (res < 0) {
2280 /* Syntax error. */
2281 goto onError;
2282 }
2283 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002285/***
2286Binary bases can be converted in time linear in the number of digits, because
2287Python's representation base is binary. Other bases (including decimal!) use
2288the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002289
Thomas Wouters477c8d52006-05-27 19:21:47 +00002290First some math: the largest integer that can be expressed in N base-B digits
2291is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2292case number of Python digits needed to hold it is the smallest integer n s.t.
2293
2294 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2295 BASE**n >= B**N [taking logs to base BASE]
2296 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2297
2298The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002299this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002300and the result is computed into it.
2301
2302The input string is actually treated as being in base base**i (i.e., i digits
2303are processed at a time), where two more static arrays hold:
2304
2305 convwidth_base[base] = the largest integer i such that base**i <= BASE
2306 convmultmax_base[base] = base ** convwidth_base[base]
2307
2308The first of these is the largest i such that i consecutive input digits
2309must fit in a single Python digit. The second is effectively the input
2310base we're really using.
2311
2312Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2313convmultmax_base[base], the result is "simply"
2314
2315 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2316
2317where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002318
2319Error analysis: as above, the number of Python digits `n` needed is worst-
2320case
2321
2322 n >= N * log(B)/log(BASE)
2323
2324where `N` is the number of input digits in base `B`. This is computed via
2325
2326 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2327
2328below. Two numeric concerns are how much space this can waste, and whether
2329the computed result can be too small. To be concrete, assume BASE = 2**15,
2330which is the default (and it's unlikely anyone changes that).
2331
2332Waste isn't a problem: provided the first input digit isn't 0, the difference
2333between the worst-case input with N digits and the smallest input with N
2334digits is about a factor of B, but B is small compared to BASE so at most
2335one allocated Python digit can remain unused on that count. If
2336N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2337and adding 1 returns a result 1 larger than necessary. However, that can't
2338happen: whenever B is a power of 2, long_from_binary_base() is called
2339instead, and it's impossible for B**i to be an integer power of 2**15 when
2340B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2341an exact integer when B is not a power of 2, since B**i has a prime factor
2342other than 2 in that case, but (2**15)**j's only prime factor is 2).
2343
2344The computed result can be too small if the true value of N*log(B)/log(BASE)
2345is a little bit larger than an exact integer, but due to roundoff errors (in
2346computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2347yields a numeric result a little less than that integer. Unfortunately, "how
2348close can a transcendental function get to an integer over some range?"
2349questions are generally theoretically intractable. Computer analysis via
2350continued fractions is practical: expand log(B)/log(BASE) via continued
2351fractions, giving a sequence i/j of "the best" rational approximations. Then
2352j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2353we can get very close to being in trouble, but very rarely. For example,
235476573 is a denominator in one of the continued-fraction approximations to
2355log(10)/log(2**15), and indeed:
2356
2357 >>> log(10)/log(2**15)*76573
2358 16958.000000654003
2359
2360is very close to an integer. If we were working with IEEE single-precision,
2361rounding errors could kill us. Finding worst cases in IEEE double-precision
2362requires better-than-double-precision log() functions, and Tim didn't bother.
2363Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002364new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002365This should happen extremely rarely, and in fact I don't have a test case
2366that triggers it(!). Instead the code was tested by artificially allocating
2367just 1 digit at the start, so that the copying code was exercised for every
2368digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002369***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002370 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002372 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 int i;
2374 int convwidth;
2375 twodigits convmultmax, convmult;
2376 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002377 const char *scan, *lastdigit;
2378 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 static double log_base_BASE[37] = {0.0e0,};
2381 static int convwidth_base[37] = {0,};
2382 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 if (log_base_BASE[base] == 0.0) {
2385 twodigits convmax = base;
2386 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002387
Mark Dickinson22b20182010-05-10 21:27:53 +00002388 log_base_BASE[base] = (log((double)base) /
2389 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 for (;;) {
2391 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002392 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002394 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 convmax = next;
2396 ++i;
2397 }
2398 convmultmax_base[base] = convmax;
2399 assert(i > 0);
2400 convwidth_base[base] = i;
2401 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 /* Find length of the string of numeric characters. */
2404 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002405 lastdigit = str;
2406
2407 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2408 if (*scan == '_') {
2409 if (prev == '_') {
2410 /* Only one underscore allowed. */
2411 str = lastdigit + 1;
2412 goto onError;
2413 }
2414 }
2415 else {
2416 ++digits;
2417 lastdigit = scan;
2418 }
2419 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002421 }
2422 if (prev == '_') {
2423 /* Trailing underscore not allowed. */
2424 /* Set error pointer to first underscore. */
2425 str = lastdigit + 1;
2426 goto onError;
2427 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002428
Serhiy Storchaka95949422013-08-27 19:40:23 +03002429 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 * integer with this base and length. Note that there's no
2431 * need to initialize z->ob_digit -- no slot is read up before
2432 * being stored into.
2433 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002434 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2435 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002436 /* The same exception as in _PyLong_New(). */
2437 PyErr_SetString(PyExc_OverflowError,
2438 "too many digits in integer");
2439 return NULL;
2440 }
2441 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 /* Uncomment next line to test exceedingly rare copy code */
2443 /* size_z = 1; */
2444 assert(size_z > 0);
2445 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002446 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002448 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002449 Py_SET_SIZE(z, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* `convwidth` consecutive input digits are treated as a single
2452 * digit in base `convmultmax`.
2453 */
2454 convwidth = convwidth_base[base];
2455 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 /* Work ;-) */
2458 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002459 if (*str == '_') {
2460 str++;
2461 continue;
2462 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 /* grab up to convwidth digits from the input string */
2464 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002465 for (i = 1; i < convwidth && str != scan; ++str) {
2466 if (*str == '_') {
2467 continue;
2468 }
2469 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002471 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 assert(c < PyLong_BASE);
2473 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 convmult = convmultmax;
2476 /* Calculate the shift only if we couldn't get
2477 * convwidth digits.
2478 */
2479 if (i != convwidth) {
2480 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002481 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002483 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 /* Multiply z by convmult, and add c. */
2487 pz = z->ob_digit;
2488 pzstop = pz + Py_SIZE(z);
2489 for (; pz < pzstop; ++pz) {
2490 c += (twodigits)*pz * convmult;
2491 *pz = (digit)(c & PyLong_MASK);
2492 c >>= PyLong_SHIFT;
2493 }
2494 /* carry off the current end? */
2495 if (c) {
2496 assert(c < PyLong_BASE);
2497 if (Py_SIZE(z) < size_z) {
2498 *pz = (digit)c;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002499 Py_SET_SIZE(z, Py_SIZE(z) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 }
2501 else {
2502 PyLongObject *tmp;
2503 /* Extremely rare. Get more space. */
2504 assert(Py_SIZE(z) == size_z);
2505 tmp = _PyLong_New(size_z + 1);
2506 if (tmp == NULL) {
2507 Py_DECREF(z);
2508 return NULL;
2509 }
2510 memcpy(tmp->ob_digit,
2511 z->ob_digit,
2512 sizeof(digit) * size_z);
2513 Py_DECREF(z);
2514 z = tmp;
2515 z->ob_digit[size_z] = (digit)c;
2516 ++size_z;
2517 }
2518 }
2519 }
2520 }
Brett Cannona721aba2016-09-09 14:57:09 -07002521 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002523 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 if (error_if_nonzero) {
2525 /* reset the base to 0, else the exception message
2526 doesn't make too much sense */
2527 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002528 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002530 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 /* there might still be other problems, therefore base
2532 remains zero here for the same reason */
2533 }
Brett Cannona721aba2016-09-09 14:57:09 -07002534 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002536 }
2537 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002538 Py_SET_SIZE(z, -(Py_SIZE(z)));
Brett Cannona721aba2016-09-09 14:57:09 -07002539 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002540 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002542 }
2543 if (*str != '\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 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002547 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002548 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002549 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002550 }
2551 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002552 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002553 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002554 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002555
Mark Dickinson22b20182010-05-10 21:27:53 +00002556 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002557 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002558 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002559 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 Py_XDECREF(z);
2561 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2562 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002563 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002565 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002567 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 base, strobj);
2569 Py_DECREF(strobj);
2570 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002571}
2572
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002573/* Since PyLong_FromString doesn't have a length parameter,
2574 * check here for possible NULs in the string.
2575 *
2576 * Reports an invalid literal as a bytes object.
2577 */
2578PyObject *
2579_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2580{
2581 PyObject *result, *strobj;
2582 char *end = NULL;
2583
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002584 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002585 if (end == NULL || (result != NULL && end == s + len))
2586 return result;
2587 Py_XDECREF(result);
2588 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2589 if (strobj != NULL) {
2590 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002591 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002592 base, strobj);
2593 Py_DECREF(strobj);
2594 }
2595 return NULL;
2596}
2597
Guido van Rossum9e896b32000-04-05 20:11:21 +00002598PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002599PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002600{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002601 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002602 if (unicode == NULL)
2603 return NULL;
2604 v = PyLong_FromUnicodeObject(unicode, base);
2605 Py_DECREF(unicode);
2606 return v;
2607}
2608
2609PyObject *
2610PyLong_FromUnicodeObject(PyObject *u, int base)
2611{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002612 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002613 const char *buffer;
2614 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002615 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002617 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002618 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002620 assert(PyUnicode_IS_ASCII(asciidig));
2621 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002622 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002623 assert(buffer != NULL);
2624
2625 result = PyLong_FromString(buffer, &end, base);
2626 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002627 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002628 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002630 Py_DECREF(asciidig);
2631 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002632 PyErr_Format(PyExc_ValueError,
2633 "invalid literal for int() with base %d: %.200R",
2634 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002635 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002636}
2637
Tim Peters9f688bf2000-07-07 15:53:28 +00002638/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002639static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002641static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002642
Serhiy Storchaka95949422013-08-27 19:40:23 +03002643/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002644
Guido van Rossume32e0141992-01-19 16:31:05 +00002645static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002646long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002648{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002649 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 if (size_b == 0) {
2653 PyErr_SetString(PyExc_ZeroDivisionError,
2654 "integer division or modulo by zero");
2655 return -1;
2656 }
2657 if (size_a < size_b ||
2658 (size_a == size_b &&
2659 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2660 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002661 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002662 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002663 return -1;
2664 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002665 Py_INCREF(_PyLong_Zero);
2666 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 return 0;
2668 }
2669 if (size_b == 1) {
2670 digit rem = 0;
2671 z = divrem1(a, b->ob_digit[0], &rem);
2672 if (z == NULL)
2673 return -1;
2674 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2675 if (*prem == NULL) {
2676 Py_DECREF(z);
2677 return -1;
2678 }
2679 }
2680 else {
2681 z = x_divrem(a, b, prem);
2682 if (z == NULL)
2683 return -1;
2684 }
2685 /* Set the signs.
2686 The quotient z has the sign of a*b;
2687 the remainder r has the sign of a,
2688 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002689 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2690 _PyLong_Negate(&z);
2691 if (z == NULL) {
2692 Py_CLEAR(*prem);
2693 return -1;
2694 }
2695 }
2696 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2697 _PyLong_Negate(prem);
2698 if (*prem == NULL) {
2699 Py_DECREF(z);
2700 Py_CLEAR(*prem);
2701 return -1;
2702 }
2703 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 *pdiv = maybe_small_long(z);
2705 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002706}
2707
Serhiy Storchaka95949422013-08-27 19:40:23 +03002708/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002709 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002710
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002711static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002712x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 PyLongObject *v, *w, *a;
2715 Py_ssize_t i, k, size_v, size_w;
2716 int d;
2717 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2718 twodigits vv;
2719 sdigit zhi;
2720 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2723 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2724 handle the special case when the initial estimate q for a quotient
2725 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2726 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002729 size_v = Py_ABS(Py_SIZE(v1));
2730 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2732 v = _PyLong_New(size_v+1);
2733 if (v == NULL) {
2734 *prem = NULL;
2735 return NULL;
2736 }
2737 w = _PyLong_New(size_w);
2738 if (w == NULL) {
2739 Py_DECREF(v);
2740 *prem = NULL;
2741 return NULL;
2742 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2745 shift v1 left by the same amount. Results go into w and v. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002746 d = PyLong_SHIFT - _Py_bit_length(w1->ob_digit[size_w-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2748 assert(carry == 0);
2749 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2750 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2751 v->ob_digit[size_v] = carry;
2752 size_v++;
2753 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2756 at most (and usually exactly) k = size_v - size_w digits. */
2757 k = size_v - size_w;
2758 assert(k >= 0);
2759 a = _PyLong_New(k);
2760 if (a == NULL) {
2761 Py_DECREF(w);
2762 Py_DECREF(v);
2763 *prem = NULL;
2764 return NULL;
2765 }
2766 v0 = v->ob_digit;
2767 w0 = w->ob_digit;
2768 wm1 = w0[size_w-1];
2769 wm2 = w0[size_w-2];
2770 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2771 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2772 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002775 Py_DECREF(a);
2776 Py_DECREF(w);
2777 Py_DECREF(v);
2778 *prem = NULL;
2779 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002780 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 /* estimate quotient digit q; may overestimate by 1 (rare) */
2783 vtop = vk[size_w];
2784 assert(vtop <= wm1);
2785 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2786 q = (digit)(vv / wm1);
2787 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2788 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2789 | vk[size_w-2])) {
2790 --q;
2791 r += wm1;
2792 if (r >= PyLong_BASE)
2793 break;
2794 }
2795 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2798 zhi = 0;
2799 for (i = 0; i < size_w; ++i) {
2800 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2801 -PyLong_BASE * q <= z < PyLong_BASE */
2802 z = (sdigit)vk[i] + zhi -
2803 (stwodigits)q * (stwodigits)w0[i];
2804 vk[i] = (digit)z & PyLong_MASK;
2805 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002806 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 /* add w back if q was too large (this branch taken rarely) */
2810 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2811 if ((sdigit)vtop + zhi < 0) {
2812 carry = 0;
2813 for (i = 0; i < size_w; ++i) {
2814 carry += vk[i] + w0[i];
2815 vk[i] = carry & PyLong_MASK;
2816 carry >>= PyLong_SHIFT;
2817 }
2818 --q;
2819 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 /* store quotient digit */
2822 assert(q < PyLong_BASE);
2823 *--ak = q;
2824 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 /* unshift remainder; we reuse w to store the result */
2827 carry = v_rshift(w0, v0, size_w, d);
2828 assert(carry==0);
2829 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 *prem = long_normalize(w);
2832 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002833}
2834
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002835/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2836 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2837 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2838 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2839 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2840 -1.0. */
2841
2842/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2843#if DBL_MANT_DIG == 53
2844#define EXP2_DBL_MANT_DIG 9007199254740992.0
2845#else
2846#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2847#endif
2848
2849double
2850_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2853 /* See below for why x_digits is always large enough. */
2854 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2855 double dx;
2856 /* Correction term for round-half-to-even rounding. For a digit x,
2857 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2858 multiple of 4, rounding ties to a multiple of 8. */
2859 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002860
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002861 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 if (a_size == 0) {
2863 /* Special case for 0: significand 0.0, exponent 0. */
2864 *e = 0;
2865 return 0.0;
2866 }
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002867 a_bits = _Py_bit_length(a->ob_digit[a_size-1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 /* The following is an overflow-free version of the check
2869 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2870 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2871 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2872 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002873 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2877 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 Number of digits needed for result: write // for floor division.
2880 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2889 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2892 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2893 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 in both cases.
2900 */
2901 if (a_bits <= DBL_MANT_DIG + 2) {
2902 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2903 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2904 x_size = 0;
2905 while (x_size < shift_digits)
2906 x_digits[x_size++] = 0;
2907 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2908 (int)shift_bits);
2909 x_size += a_size;
2910 x_digits[x_size++] = rem;
2911 }
2912 else {
2913 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2914 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2915 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2916 a_size - shift_digits, (int)shift_bits);
2917 x_size = a_size - shift_digits;
2918 /* For correct rounding below, we need the least significant
2919 bit of x to be 'sticky' for this shift: if any of the bits
2920 shifted out was nonzero, we set the least significant bit
2921 of x. */
2922 if (rem)
2923 x_digits[0] |= 1;
2924 else
2925 while (shift_digits > 0)
2926 if (a->ob_digit[--shift_digits]) {
2927 x_digits[0] |= 1;
2928 break;
2929 }
2930 }
Victor Stinner63941882011-09-29 00:42:28 +02002931 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 /* Round, and convert to double. */
2934 x_digits[0] += half_even_correction[x_digits[0] & 7];
2935 dx = x_digits[--x_size];
2936 while (x_size > 0)
2937 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 /* Rescale; make correction if result is 1.0. */
2940 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2941 if (dx == 1.0) {
2942 if (a_bits == PY_SSIZE_T_MAX)
2943 goto overflow;
2944 dx = 0.5;
2945 a_bits += 1;
2946 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 *e = a_bits;
2949 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002950
2951 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 /* exponent > PY_SSIZE_T_MAX */
2953 PyErr_SetString(PyExc_OverflowError,
2954 "huge integer: number of bits overflows a Py_ssize_t");
2955 *e = 0;
2956 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002957}
2958
Serhiy Storchaka95949422013-08-27 19:40:23 +03002959/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002960 using the round-half-to-even rule in the case of a tie. */
2961
2962double
2963PyLong_AsDouble(PyObject *v)
2964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 Py_ssize_t exponent;
2966 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002967
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002968 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 PyErr_BadInternalCall();
2970 return -1.0;
2971 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002972 if (!PyLong_Check(v)) {
2973 PyErr_SetString(PyExc_TypeError, "an integer is required");
2974 return -1.0;
2975 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002976 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002977 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002978 to double. This improves performance of FP/long operations
2979 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002980 */
2981 return (double)MEDIUM_VALUE((PyLongObject *)v);
2982 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2984 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2985 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002986 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 return -1.0;
2988 }
2989 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002990}
2991
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002992/* Methods */
2993
HongWeipeng42acb7b2019-09-18 23:10:15 +08002994/* if a < b, return a negative number
2995 if a == b, return 0
2996 if a > b, return a positive number */
2997
2998static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002999long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003000{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003001 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
3002 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003003 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08003004 sdigit diff = 0;
3005 while (--i >= 0) {
3006 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
3007 if (diff) {
3008 break;
3009 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003011 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003013 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003014}
3015
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003016static PyObject *
3017long_richcompare(PyObject *self, PyObject *other, int op)
3018{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003019 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 CHECK_BINOP(self, other);
3021 if (self == other)
3022 result = 0;
3023 else
3024 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003025 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003026}
3027
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003028static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003029long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003030{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003031 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 Py_ssize_t i;
3033 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 i = Py_SIZE(v);
3036 switch(i) {
3037 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3038 case 0: return 0;
3039 case 1: return v->ob_digit[0];
3040 }
3041 sign = 1;
3042 x = 0;
3043 if (i < 0) {
3044 sign = -1;
3045 i = -(i);
3046 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003048 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3049 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3050 _PyHASH_MODULUS.
3051
3052 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3053 amounts to a rotation of the bits of x. To see this, write
3054
3055 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3056
3057 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3058 PyLong_SHIFT bits of x (those that are shifted out of the
3059 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3060 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3061 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3062 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3063 congruent to y modulo _PyHASH_MODULUS. So
3064
3065 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3066
3067 The right-hand side is just the result of rotating the
3068 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3069 not all _PyHASH_BITS bits of x are 1s, the same is true
3070 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3071 the reduction of x*2**PyLong_SHIFT modulo
3072 _PyHASH_MODULUS. */
3073 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3074 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003076 if (x >= _PyHASH_MODULUS)
3077 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 }
3079 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003080 if (x == (Py_uhash_t)-1)
3081 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003082 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003083}
3084
3085
Serhiy Storchaka95949422013-08-27 19:40:23 +03003086/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003087
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003088static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003089x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003090{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003091 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 PyLongObject *z;
3093 Py_ssize_t i;
3094 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 /* Ensure a is the larger of the two: */
3097 if (size_a < size_b) {
3098 { PyLongObject *temp = a; a = b; b = temp; }
3099 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003100 size_a = size_b;
3101 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 }
3103 z = _PyLong_New(size_a+1);
3104 if (z == NULL)
3105 return NULL;
3106 for (i = 0; i < size_b; ++i) {
3107 carry += a->ob_digit[i] + b->ob_digit[i];
3108 z->ob_digit[i] = carry & PyLong_MASK;
3109 carry >>= PyLong_SHIFT;
3110 }
3111 for (; i < size_a; ++i) {
3112 carry += a->ob_digit[i];
3113 z->ob_digit[i] = carry & PyLong_MASK;
3114 carry >>= PyLong_SHIFT;
3115 }
3116 z->ob_digit[i] = carry;
3117 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003118}
3119
3120/* Subtract the absolute values of two integers. */
3121
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003122static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003123x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003124{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003125 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 PyLongObject *z;
3127 Py_ssize_t i;
3128 int sign = 1;
3129 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 /* Ensure a is the larger of the two: */
3132 if (size_a < size_b) {
3133 sign = -1;
3134 { PyLongObject *temp = a; a = b; b = temp; }
3135 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003136 size_a = size_b;
3137 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 }
3139 else if (size_a == size_b) {
3140 /* Find highest digit where a and b differ: */
3141 i = size_a;
3142 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3143 ;
3144 if (i < 0)
3145 return (PyLongObject *)PyLong_FromLong(0);
3146 if (a->ob_digit[i] < b->ob_digit[i]) {
3147 sign = -1;
3148 { PyLongObject *temp = a; a = b; b = temp; }
3149 }
3150 size_a = size_b = i+1;
3151 }
3152 z = _PyLong_New(size_a);
3153 if (z == NULL)
3154 return NULL;
3155 for (i = 0; i < size_b; ++i) {
3156 /* The following assumes unsigned arithmetic
3157 works module 2**N for some N>PyLong_SHIFT. */
3158 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3159 z->ob_digit[i] = borrow & PyLong_MASK;
3160 borrow >>= PyLong_SHIFT;
3161 borrow &= 1; /* Keep only one sign bit */
3162 }
3163 for (; i < size_a; ++i) {
3164 borrow = a->ob_digit[i] - borrow;
3165 z->ob_digit[i] = borrow & PyLong_MASK;
3166 borrow >>= PyLong_SHIFT;
3167 borrow &= 1; /* Keep only one sign bit */
3168 }
3169 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003170 if (sign < 0) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003171 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02003172 }
HongWeipeng036fe852019-11-26 15:54:49 +08003173 return maybe_small_long(long_normalize(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003174}
3175
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003176static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003177long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003182
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003183 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003184 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 }
3186 if (Py_SIZE(a) < 0) {
3187 if (Py_SIZE(b) < 0) {
3188 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003189 if (z != NULL) {
3190 /* x_add received at least one multiple-digit int,
3191 and thus z must be a multiple-digit int.
3192 That also means z is not an element of
3193 small_ints, so negating it in-place is safe. */
3194 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003195 Py_SET_SIZE(z, -(Py_SIZE(z)));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003196 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 }
3198 else
3199 z = x_sub(b, a);
3200 }
3201 else {
3202 if (Py_SIZE(b) < 0)
3203 z = x_sub(a, b);
3204 else
3205 z = x_add(a, b);
3206 }
3207 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003208}
3209
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003210static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003211long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003216
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003217 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003218 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 }
3220 if (Py_SIZE(a) < 0) {
HongWeipeng036fe852019-11-26 15:54:49 +08003221 if (Py_SIZE(b) < 0) {
3222 z = x_sub(b, a);
3223 }
3224 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 z = x_add(a, b);
HongWeipeng036fe852019-11-26 15:54:49 +08003226 if (z != NULL) {
3227 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003228 Py_SET_SIZE(z, -(Py_SIZE(z)));
HongWeipeng036fe852019-11-26 15:54:49 +08003229 }
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003230 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 }
3232 else {
3233 if (Py_SIZE(b) < 0)
3234 z = x_add(a, b);
3235 else
3236 z = x_sub(a, b);
3237 }
3238 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003239}
3240
Tim Peters5af4e6c2002-08-12 02:31:19 +00003241/* Grade school multiplication, ignoring the signs.
3242 * Returns the absolute value of the product, or NULL if error.
3243 */
3244static PyLongObject *
3245x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003248 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3249 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 z = _PyLong_New(size_a + size_b);
3253 if (z == NULL)
3254 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3257 if (a == b) {
3258 /* Efficient squaring per HAC, Algorithm 14.16:
3259 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3260 * Gives slightly less than a 2x speedup when a == b,
3261 * via exploiting that each entry in the multiplication
3262 * pyramid appears twice (except for the size_a squares).
3263 */
3264 for (i = 0; i < size_a; ++i) {
3265 twodigits carry;
3266 twodigits f = a->ob_digit[i];
3267 digit *pz = z->ob_digit + (i << 1);
3268 digit *pa = a->ob_digit + i + 1;
3269 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003272 Py_DECREF(z);
3273 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003274 });
Tim Peters0973b992004-08-29 22:16:50 +00003275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 carry = *pz + f * f;
3277 *pz++ = (digit)(carry & PyLong_MASK);
3278 carry >>= PyLong_SHIFT;
3279 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 /* Now f is added in twice in each column of the
3282 * pyramid it appears. Same as adding f<<1 once.
3283 */
3284 f <<= 1;
3285 while (pa < paend) {
3286 carry += *pz + *pa++ * f;
3287 *pz++ = (digit)(carry & PyLong_MASK);
3288 carry >>= PyLong_SHIFT;
3289 assert(carry <= (PyLong_MASK << 1));
3290 }
3291 if (carry) {
3292 carry += *pz;
3293 *pz++ = (digit)(carry & PyLong_MASK);
3294 carry >>= PyLong_SHIFT;
3295 }
3296 if (carry)
3297 *pz += (digit)(carry & PyLong_MASK);
3298 assert((carry >> PyLong_SHIFT) == 0);
3299 }
3300 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003301 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 for (i = 0; i < size_a; ++i) {
3303 twodigits carry = 0;
3304 twodigits f = a->ob_digit[i];
3305 digit *pz = z->ob_digit + i;
3306 digit *pb = b->ob_digit;
3307 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003310 Py_DECREF(z);
3311 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003312 });
Tim Peters0973b992004-08-29 22:16:50 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 while (pb < pbend) {
3315 carry += *pz + *pb++ * f;
3316 *pz++ = (digit)(carry & PyLong_MASK);
3317 carry >>= PyLong_SHIFT;
3318 assert(carry <= PyLong_MASK);
3319 }
3320 if (carry)
3321 *pz += (digit)(carry & PyLong_MASK);
3322 assert((carry >> PyLong_SHIFT) == 0);
3323 }
3324 }
3325 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003326}
3327
3328/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003329 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003330 split, and sets low and high such that abs(n) == (high << size) + low,
3331 viewing the shift as being by digits. The sign bit is ignored, and
3332 the return values are >= 0.
3333 Returns 0 on success, -1 on failure.
3334*/
3335static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003336kmul_split(PyLongObject *n,
3337 Py_ssize_t size,
3338 PyLongObject **high,
3339 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 PyLongObject *hi, *lo;
3342 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003343 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003344
Victor Stinner640c35c2013-06-04 23:14:37 +02003345 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 if ((hi = _PyLong_New(size_hi)) == NULL)
3349 return -1;
3350 if ((lo = _PyLong_New(size_lo)) == NULL) {
3351 Py_DECREF(hi);
3352 return -1;
3353 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3356 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 *high = long_normalize(hi);
3359 *low = long_normalize(lo);
3360 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003361}
3362
Tim Peters60004642002-08-12 22:01:34 +00003363static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3364
Tim Peters5af4e6c2002-08-12 02:31:19 +00003365/* Karatsuba multiplication. Ignores the input signs, and returns the
3366 * absolute value of the product (or NULL if error).
3367 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3368 */
3369static PyLongObject *
3370k_mul(PyLongObject *a, PyLongObject *b)
3371{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003372 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3373 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 PyLongObject *ah = NULL;
3375 PyLongObject *al = NULL;
3376 PyLongObject *bh = NULL;
3377 PyLongObject *bl = NULL;
3378 PyLongObject *ret = NULL;
3379 PyLongObject *t1, *t2, *t3;
3380 Py_ssize_t shift; /* the number of digits we split off */
3381 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3384 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3385 * Then the original product is
3386 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3387 * By picking X to be a power of 2, "*X" is just shifting, and it's
3388 * been reduced to 3 multiplies on numbers half the size.
3389 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 /* We want to split based on the larger number; fiddle so that b
3392 * is largest.
3393 */
3394 if (asize > bsize) {
3395 t1 = a;
3396 a = b;
3397 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 i = asize;
3400 asize = bsize;
3401 bsize = i;
3402 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 /* Use gradeschool math when either number is too small. */
3405 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3406 if (asize <= i) {
3407 if (asize == 0)
3408 return (PyLongObject *)PyLong_FromLong(0);
3409 else
3410 return x_mul(a, b);
3411 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 /* If a is small compared to b, splitting on b gives a degenerate
3414 * case with ah==0, and Karatsuba may be (even much) less efficient
3415 * than "grade school" then. However, we can still win, by viewing
3416 * b as a string of "big digits", each of width a->ob_size. That
3417 * leads to a sequence of balanced calls to k_mul.
3418 */
3419 if (2 * asize <= bsize)
3420 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 /* Split a & b into hi & lo pieces. */
3423 shift = bsize >> 1;
3424 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3425 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 if (a == b) {
3428 bh = ah;
3429 bl = al;
3430 Py_INCREF(bh);
3431 Py_INCREF(bl);
3432 }
3433 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 /* The plan:
3436 * 1. Allocate result space (asize + bsize digits: that's always
3437 * enough).
3438 * 2. Compute ah*bh, and copy into result at 2*shift.
3439 * 3. Compute al*bl, and copy into result at 0. Note that this
3440 * can't overlap with #2.
3441 * 4. Subtract al*bl from the result, starting at shift. This may
3442 * underflow (borrow out of the high digit), but we don't care:
3443 * we're effectively doing unsigned arithmetic mod
3444 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3445 * borrows and carries out of the high digit can be ignored.
3446 * 5. Subtract ah*bh from the result, starting at shift.
3447 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3448 * at shift.
3449 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 /* 1. Allocate result space. */
3452 ret = _PyLong_New(asize + bsize);
3453 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003454#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 /* Fill with trash, to catch reference to uninitialized digits. */
3456 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003457#endif
Tim Peters44121a62002-08-12 06:17:58 +00003458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3460 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3461 assert(Py_SIZE(t1) >= 0);
3462 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3463 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3464 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 /* Zero-out the digits higher than the ah*bh copy. */
3467 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3468 if (i)
3469 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3470 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 /* 3. t2 <- al*bl, and copy into the low digits. */
3473 if ((t2 = k_mul(al, bl)) == NULL) {
3474 Py_DECREF(t1);
3475 goto fail;
3476 }
3477 assert(Py_SIZE(t2) >= 0);
3478 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3479 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 /* Zero out remaining digits. */
3482 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3483 if (i)
3484 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3487 * because it's fresher in cache.
3488 */
3489 i = Py_SIZE(ret) - shift; /* # digits after shift */
3490 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3491 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3494 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3497 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3498 Py_DECREF(ah);
3499 Py_DECREF(al);
3500 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 if (a == b) {
3503 t2 = t1;
3504 Py_INCREF(t2);
3505 }
3506 else if ((t2 = x_add(bh, bl)) == NULL) {
3507 Py_DECREF(t1);
3508 goto fail;
3509 }
3510 Py_DECREF(bh);
3511 Py_DECREF(bl);
3512 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 t3 = k_mul(t1, t2);
3515 Py_DECREF(t1);
3516 Py_DECREF(t2);
3517 if (t3 == NULL) goto fail;
3518 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 /* Add t3. It's not obvious why we can't run out of room here.
3521 * See the (*) comment after this function.
3522 */
3523 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3524 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003527
Mark Dickinson22b20182010-05-10 21:27:53 +00003528 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 Py_XDECREF(ret);
3530 Py_XDECREF(ah);
3531 Py_XDECREF(al);
3532 Py_XDECREF(bh);
3533 Py_XDECREF(bl);
3534 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003535}
3536
Tim Petersd6974a52002-08-13 20:37:51 +00003537/* (*) Why adding t3 can't "run out of room" above.
3538
Tim Petersab86c2b2002-08-15 20:06:00 +00003539Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3540to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003541
Tim Petersab86c2b2002-08-15 20:06:00 +000035421. For any integer i, i = c(i/2) + f(i/2). In particular,
3543 bsize = c(bsize/2) + f(bsize/2).
35442. shift = f(bsize/2)
35453. asize <= bsize
35464. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3547 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003548
Tim Petersab86c2b2002-08-15 20:06:00 +00003549We allocated asize + bsize result digits, and add t3 into them at an offset
3550of shift. This leaves asize+bsize-shift allocated digit positions for t3
3551to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3552asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003553
Tim Petersab86c2b2002-08-15 20:06:00 +00003554bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3555at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003556
Tim Petersab86c2b2002-08-15 20:06:00 +00003557If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3558digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3559most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003560
Tim Petersab86c2b2002-08-15 20:06:00 +00003561The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003562
Tim Petersab86c2b2002-08-15 20:06:00 +00003563 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003564
Tim Petersab86c2b2002-08-15 20:06:00 +00003565and we have asize + c(bsize/2) available digit positions. We need to show
3566this is always enough. An instance of c(bsize/2) cancels out in both, so
3567the question reduces to whether asize digits is enough to hold
3568(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3569then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3570asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003571digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003572asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003573c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3574is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3575bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003576
Tim Peters48d52c02002-08-14 17:07:32 +00003577Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3578clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3579ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003580*/
3581
Tim Peters60004642002-08-12 22:01:34 +00003582/* b has at least twice the digits of a, and a is big enough that Karatsuba
3583 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3584 * of slices, each with a->ob_size digits, and multiply the slices by a,
3585 * one at a time. This gives k_mul balanced inputs to work with, and is
3586 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003587 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003588 * single-width slice overlap between successive partial sums).
3589 */
3590static PyLongObject *
3591k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3592{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003593 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3594 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 Py_ssize_t nbdone; /* # of b digits already multiplied */
3596 PyLongObject *ret;
3597 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 assert(asize > KARATSUBA_CUTOFF);
3600 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 /* Allocate result space, and zero it out. */
3603 ret = _PyLong_New(asize + bsize);
3604 if (ret == NULL)
3605 return NULL;
3606 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 /* Successive slices of b are copied into bslice. */
3609 bslice = _PyLong_New(asize);
3610 if (bslice == NULL)
3611 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 nbdone = 0;
3614 while (bsize > 0) {
3615 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003616 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 /* Multiply the next slice of b by a. */
3619 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3620 nbtouse * sizeof(digit));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01003621 Py_SET_SIZE(bslice, nbtouse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 product = k_mul(a, bslice);
3623 if (product == NULL)
3624 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 /* Add into result. */
3627 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3628 product->ob_digit, Py_SIZE(product));
3629 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 bsize -= nbtouse;
3632 nbdone += nbtouse;
3633 }
Tim Peters60004642002-08-12 22:01:34 +00003634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 Py_DECREF(bslice);
3636 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003637
Mark Dickinson22b20182010-05-10 21:27:53 +00003638 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 Py_DECREF(ret);
3640 Py_XDECREF(bslice);
3641 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003642}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003643
3644static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003645long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003652 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003654 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 z = k_mul(a, b);
3658 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003659 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3660 _PyLong_Negate(&z);
3661 if (z == NULL)
3662 return NULL;
3663 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003665}
3666
Yury Selivanove0b23092016-02-11 10:26:27 -05003667/* Fast modulo division for single-digit longs. */
3668static PyObject *
3669fast_mod(PyLongObject *a, PyLongObject *b)
3670{
3671 sdigit left = a->ob_digit[0];
3672 sdigit right = b->ob_digit[0];
3673 sdigit mod;
3674
3675 assert(Py_ABS(Py_SIZE(a)) == 1);
3676 assert(Py_ABS(Py_SIZE(b)) == 1);
3677
3678 if (Py_SIZE(a) == Py_SIZE(b)) {
3679 /* 'a' and 'b' have the same sign. */
3680 mod = left % right;
3681 }
3682 else {
3683 /* Either 'a' or 'b' is negative. */
3684 mod = right - 1 - (left - 1) % right;
3685 }
3686
Victor Stinnerf963c132016-03-23 18:36:54 +01003687 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003688}
3689
3690/* Fast floor division for single-digit longs. */
3691static PyObject *
3692fast_floor_div(PyLongObject *a, PyLongObject *b)
3693{
3694 sdigit left = a->ob_digit[0];
3695 sdigit right = b->ob_digit[0];
3696 sdigit div;
3697
3698 assert(Py_ABS(Py_SIZE(a)) == 1);
3699 assert(Py_ABS(Py_SIZE(b)) == 1);
3700
3701 if (Py_SIZE(a) == Py_SIZE(b)) {
3702 /* 'a' and 'b' have the same sign. */
3703 div = left / right;
3704 }
3705 else {
3706 /* Either 'a' or 'b' is negative. */
3707 div = -1 - (left - 1) / right;
3708 }
3709
3710 return PyLong_FromLong(div);
3711}
3712
Guido van Rossume32e0141992-01-19 16:31:05 +00003713/* The / and % operators are now defined in terms of divmod().
3714 The expression a mod b has the value a - b*floor(a/b).
3715 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003716 |a| by |b|, with the sign of a. This is also expressed
3717 as a - b*trunc(a/b), if trunc truncates towards zero.
3718 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 a b a rem b a mod b
3720 13 10 3 3
3721 -13 10 -3 7
3722 13 -10 3 -7
3723 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003724 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003725 have different signs. We then subtract one from the 'div'
3726 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003727
Tim Peters47e52ee2004-08-30 02:44:38 +00003728/* Compute
3729 * *pdiv, *pmod = divmod(v, w)
3730 * NULL can be passed for pdiv or pmod, in which case that part of
3731 * the result is simply thrown away. The caller owns a reference to
3732 * each of these it requests (does not pass NULL for).
3733 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003734static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003735l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003739
Yury Selivanove0b23092016-02-11 10:26:27 -05003740 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3741 /* Fast path for single-digit longs */
3742 div = NULL;
3743 if (pdiv != NULL) {
3744 div = (PyLongObject *)fast_floor_div(v, w);
3745 if (div == NULL) {
3746 return -1;
3747 }
3748 }
3749 if (pmod != NULL) {
3750 mod = (PyLongObject *)fast_mod(v, w);
3751 if (mod == NULL) {
3752 Py_XDECREF(div);
3753 return -1;
3754 }
3755 *pmod = mod;
3756 }
3757 if (pdiv != NULL) {
3758 /* We only want to set `*pdiv` when `*pmod` is
3759 set successfully. */
3760 *pdiv = div;
3761 }
3762 return 0;
3763 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 if (long_divrem(v, w, &div, &mod) < 0)
3765 return -1;
3766 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3767 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3768 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 temp = (PyLongObject *) long_add(mod, w);
3770 Py_DECREF(mod);
3771 mod = temp;
3772 if (mod == NULL) {
3773 Py_DECREF(div);
3774 return -1;
3775 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003776 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3777 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 Py_DECREF(mod);
3779 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 return -1;
3781 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 Py_DECREF(div);
3783 div = temp;
3784 }
3785 if (pdiv != NULL)
3786 *pdiv = div;
3787 else
3788 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 if (pmod != NULL)
3791 *pmod = mod;
3792 else
3793 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003796}
3797
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003798static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003799long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003804
3805 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3806 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3807 }
3808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3810 div = NULL;
3811 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003812}
3813
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003814/* PyLong/PyLong -> float, with correctly rounded result. */
3815
3816#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3817#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3818
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003819static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003820long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 PyLongObject *a, *b, *x;
3823 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3824 digit mask, low;
3825 int inexact, negate, a_is_small, b_is_small;
3826 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 CHECK_BINOP(v, w);
3829 a = (PyLongObject *)v;
3830 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 /*
3833 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3836 1. choose a suitable integer 'shift'
3837 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3838 3. adjust x for correct rounding
3839 4. convert x to a double dx with the same value
3840 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3845 returns either 0.0 or -0.0, depending on the sign of b. For a and
3846 b both nonzero, ignore signs of a and b, and add the sign back in
3847 at the end. Now write a_bits and b_bits for the bit lengths of a
3848 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3849 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3854 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3855 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3856 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 1. The integer 'shift' is chosen so that x has the right number of
3861 bits for a double, plus two or three extra bits that will be used
3862 in the rounding decisions. Writing a_bits and b_bits for the
3863 number of significant bits in a and b respectively, a
3864 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 This is fine in the usual case, but if a/b is smaller than the
3869 smallest normal float then it can lead to double rounding on an
3870 IEEE 754 platform, giving incorrectly rounded results. So we
3871 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 2. The quantity x is computed by first shifting a (left -shift bits
3876 if shift <= 0, right shift bits if shift > 0) and then dividing by
3877 b. For both the shift and the division, we keep track of whether
3878 the result is inexact, in a flag 'inexact'; this information is
3879 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 With the choice of shift above, together with our assumption that
3882 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3883 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3886 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 For float representability, we need x/2**extra_bits <
3891 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3892 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 To round, we just modify the bottom digit of x in-place; this can
3897 end up giving a digit with value > PyLONG_MASK, but that's not a
3898 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 With the original choices for shift above, extra_bits will always
3901 be 2 or 3. Then rounding under the round-half-to-even rule, we
3902 round up iff the most significant of the extra bits is 1, and
3903 either: (a) the computation of x in step 2 had an inexact result,
3904 or (b) at least one other of the extra bits is 1, or (c) the least
3905 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 4. Conversion to a double is straightforward; all floating-point
3908 operations involved in the conversion are exact, so there's no
3909 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3912 The result will always be exactly representable as a double, except
3913 in the case that it overflows. To avoid dependence on the exact
3914 behaviour of ldexp on overflow, we check for overflow before
3915 applying ldexp. The result of ldexp is adjusted for sign before
3916 returning.
3917 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003920 a_size = Py_ABS(Py_SIZE(a));
3921 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3923 if (b_size == 0) {
3924 PyErr_SetString(PyExc_ZeroDivisionError,
3925 "division by zero");
3926 goto error;
3927 }
3928 if (a_size == 0)
3929 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 /* Fast path for a and b small (exactly representable in a double).
3932 Relies on floating-point division being correctly rounded; results
3933 may be subject to double rounding on x86 machines that operate with
3934 the x87 FPU set to 64-bit precision. */
3935 a_is_small = a_size <= MANT_DIG_DIGITS ||
3936 (a_size == MANT_DIG_DIGITS+1 &&
3937 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3938 b_is_small = b_size <= MANT_DIG_DIGITS ||
3939 (b_size == MANT_DIG_DIGITS+1 &&
3940 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3941 if (a_is_small && b_is_small) {
3942 double da, db;
3943 da = a->ob_digit[--a_size];
3944 while (a_size > 0)
3945 da = da * PyLong_BASE + a->ob_digit[--a_size];
3946 db = b->ob_digit[--b_size];
3947 while (b_size > 0)
3948 db = db * PyLong_BASE + b->ob_digit[--b_size];
3949 result = da / db;
3950 goto success;
3951 }
Tim Peterse2a60002001-09-04 06:17:36 +00003952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 /* Catch obvious cases of underflow and overflow */
3954 diff = a_size - b_size;
3955 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3956 /* Extreme overflow */
3957 goto overflow;
3958 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3959 /* Extreme underflow */
3960 goto underflow_or_zero;
3961 /* Next line is now safe from overflowing a Py_ssize_t */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01003962 diff = diff * PyLong_SHIFT + _Py_bit_length(a->ob_digit[a_size - 1]) -
3963 _Py_bit_length(b->ob_digit[b_size - 1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 /* Now diff = a_bits - b_bits. */
3965 if (diff > DBL_MAX_EXP)
3966 goto overflow;
3967 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3968 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003971 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 /* x = abs(a * 2**-shift) */
3976 if (shift <= 0) {
3977 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3978 digit rem;
3979 /* x = a << -shift */
3980 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3981 /* In practice, it's probably impossible to end up
3982 here. Both a and b would have to be enormous,
3983 using close to SIZE_T_MAX bytes of memory each. */
3984 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003985 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 goto error;
3987 }
3988 x = _PyLong_New(a_size + shift_digits + 1);
3989 if (x == NULL)
3990 goto error;
3991 for (i = 0; i < shift_digits; i++)
3992 x->ob_digit[i] = 0;
3993 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3994 a_size, -shift % PyLong_SHIFT);
3995 x->ob_digit[a_size + shift_digits] = rem;
3996 }
3997 else {
3998 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3999 digit rem;
4000 /* x = a >> shift */
4001 assert(a_size >= shift_digits);
4002 x = _PyLong_New(a_size - shift_digits);
4003 if (x == NULL)
4004 goto error;
4005 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4006 a_size - shift_digits, shift % PyLong_SHIFT);
4007 /* set inexact if any of the bits shifted out is nonzero */
4008 if (rem)
4009 inexact = 1;
4010 while (!inexact && shift_digits > 0)
4011 if (a->ob_digit[--shift_digits])
4012 inexact = 1;
4013 }
4014 long_normalize(x);
4015 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4018 reference to x, so it's safe to modify it in-place. */
4019 if (b_size == 1) {
4020 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4021 b->ob_digit[0]);
4022 long_normalize(x);
4023 if (rem)
4024 inexact = 1;
4025 }
4026 else {
4027 PyLongObject *div, *rem;
4028 div = x_divrem(x, b, &rem);
4029 Py_DECREF(x);
4030 x = div;
4031 if (x == NULL)
4032 goto error;
4033 if (Py_SIZE(rem))
4034 inexact = 1;
4035 Py_DECREF(rem);
4036 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004037 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 assert(x_size > 0); /* result of division is never zero */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004039 x_bits = (x_size-1)*PyLong_SHIFT+_Py_bit_length(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004042 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 /* Round by directly modifying the low digit of x. */
4046 mask = (digit)1 << (extra_bits - 1);
4047 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004048 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004050 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 /* Convert x to a double dx; the conversion is exact. */
4053 dx = x->ob_digit[--x_size];
4054 while (x_size > 0)
4055 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4056 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 /* Check whether ldexp result will overflow a double. */
4059 if (shift + x_bits >= DBL_MAX_EXP &&
4060 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4061 goto overflow;
4062 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004063
4064 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004066
4067 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004069
4070 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 PyErr_SetString(PyExc_OverflowError,
4072 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004073 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004075}
4076
4077static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004078long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 CHECK_BINOP(a, b);
4083
Yury Selivanove0b23092016-02-11 10:26:27 -05004084 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4085 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4086 }
4087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4089 mod = NULL;
4090 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004091}
4092
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004093static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004094long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 PyLongObject *div, *mod;
4097 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4102 return NULL;
4103 }
4104 z = PyTuple_New(2);
4105 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004106 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4107 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 }
4109 else {
4110 Py_DECREF(div);
4111 Py_DECREF(mod);
4112 }
4113 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004114}
4115
Mark Dickinsonc5299672019-06-02 10:24:06 +01004116
4117/* Compute an inverse to a modulo n, or raise ValueError if a is not
4118 invertible modulo n. Assumes n is positive. The inverse returned
4119 is whatever falls out of the extended Euclidean algorithm: it may
4120 be either positive or negative, but will be smaller than n in
4121 absolute value.
4122
4123 Pure Python equivalent for long_invmod:
4124
4125 def invmod(a, n):
4126 b, c = 1, 0
4127 while n:
4128 q, r = divmod(a, n)
4129 a, b, c, n = n, c, b - q*c, r
4130
4131 # at this point a is the gcd of the original inputs
4132 if a == 1:
4133 return b
4134 raise ValueError("Not invertible")
4135*/
4136
4137static PyLongObject *
4138long_invmod(PyLongObject *a, PyLongObject *n)
4139{
4140 PyLongObject *b, *c;
4141
4142 /* Should only ever be called for positive n */
4143 assert(Py_SIZE(n) > 0);
4144
4145 b = (PyLongObject *)PyLong_FromLong(1L);
4146 if (b == NULL) {
4147 return NULL;
4148 }
4149 c = (PyLongObject *)PyLong_FromLong(0L);
4150 if (c == NULL) {
4151 Py_DECREF(b);
4152 return NULL;
4153 }
4154 Py_INCREF(a);
4155 Py_INCREF(n);
4156
4157 /* references now owned: a, b, c, n */
4158 while (Py_SIZE(n) != 0) {
4159 PyLongObject *q, *r, *s, *t;
4160
4161 if (l_divmod(a, n, &q, &r) == -1) {
4162 goto Error;
4163 }
4164 Py_DECREF(a);
4165 a = n;
4166 n = r;
4167 t = (PyLongObject *)long_mul(q, c);
4168 Py_DECREF(q);
4169 if (t == NULL) {
4170 goto Error;
4171 }
4172 s = (PyLongObject *)long_sub(b, t);
4173 Py_DECREF(t);
4174 if (s == NULL) {
4175 goto Error;
4176 }
4177 Py_DECREF(b);
4178 b = c;
4179 c = s;
4180 }
4181 /* references now owned: a, b, c, n */
4182
4183 Py_DECREF(c);
4184 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004185 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004186 /* a != 1; we don't have an inverse. */
4187 Py_DECREF(a);
4188 Py_DECREF(b);
4189 PyErr_SetString(PyExc_ValueError,
4190 "base is not invertible for the given modulus");
4191 return NULL;
4192 }
4193 else {
4194 /* a == 1; b gives an inverse modulo n */
4195 Py_DECREF(a);
4196 return b;
4197 }
4198
4199 Error:
4200 Py_DECREF(a);
4201 Py_DECREF(b);
4202 Py_DECREF(c);
4203 Py_DECREF(n);
4204 return NULL;
4205}
4206
4207
Tim Peters47e52ee2004-08-30 02:44:38 +00004208/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004209static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004210long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4213 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 PyLongObject *z = NULL; /* accumulated result */
4216 Py_ssize_t i, j, k; /* counters */
4217 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 /* 5-ary values. If the exponent is large enough, table is
4220 * precomputed so that table[i] == a**i % c for i in range(32).
4221 */
4222 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4223 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 /* a, b, c = v, w, x */
4226 CHECK_BINOP(v, w);
4227 a = (PyLongObject*)v; Py_INCREF(a);
4228 b = (PyLongObject*)w; Py_INCREF(b);
4229 if (PyLong_Check(x)) {
4230 c = (PyLongObject *)x;
4231 Py_INCREF(x);
4232 }
4233 else if (x == Py_None)
4234 c = NULL;
4235 else {
4236 Py_DECREF(a);
4237 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004238 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 }
Tim Peters4c483c42001-09-05 06:24:58 +00004240
Mark Dickinsonc5299672019-06-02 10:24:06 +01004241 if (Py_SIZE(b) < 0 && c == NULL) {
4242 /* if exponent is negative and there's no modulus:
4243 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 that this calls float_pow() which converts its
4245 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004246 Py_DECREF(a);
4247 Py_DECREF(b);
4248 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 if (c) {
4252 /* if modulus == 0:
4253 raise ValueError() */
4254 if (Py_SIZE(c) == 0) {
4255 PyErr_SetString(PyExc_ValueError,
4256 "pow() 3rd argument cannot be 0");
4257 goto Error;
4258 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 /* if modulus < 0:
4261 negativeOutput = True
4262 modulus = -modulus */
4263 if (Py_SIZE(c) < 0) {
4264 negativeOutput = 1;
4265 temp = (PyLongObject *)_PyLong_Copy(c);
4266 if (temp == NULL)
4267 goto Error;
4268 Py_DECREF(c);
4269 c = temp;
4270 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004271 _PyLong_Negate(&c);
4272 if (c == NULL)
4273 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 /* if modulus == 1:
4277 return 0 */
4278 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4279 z = (PyLongObject *)PyLong_FromLong(0L);
4280 goto Done;
4281 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004282
Mark Dickinsonc5299672019-06-02 10:24:06 +01004283 /* if exponent is negative, negate the exponent and
4284 replace the base with a modular inverse */
4285 if (Py_SIZE(b) < 0) {
4286 temp = (PyLongObject *)_PyLong_Copy(b);
4287 if (temp == NULL)
4288 goto Error;
4289 Py_DECREF(b);
4290 b = temp;
4291 temp = NULL;
4292 _PyLong_Negate(&b);
4293 if (b == NULL)
4294 goto Error;
4295
4296 temp = long_invmod(a, c);
4297 if (temp == NULL)
4298 goto Error;
4299 Py_DECREF(a);
4300 a = temp;
4301 }
4302
Tim Peters81a93152013-10-05 16:53:52 -05004303 /* Reduce base by modulus in some cases:
4304 1. If base < 0. Forcing the base non-negative makes things easier.
4305 2. If base is obviously larger than the modulus. The "small
4306 exponent" case later can multiply directly by base repeatedly,
4307 while the "large exponent" case multiplies directly by base 31
4308 times. It can be unboundedly faster to multiply by
4309 base % modulus instead.
4310 We could _always_ do this reduction, but l_divmod() isn't cheap,
4311 so we only do it when it buys something. */
4312 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 if (l_divmod(a, c, NULL, &temp) < 0)
4314 goto Error;
4315 Py_DECREF(a);
4316 a = temp;
4317 temp = NULL;
4318 }
4319 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 /* At this point a, b, and c are guaranteed non-negative UNLESS
4322 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 z = (PyLongObject *)PyLong_FromLong(1L);
4325 if (z == NULL)
4326 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 /* Perform a modular reduction, X = X % c, but leave X alone if c
4329 * is NULL.
4330 */
4331#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004332 do { \
4333 if (c != NULL) { \
4334 if (l_divmod(X, c, NULL, &temp) < 0) \
4335 goto Error; \
4336 Py_XDECREF(X); \
4337 X = temp; \
4338 temp = NULL; \
4339 } \
4340 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 /* Multiply two values, then reduce the result:
4343 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004344#define MULT(X, Y, result) \
4345 do { \
4346 temp = (PyLongObject *)long_mul(X, Y); \
4347 if (temp == NULL) \
4348 goto Error; \
4349 Py_XDECREF(result); \
4350 result = temp; \
4351 temp = NULL; \
4352 REDUCE(result); \
4353 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4356 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4357 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4358 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4359 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004362 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004364 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 }
4366 }
4367 }
4368 else {
4369 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4370 Py_INCREF(z); /* still holds 1L */
4371 table[0] = z;
4372 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004373 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4376 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4379 const int index = (bi >> j) & 0x1f;
4380 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004381 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004383 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 }
4385 }
4386 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 if (negativeOutput && (Py_SIZE(z) != 0)) {
4389 temp = (PyLongObject *)long_sub(z, c);
4390 if (temp == NULL)
4391 goto Error;
4392 Py_DECREF(z);
4393 z = temp;
4394 temp = NULL;
4395 }
4396 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004397
Mark Dickinson22b20182010-05-10 21:27:53 +00004398 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004399 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004401 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4403 for (i = 0; i < 32; ++i)
4404 Py_XDECREF(table[i]);
4405 }
4406 Py_DECREF(a);
4407 Py_DECREF(b);
4408 Py_XDECREF(c);
4409 Py_XDECREF(temp);
4410 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004411}
4412
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004413static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004414long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 /* Implement ~x as -(x+1) */
4417 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004418 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004420 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 if (x == NULL)
4422 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004423 _PyLong_Negate(&x);
4424 /* No need for maybe_small_long here, since any small
4425 longs will have been caught in the Py_SIZE <= 1 fast path. */
4426 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004427}
4428
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004429static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004430long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004433 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 return PyLong_FromLong(-MEDIUM_VALUE(v));
4435 z = (PyLongObject *)_PyLong_Copy(v);
4436 if (z != NULL)
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004437 Py_SET_SIZE(z, -(Py_SIZE(v)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004439}
4440
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004441static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004442long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 if (Py_SIZE(v) < 0)
4445 return long_neg(v);
4446 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004447 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004448}
4449
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004450static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004451long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004454}
4455
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004456/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4457static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004458divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004459{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004460 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004461 assert(Py_SIZE(shiftby) >= 0);
4462 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4463 if (lshiftby >= 0) {
4464 *wordshift = lshiftby / PyLong_SHIFT;
4465 *remshift = lshiftby % PyLong_SHIFT;
4466 return 0;
4467 }
4468 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4469 be that PyLong_AsSsize_t raised an OverflowError. */
4470 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4471 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004472 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004473 if (wordshift_obj == NULL) {
4474 return -1;
4475 }
4476 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4477 Py_DECREF(wordshift_obj);
4478 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4479 return 0;
4480 }
4481 PyErr_Clear();
4482 /* Clip the value. With such large wordshift the right shift
4483 returns 0 and the left shift raises an error in _PyLong_New(). */
4484 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4485 *remshift = 0;
4486 return 0;
4487}
4488
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004489static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004490long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004493 Py_ssize_t newsize, hishift, i, j;
4494 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 if (Py_SIZE(a) < 0) {
4497 /* Right shifting negative numbers is harder */
4498 PyLongObject *a1, *a2;
4499 a1 = (PyLongObject *) long_invert(a);
4500 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004501 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004502 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 Py_DECREF(a1);
4504 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004505 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 z = (PyLongObject *) long_invert(a2);
4507 Py_DECREF(a2);
4508 }
4509 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004510 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 if (newsize <= 0)
4512 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004513 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 lomask = ((digit)1 << hishift) - 1;
4515 himask = PyLong_MASK ^ lomask;
4516 z = _PyLong_New(newsize);
4517 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004518 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004520 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004522 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004524 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004526 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004527}
4528
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004529static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004530long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004531{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004532 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004533 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004536
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004537 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004539 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004541 if (Py_SIZE(a) == 0) {
4542 return PyLong_FromLong(0);
4543 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004544 if (divmod_shift(b, &wordshift, &remshift) < 0)
4545 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004546 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4547}
4548
4549/* Return a >> shiftby. */
4550PyObject *
4551_PyLong_Rshift(PyObject *a, size_t shiftby)
4552{
4553 Py_ssize_t wordshift;
4554 digit remshift;
4555
4556 assert(PyLong_Check(a));
4557 if (Py_SIZE(a) == 0) {
4558 return PyLong_FromLong(0);
4559 }
4560 wordshift = shiftby / PyLong_SHIFT;
4561 remshift = shiftby % PyLong_SHIFT;
4562 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4563}
4564
4565static PyObject *
4566long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4567{
4568 /* This version due to Tim Peters */
4569 PyLongObject *z = NULL;
4570 Py_ssize_t oldsize, newsize, i, j;
4571 twodigits accum;
4572
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004573 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 newsize = oldsize + wordshift;
4575 if (remshift)
4576 ++newsize;
4577 z = _PyLong_New(newsize);
4578 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004579 return NULL;
4580 if (Py_SIZE(a) < 0) {
4581 assert(Py_REFCNT(z) == 1);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004582 Py_SET_SIZE(z, -Py_SIZE(z));
Victor Stinner8aed6f12013-07-17 22:31:17 +02004583 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 for (i = 0; i < wordshift; i++)
4585 z->ob_digit[i] = 0;
4586 accum = 0;
4587 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4588 accum |= (twodigits)a->ob_digit[j] << remshift;
4589 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4590 accum >>= PyLong_SHIFT;
4591 }
4592 if (remshift)
4593 z->ob_digit[newsize-1] = (digit)accum;
4594 else
4595 assert(!accum);
4596 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004598}
4599
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004600static PyObject *
4601long_lshift(PyObject *a, PyObject *b)
4602{
4603 Py_ssize_t wordshift;
4604 digit remshift;
4605
4606 CHECK_BINOP(a, b);
4607
4608 if (Py_SIZE(b) < 0) {
4609 PyErr_SetString(PyExc_ValueError, "negative shift count");
4610 return NULL;
4611 }
4612 if (Py_SIZE(a) == 0) {
4613 return PyLong_FromLong(0);
4614 }
4615 if (divmod_shift(b, &wordshift, &remshift) < 0)
4616 return NULL;
4617 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4618}
4619
4620/* Return a << shiftby. */
4621PyObject *
4622_PyLong_Lshift(PyObject *a, size_t shiftby)
4623{
4624 Py_ssize_t wordshift;
4625 digit remshift;
4626
4627 assert(PyLong_Check(a));
4628 if (Py_SIZE(a) == 0) {
4629 return PyLong_FromLong(0);
4630 }
4631 wordshift = shiftby / PyLong_SHIFT;
4632 remshift = shiftby % PyLong_SHIFT;
4633 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4634}
4635
Mark Dickinson27a87a22009-10-25 20:43:34 +00004636/* Compute two's complement of digit vector a[0:m], writing result to
4637 z[0:m]. The digit vector a need not be normalized, but should not
4638 be entirely zero. a and z may point to the same digit vector. */
4639
4640static void
4641v_complement(digit *z, digit *a, Py_ssize_t m)
4642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 Py_ssize_t i;
4644 digit carry = 1;
4645 for (i = 0; i < m; ++i) {
4646 carry += a[i] ^ PyLong_MASK;
4647 z[i] = carry & PyLong_MASK;
4648 carry >>= PyLong_SHIFT;
4649 }
4650 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004651}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004652
4653/* Bitwise and/xor/or operations */
4654
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004655static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004656long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004657 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004658 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 int nega, negb, negz;
4661 Py_ssize_t size_a, size_b, size_z, i;
4662 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 /* Bitwise operations for negative numbers operate as though
4665 on a two's complement representation. So convert arguments
4666 from sign-magnitude to two's complement, and convert the
4667 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004670 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 nega = Py_SIZE(a) < 0;
4672 if (nega) {
4673 z = _PyLong_New(size_a);
4674 if (z == NULL)
4675 return NULL;
4676 v_complement(z->ob_digit, a->ob_digit, size_a);
4677 a = z;
4678 }
4679 else
4680 /* Keep reference count consistent. */
4681 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004684 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 negb = Py_SIZE(b) < 0;
4686 if (negb) {
4687 z = _PyLong_New(size_b);
4688 if (z == NULL) {
4689 Py_DECREF(a);
4690 return NULL;
4691 }
4692 v_complement(z->ob_digit, b->ob_digit, size_b);
4693 b = z;
4694 }
4695 else
4696 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 /* Swap a and b if necessary to ensure size_a >= size_b. */
4699 if (size_a < size_b) {
4700 z = a; a = b; b = z;
4701 size_z = size_a; size_a = size_b; size_b = size_z;
4702 negz = nega; nega = negb; negb = negz;
4703 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 /* JRH: The original logic here was to allocate the result value (z)
4706 as the longer of the two operands. However, there are some cases
4707 where the result is guaranteed to be shorter than that: AND of two
4708 positives, OR of two negatives: use the shorter number. AND with
4709 mixed signs: use the positive number. OR with mixed signs: use the
4710 negative number.
4711 */
4712 switch (op) {
4713 case '^':
4714 negz = nega ^ negb;
4715 size_z = size_a;
4716 break;
4717 case '&':
4718 negz = nega & negb;
4719 size_z = negb ? size_a : size_b;
4720 break;
4721 case '|':
4722 negz = nega | negb;
4723 size_z = negb ? size_b : size_a;
4724 break;
4725 default:
stratakisa10d4262019-03-18 18:59:20 +01004726 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 /* We allow an extra digit if z is negative, to make sure that
4730 the final two's complement of z doesn't overflow. */
4731 z = _PyLong_New(size_z + negz);
4732 if (z == NULL) {
4733 Py_DECREF(a);
4734 Py_DECREF(b);
4735 return NULL;
4736 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 /* Compute digits for overlap of a and b. */
4739 switch(op) {
4740 case '&':
4741 for (i = 0; i < size_b; ++i)
4742 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4743 break;
4744 case '|':
4745 for (i = 0; i < size_b; ++i)
4746 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4747 break;
4748 case '^':
4749 for (i = 0; i < size_b; ++i)
4750 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4751 break;
4752 default:
stratakisa10d4262019-03-18 18:59:20 +01004753 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 /* Copy any remaining digits of a, inverting if necessary. */
4757 if (op == '^' && negb)
4758 for (; i < size_z; ++i)
4759 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4760 else if (i < size_z)
4761 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4762 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 /* Complement result if negative. */
4765 if (negz) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004766 Py_SET_SIZE(z, -(Py_SIZE(z)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 z->ob_digit[size_z] = PyLong_MASK;
4768 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4769 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771 Py_DECREF(a);
4772 Py_DECREF(b);
4773 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004774}
4775
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004776static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004777long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 PyObject *c;
4780 CHECK_BINOP(a, b);
4781 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4782 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004783}
4784
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004785static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004786long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 PyObject *c;
4789 CHECK_BINOP(a, b);
4790 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4791 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004792}
4793
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004794static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004795long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 PyObject *c;
4798 CHECK_BINOP(a, b);
4799 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4800 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004801}
4802
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004803static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004804long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 if (PyLong_CheckExact(v))
4807 Py_INCREF(v);
4808 else
4809 v = _PyLong_Copy((PyLongObject *)v);
4810 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004811}
4812
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004813PyObject *
4814_PyLong_GCD(PyObject *aarg, PyObject *barg)
4815{
4816 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4817 stwodigits x, y, q, s, t, c_carry, d_carry;
4818 stwodigits A, B, C, D, T;
4819 int nbits, k;
4820 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4821 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4822
4823 a = (PyLongObject *)aarg;
4824 b = (PyLongObject *)barg;
4825 size_a = Py_SIZE(a);
4826 size_b = Py_SIZE(b);
4827 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4828 Py_INCREF(a);
4829 Py_INCREF(b);
4830 goto simple;
4831 }
4832
4833 /* Initial reduction: make sure that 0 <= b <= a. */
4834 a = (PyLongObject *)long_abs(a);
4835 if (a == NULL)
4836 return NULL;
4837 b = (PyLongObject *)long_abs(b);
4838 if (b == NULL) {
4839 Py_DECREF(a);
4840 return NULL;
4841 }
4842 if (long_compare(a, b) < 0) {
4843 r = a;
4844 a = b;
4845 b = r;
4846 }
4847 /* We now own references to a and b */
4848
4849 alloc_a = Py_SIZE(a);
4850 alloc_b = Py_SIZE(b);
4851 /* reduce until a fits into 2 digits */
4852 while ((size_a = Py_SIZE(a)) > 2) {
Niklas Fiekasc5b79002020-01-16 15:09:19 +01004853 nbits = _Py_bit_length(a->ob_digit[size_a-1]);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004854 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4855 corresponding bits of b into y */
4856 size_b = Py_SIZE(b);
4857 assert(size_b <= size_a);
4858 if (size_b == 0) {
4859 if (size_a < alloc_a) {
4860 r = (PyLongObject *)_PyLong_Copy(a);
4861 Py_DECREF(a);
4862 }
4863 else
4864 r = a;
4865 Py_DECREF(b);
4866 Py_XDECREF(c);
4867 Py_XDECREF(d);
4868 return (PyObject *)r;
4869 }
4870 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4871 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4872 (a->ob_digit[size_a-3] >> nbits));
4873
4874 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4875 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4876 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4877
4878 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4879 larger than PyLong_MASK during the algorithm. */
4880 A = 1; B = 0; C = 0; D = 1;
4881 for (k=0;; k++) {
4882 if (y-C == 0)
4883 break;
4884 q = (x+(A-1))/(y-C);
4885 s = B+q*D;
4886 t = x-q*y;
4887 if (s > t)
4888 break;
4889 x = y; y = t;
4890 t = A+q*C; A = D; B = C; C = s; D = t;
4891 }
4892
4893 if (k == 0) {
4894 /* no progress; do a Euclidean step */
4895 if (l_divmod(a, b, NULL, &r) < 0)
4896 goto error;
4897 Py_DECREF(a);
4898 a = b;
4899 b = r;
4900 alloc_a = alloc_b;
4901 alloc_b = Py_SIZE(b);
4902 continue;
4903 }
4904
4905 /*
4906 a, b = A*b-B*a, D*a-C*b if k is odd
4907 a, b = A*a-B*b, D*b-C*a if k is even
4908 */
4909 if (k&1) {
4910 T = -A; A = -B; B = T;
4911 T = -C; C = -D; D = T;
4912 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004913 if (c != NULL) {
4914 Py_SET_SIZE(c, size_a);
4915 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004916 else if (Py_REFCNT(a) == 1) {
4917 Py_INCREF(a);
4918 c = a;
4919 }
4920 else {
4921 alloc_a = size_a;
4922 c = _PyLong_New(size_a);
4923 if (c == NULL)
4924 goto error;
4925 }
4926
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004927 if (d != NULL) {
4928 Py_SET_SIZE(d, size_a);
4929 }
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004930 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4931 Py_INCREF(b);
4932 d = b;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01004933 Py_SET_SIZE(d, size_a);
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004934 }
4935 else {
4936 alloc_b = size_a;
4937 d = _PyLong_New(size_a);
4938 if (d == NULL)
4939 goto error;
4940 }
4941 a_end = a->ob_digit + size_a;
4942 b_end = b->ob_digit + size_b;
4943
4944 /* compute new a and new b in parallel */
4945 a_digit = a->ob_digit;
4946 b_digit = b->ob_digit;
4947 c_digit = c->ob_digit;
4948 d_digit = d->ob_digit;
4949 c_carry = 0;
4950 d_carry = 0;
4951 while (b_digit < b_end) {
4952 c_carry += (A * *a_digit) - (B * *b_digit);
4953 d_carry += (D * *b_digit++) - (C * *a_digit++);
4954 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4955 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4956 c_carry >>= PyLong_SHIFT;
4957 d_carry >>= PyLong_SHIFT;
4958 }
4959 while (a_digit < a_end) {
4960 c_carry += A * *a_digit;
4961 d_carry -= C * *a_digit++;
4962 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4963 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4964 c_carry >>= PyLong_SHIFT;
4965 d_carry >>= PyLong_SHIFT;
4966 }
4967 assert(c_carry == 0);
4968 assert(d_carry == 0);
4969
4970 Py_INCREF(c);
4971 Py_INCREF(d);
4972 Py_DECREF(a);
4973 Py_DECREF(b);
4974 a = long_normalize(c);
4975 b = long_normalize(d);
4976 }
4977 Py_XDECREF(c);
4978 Py_XDECREF(d);
4979
4980simple:
4981 assert(Py_REFCNT(a) > 0);
4982 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004983/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4984 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4985#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004986 /* a fits into a long, so b must too */
4987 x = PyLong_AsLong((PyObject *)a);
4988 y = PyLong_AsLong((PyObject *)b);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05004989#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004990 x = PyLong_AsLongLong((PyObject *)a);
4991 y = PyLong_AsLongLong((PyObject *)b);
4992#else
4993# error "_PyLong_GCD"
4994#endif
4995 x = Py_ABS(x);
4996 y = Py_ABS(y);
4997 Py_DECREF(a);
4998 Py_DECREF(b);
4999
5000 /* usual Euclidean algorithm for longs */
5001 while (y != 0) {
5002 t = y;
5003 y = x % y;
5004 x = t;
5005 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005006#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005007 return PyLong_FromLong(x);
Sergey Fedoseev1f9f69d2019-12-05 19:55:28 +05005008#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005009 return PyLong_FromLongLong(x);
5010#else
5011# error "_PyLong_GCD"
5012#endif
5013
5014error:
5015 Py_DECREF(a);
5016 Py_DECREF(b);
5017 Py_XDECREF(c);
5018 Py_XDECREF(d);
5019 return NULL;
5020}
5021
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005022static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005023long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 double result;
5026 result = PyLong_AsDouble(v);
5027 if (result == -1.0 && PyErr_Occurred())
5028 return NULL;
5029 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005030}
5031
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005032static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005033long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5034
5035/*[clinic input]
5036@classmethod
5037int.__new__ as long_new
5038 x: object(c_default="NULL") = 0
5039 /
5040 base as obase: object(c_default="NULL") = 10
5041[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005042
Tim Peters6d6c1a32001-08-02 04:15:00 +00005043static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005044long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5045/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005046{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005047 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005049 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005050 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005051 if (x == NULL) {
5052 if (obase != NULL) {
5053 PyErr_SetString(PyExc_TypeError,
5054 "int() missing string argument");
5055 return NULL;
5056 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005058 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005059 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005061
Gregory P. Smitha689e522012-12-25 22:38:32 -08005062 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005063 if (base == -1 && PyErr_Occurred())
5064 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005065 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005066 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305067 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005068 return NULL;
5069 }
5070
5071 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005072 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 if (PyByteArray_Check(x))
5076 string = PyByteArray_AS_STRING(x);
5077 else
5078 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005079 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 }
5081 else {
5082 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005083 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 return NULL;
5085 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005086}
5087
Serhiy Storchaka95949422013-08-27 19:40:23 +03005088/* Wimpy, slow approach to tp_new calls for subtypes of int:
5089 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005090 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005091 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005092*/
5093static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005094long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 PyLongObject *tmp, *newobj;
5097 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005100 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 if (tmp == NULL)
5102 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005103 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 n = Py_SIZE(tmp);
5105 if (n < 0)
5106 n = -n;
5107 newobj = (PyLongObject *)type->tp_alloc(type, n);
5108 if (newobj == NULL) {
5109 Py_DECREF(tmp);
5110 return NULL;
5111 }
5112 assert(PyLong_Check(newobj));
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005113 Py_SET_SIZE(newobj, Py_SIZE(tmp));
5114 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 newobj->ob_digit[i] = tmp->ob_digit[i];
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 Py_DECREF(tmp);
5118 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005119}
5120
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005121/*[clinic input]
5122int.__getnewargs__
5123[clinic start generated code]*/
5124
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005125static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005126int___getnewargs___impl(PyObject *self)
5127/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005128{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005129 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005130}
5131
Guido van Rossumb43daf72007-08-01 18:08:08 +00005132static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005133long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005136}
5137
5138static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005139long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005141 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005142}
5143
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005144/*[clinic input]
5145int.__format__
5146
5147 format_spec: unicode
5148 /
5149[clinic start generated code]*/
5150
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005151static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005152int___format___impl(PyObject *self, PyObject *format_spec)
5153/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005154{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005155 _PyUnicodeWriter writer;
5156 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005157
Victor Stinner8f674cc2013-04-17 23:02:17 +02005158 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005159 ret = _PyLong_FormatAdvancedWriter(
5160 &writer,
5161 self,
5162 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5163 if (ret == -1) {
5164 _PyUnicodeWriter_Dealloc(&writer);
5165 return NULL;
5166 }
5167 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005168}
5169
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005170/* Return a pair (q, r) such that a = b * q + r, and
5171 abs(r) <= abs(b)/2, with equality possible only if q is even.
5172 In other words, q == a / b, rounded to the nearest integer using
5173 round-half-to-even. */
5174
5175PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005176_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005177{
5178 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005179 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005180 int quo_is_odd, quo_is_neg;
5181 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005182
5183 /* Equivalent Python code:
5184
5185 def divmod_near(a, b):
5186 q, r = divmod(a, b)
5187 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5188 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5189 # positive, 2 * r < b if b negative.
5190 greater_than_half = 2*r > b if b > 0 else 2*r < b
5191 exactly_half = 2*r == b
5192 if greater_than_half or exactly_half and q % 2 == 1:
5193 q += 1
5194 r -= b
5195 return q, r
5196
5197 */
5198 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5199 PyErr_SetString(PyExc_TypeError,
5200 "non-integer arguments in division");
5201 return NULL;
5202 }
5203
5204 /* Do a and b have different signs? If so, quotient is negative. */
5205 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5206
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005207 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5208 goto error;
5209
5210 /* compare twice the remainder with the divisor, to see
5211 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005212 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005213 if (twice_rem == NULL)
5214 goto error;
5215 if (quo_is_neg) {
5216 temp = long_neg((PyLongObject*)twice_rem);
5217 Py_DECREF(twice_rem);
5218 twice_rem = temp;
5219 if (twice_rem == NULL)
5220 goto error;
5221 }
5222 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5223 Py_DECREF(twice_rem);
5224
5225 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5226 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5227 /* fix up quotient */
5228 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005229 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005230 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005231 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005232 Py_DECREF(quo);
5233 quo = (PyLongObject *)temp;
5234 if (quo == NULL)
5235 goto error;
5236 /* and remainder */
5237 if (quo_is_neg)
5238 temp = long_add(rem, (PyLongObject *)b);
5239 else
5240 temp = long_sub(rem, (PyLongObject *)b);
5241 Py_DECREF(rem);
5242 rem = (PyLongObject *)temp;
5243 if (rem == NULL)
5244 goto error;
5245 }
5246
5247 result = PyTuple_New(2);
5248 if (result == NULL)
5249 goto error;
5250
5251 /* PyTuple_SET_ITEM steals references */
5252 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5253 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005254 return result;
5255
5256 error:
5257 Py_XDECREF(quo);
5258 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005259 return NULL;
5260}
5261
Eric Smith8c663262007-08-25 02:26:07 +00005262static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005263long_round(PyObject *self, PyObject *args)
5264{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005265 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005266
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005267 /* To round an integer m to the nearest 10**n (n positive), we make use of
5268 * the divmod_near operation, defined by:
5269 *
5270 * divmod_near(a, b) = (q, r)
5271 *
5272 * where q is the nearest integer to the quotient a / b (the
5273 * nearest even integer in the case of a tie) and r == a - q * b.
5274 * Hence q * b = a - r is the nearest multiple of b to a,
5275 * preferring even multiples in the case of a tie.
5276 *
5277 * So the nearest multiple of 10**n to m is:
5278 *
5279 * m - divmod_near(m, 10**n)[1].
5280 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5282 return NULL;
5283 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005284 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005285
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005286 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 if (ndigits == NULL)
5288 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005289
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005290 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 if (Py_SIZE(ndigits) >= 0) {
5292 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005293 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005295
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005296 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5297 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005299 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005301 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005302
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005303 result = PyLong_FromLong(10L);
5304 if (result == NULL) {
5305 Py_DECREF(ndigits);
5306 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005308
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005309 temp = long_pow(result, ndigits, Py_None);
5310 Py_DECREF(ndigits);
5311 Py_DECREF(result);
5312 result = temp;
5313 if (result == NULL)
5314 return NULL;
5315
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005316 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005317 Py_DECREF(result);
5318 result = temp;
5319 if (result == NULL)
5320 return NULL;
5321
5322 temp = long_sub((PyLongObject *)self,
5323 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5324 Py_DECREF(result);
5325 result = temp;
5326
5327 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005328}
5329
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005330/*[clinic input]
5331int.__sizeof__ -> Py_ssize_t
5332
5333Returns size in memory, in bytes.
5334[clinic start generated code]*/
5335
5336static Py_ssize_t
5337int___sizeof___impl(PyObject *self)
5338/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005341
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005342 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5343 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005344}
5345
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005346/*[clinic input]
5347int.bit_length
5348
5349Number of bits necessary to represent self in binary.
5350
5351>>> bin(37)
5352'0b100101'
5353>>> (37).bit_length()
53546
5355[clinic start generated code]*/
5356
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005357static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005358int_bit_length_impl(PyObject *self)
5359/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005362 Py_ssize_t ndigits;
5363 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005365
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005366 assert(self != NULL);
5367 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005368
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005369 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 if (ndigits == 0)
5371 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005372
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005373 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Niklas Fiekasc5b79002020-01-16 15:09:19 +01005374 msd_bits = _Py_bit_length(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5377 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 /* expression above may overflow; use Python integers instead */
5380 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5381 if (result == NULL)
5382 return NULL;
5383 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5384 if (x == NULL)
5385 goto error;
5386 y = (PyLongObject *)long_mul(result, x);
5387 Py_DECREF(x);
5388 if (y == NULL)
5389 goto error;
5390 Py_DECREF(result);
5391 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5394 if (x == NULL)
5395 goto error;
5396 y = (PyLongObject *)long_add(result, x);
5397 Py_DECREF(x);
5398 if (y == NULL)
5399 goto error;
5400 Py_DECREF(result);
5401 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005404
Mark Dickinson22b20182010-05-10 21:27:53 +00005405 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 Py_DECREF(result);
5407 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005408}
5409
Christian Heimes53876d92008-04-19 00:31:39 +00005410
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005411/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005412int.as_integer_ratio
5413
5414Return integer ratio.
5415
5416Return a pair of integers, whose ratio is exactly equal to the original int
5417and with a positive denominator.
5418
5419>>> (10).as_integer_ratio()
5420(10, 1)
5421>>> (-10).as_integer_ratio()
5422(-10, 1)
5423>>> (0).as_integer_ratio()
5424(0, 1)
5425[clinic start generated code]*/
5426
5427static PyObject *
5428int_as_integer_ratio_impl(PyObject *self)
5429/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5430{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005431 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005432 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005433 if (numerator == NULL) {
5434 return NULL;
5435 }
5436 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5437 Py_DECREF(numerator);
5438 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005439}
5440
5441/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005442int.to_bytes
5443
5444 length: Py_ssize_t
5445 Length of bytes object to use. An OverflowError is raised if the
5446 integer is not representable with the given number of bytes.
5447 byteorder: unicode
5448 The byte order used to represent the integer. If byteorder is 'big',
5449 the most significant byte is at the beginning of the byte array. If
5450 byteorder is 'little', the most significant byte is at the end of the
5451 byte array. To request the native byte order of the host system, use
5452 `sys.byteorder' as the byte order value.
5453 *
5454 signed as is_signed: bool = False
5455 Determines whether two's complement is used to represent the integer.
5456 If signed is False and a negative integer is given, an OverflowError
5457 is raised.
5458
5459Return an array of bytes representing an integer.
5460[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005461
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005462static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005463int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5464 int is_signed)
5465/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005469
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005470 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005472 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 little_endian = 0;
5474 else {
5475 PyErr_SetString(PyExc_ValueError,
5476 "byteorder must be either 'little' or 'big'");
5477 return NULL;
5478 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 if (length < 0) {
5481 PyErr_SetString(PyExc_ValueError,
5482 "length argument must be non-negative");
5483 return NULL;
5484 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005486 bytes = PyBytes_FromStringAndSize(NULL, length);
5487 if (bytes == NULL)
5488 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005489
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005490 if (_PyLong_AsByteArray((PyLongObject *)self,
5491 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 length, little_endian, is_signed) < 0) {
5493 Py_DECREF(bytes);
5494 return NULL;
5495 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005497 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005498}
5499
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005500/*[clinic input]
5501@classmethod
5502int.from_bytes
5503
5504 bytes as bytes_obj: object
5505 Holds the array of bytes to convert. The argument must either
5506 support the buffer protocol or be an iterable object producing bytes.
5507 Bytes and bytearray are examples of built-in objects that support the
5508 buffer protocol.
5509 byteorder: unicode
5510 The byte order used to represent the integer. If byteorder is 'big',
5511 the most significant byte is at the beginning of the byte array. If
5512 byteorder is 'little', the most significant byte is at the end of the
5513 byte array. To request the native byte order of the host system, use
5514 `sys.byteorder' as the byte order value.
5515 *
5516 signed as is_signed: bool = False
5517 Indicates whether two's complement is used to represent the integer.
5518
5519Return the integer represented by the given array of bytes.
5520[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005521
5522static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005523int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5524 PyObject *byteorder, int is_signed)
5525/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005528 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005529
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005530 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005532 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 little_endian = 0;
5534 else {
5535 PyErr_SetString(PyExc_ValueError,
5536 "byteorder must be either 'little' or 'big'");
5537 return NULL;
5538 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005539
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005540 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 if (bytes == NULL)
5542 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 long_obj = _PyLong_FromByteArray(
5545 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5546 little_endian, is_signed);
5547 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005548
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005549 if (long_obj != NULL && type != &PyLong_Type) {
Petr Viktorinffd97532020-02-11 17:46:57 +01005550 Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005553 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005554}
5555
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005556static PyObject *
5557long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5558{
5559 return long_long(self);
5560}
5561
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005562static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005563 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005565 INT_BIT_LENGTH_METHODDEF
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005566 INT_TO_BYTES_METHODDEF
5567 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005568 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005569 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005571 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005573 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 "Ceiling of an Integral returns itself."},
5575 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5576 "Rounding an Integral returns itself.\n"
5577 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005578 INT___GETNEWARGS___METHODDEF
5579 INT___FORMAT___METHODDEF
5580 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005581 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005582};
5583
Guido van Rossumb43daf72007-08-01 18:08:08 +00005584static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005585 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005586 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005587 "the real part of a complex number",
5588 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005589 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005590 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005591 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005592 NULL},
5593 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005594 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005595 "the numerator of a rational number in lowest terms",
5596 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005597 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005598 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005599 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005600 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005601 {NULL} /* Sentinel */
5602};
5603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005604PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005605"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005606int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005607\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005608Convert a number or string to an integer, or return 0 if no arguments\n\
5609are given. If x is a number, return x.__int__(). For floating point\n\
5610numbers, this truncates towards zero.\n\
5611\n\
5612If x is not a number or if base is given, then x must be a string,\n\
5613bytes, or bytearray instance representing an integer literal in the\n\
5614given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5615by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5616Base 0 means to interpret the base from the string as an integer literal.\n\
5617>>> int('0b100', base=0)\n\
56184");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005619
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005620static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005621 (binaryfunc)long_add, /*nb_add*/
5622 (binaryfunc)long_sub, /*nb_subtract*/
5623 (binaryfunc)long_mul, /*nb_multiply*/
5624 long_mod, /*nb_remainder*/
5625 long_divmod, /*nb_divmod*/
5626 long_pow, /*nb_power*/
5627 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005628 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005629 (unaryfunc)long_abs, /*tp_absolute*/
5630 (inquiry)long_bool, /*tp_bool*/
5631 (unaryfunc)long_invert, /*nb_invert*/
5632 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005633 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005634 long_and, /*nb_and*/
5635 long_xor, /*nb_xor*/
5636 long_or, /*nb_or*/
5637 long_long, /*nb_int*/
5638 0, /*nb_reserved*/
5639 long_float, /*nb_float*/
5640 0, /* nb_inplace_add */
5641 0, /* nb_inplace_subtract */
5642 0, /* nb_inplace_multiply */
5643 0, /* nb_inplace_remainder */
5644 0, /* nb_inplace_power */
5645 0, /* nb_inplace_lshift */
5646 0, /* nb_inplace_rshift */
5647 0, /* nb_inplace_and */
5648 0, /* nb_inplace_xor */
5649 0, /* nb_inplace_or */
5650 long_div, /* nb_floor_divide */
5651 long_true_divide, /* nb_true_divide */
5652 0, /* nb_inplace_floor_divide */
5653 0, /* nb_inplace_true_divide */
5654 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005655};
5656
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005657PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5659 "int", /* tp_name */
5660 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5661 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005662 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005663 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 0, /* tp_getattr */
5665 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005666 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 long_to_decimal_string, /* tp_repr */
5668 &long_as_number, /* tp_as_number */
5669 0, /* tp_as_sequence */
5670 0, /* tp_as_mapping */
5671 (hashfunc)long_hash, /* tp_hash */
5672 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005673 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 PyObject_GenericGetAttr, /* tp_getattro */
5675 0, /* tp_setattro */
5676 0, /* tp_as_buffer */
5677 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5678 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5679 long_doc, /* tp_doc */
5680 0, /* tp_traverse */
5681 0, /* tp_clear */
5682 long_richcompare, /* tp_richcompare */
5683 0, /* tp_weaklistoffset */
5684 0, /* tp_iter */
5685 0, /* tp_iternext */
5686 long_methods, /* tp_methods */
5687 0, /* tp_members */
5688 long_getset, /* tp_getset */
5689 0, /* tp_base */
5690 0, /* tp_dict */
5691 0, /* tp_descr_get */
5692 0, /* tp_descr_set */
5693 0, /* tp_dictoffset */
5694 0, /* tp_init */
5695 0, /* tp_alloc */
5696 long_new, /* tp_new */
5697 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005698};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005699
Mark Dickinsonbd792642009-03-18 20:06:12 +00005700static PyTypeObject Int_InfoType;
5701
5702PyDoc_STRVAR(int_info__doc__,
5703"sys.int_info\n\
5704\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005705A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005706internal representation of integers. The attributes are read only.");
5707
5708static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005710 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005712};
5713
5714static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 "sys.int_info", /* name */
5716 int_info__doc__, /* doc */
5717 int_info_fields, /* fields */
5718 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005719};
5720
5721PyObject *
5722PyLong_GetInfo(void)
5723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 PyObject* int_info;
5725 int field = 0;
5726 int_info = PyStructSequence_New(&Int_InfoType);
5727 if (int_info == NULL)
5728 return NULL;
5729 PyStructSequence_SET_ITEM(int_info, field++,
5730 PyLong_FromLong(PyLong_SHIFT));
5731 PyStructSequence_SET_ITEM(int_info, field++,
5732 PyLong_FromLong(sizeof(digit)));
5733 if (PyErr_Occurred()) {
5734 Py_CLEAR(int_info);
5735 return NULL;
5736 }
5737 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005738}
5739
Guido van Rossumddefaf32007-01-14 03:31:43 +00005740int
Victor Stinner630c8df2019-12-17 13:02:18 +01005741_PyLong_Init(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005742{
5743#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005744 for (Py_ssize_t i=0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
5745 sdigit ival = (sdigit)i - NSMALLNEGINTS;
5746 int size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005747
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005748 PyLongObject *v = _PyLong_New(1);
5749 if (!v) {
5750 return -1;
5751 }
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005752
Victor Stinner60ac6ed2020-02-07 23:18:08 +01005753 Py_SET_SIZE(v, size);
Victor Stinner12174a52014-08-15 23:17:38 +02005754 v->ob_digit[0] = (digit)abs(ival);
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005755
Victor Stinner630c8df2019-12-17 13:02:18 +01005756 tstate->interp->small_ints[i] = v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005757 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005758#endif
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005759
Victor Stinner630c8df2019-12-17 13:02:18 +01005760 if (_Py_IsMainInterpreter(tstate)) {
5761 _PyLong_Zero = PyLong_FromLong(0);
5762 if (_PyLong_Zero == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005763 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005764 }
Victor Stinner630c8df2019-12-17 13:02:18 +01005765
5766 _PyLong_One = PyLong_FromLong(1);
5767 if (_PyLong_One == NULL) {
5768 return 0;
5769 }
5770
5771 /* initialize int_info */
5772 if (Int_InfoType.tp_name == NULL) {
5773 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
5774 return 0;
5775 }
5776 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005777 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005780}
5781
5782void
Victor Stinner630c8df2019-12-17 13:02:18 +01005783_PyLong_Fini(PyThreadState *tstate)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005784{
Victor Stinner630c8df2019-12-17 13:02:18 +01005785 if (_Py_IsMainInterpreter(tstate)) {
5786 Py_CLEAR(_PyLong_One);
5787 Py_CLEAR(_PyLong_Zero);
5788 }
5789
Guido van Rossumddefaf32007-01-14 03:31:43 +00005790#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Victor Stinner5dcc06f2019-11-21 08:51:59 +01005791 for (Py_ssize_t i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++) {
Victor Stinner630c8df2019-12-17 13:02:18 +01005792 Py_CLEAR(tstate->interp->small_ints[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005794#endif
5795}