blob: f2f6f9540892eece80e4169cdf642fbec0c5127c [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"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Serhiy Storchaka495e8802017-02-01 23:12:20 +020012#include "clinic/longobject.c.h"
13/*[clinic input]
14class int "PyObject *" "&PyLong_Type"
15[clinic start generated code]*/
16/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
17
Guido van Rossumddefaf32007-01-14 03:31:43 +000018#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000020#endif
21#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000023#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020025_Py_IDENTIFIER(little);
26_Py_IDENTIFIER(big);
27
Mark Dickinsone4416742009-02-15 15:14:57 +000028/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020029#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
30 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 (Py_SIZE(x) == 0 ? (sdigit)0 : \
32 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000033
Serhiy Storchakaba85d692017-03-30 09:09:41 +030034PyObject *_PyLong_Zero = NULL;
35PyObject *_PyLong_One = NULL;
36
Guido van Rossumddefaf32007-01-14 03:31:43 +000037#if NSMALLNEGINTS + NSMALLPOSINTS > 0
38/* Small integers are preallocated in this array so that they
39 can be shared.
40 The integers that are preallocated are those in the range
41 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
42*/
43static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
Greg Price5e63ab02019-08-24 10:19:37 -070044
animalize6b519982019-09-06 14:00:56 +080045#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050046#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070047
Guido van Rossumddefaf32007-01-14 03:31:43 +000048#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +000049Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000050#endif
51
Guido van Rossum7eaf8222007-06-18 17:58:50 +000052static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000053get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000054{
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050055 PyObject *v;
animalize6b519982019-09-06 14:00:56 +080056 assert(IS_SMALL_INT(ival));
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050057 v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000059#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 if (ival >= 0)
Pablo Galindo49c75a82018-10-28 15:02:17 +000061 _Py_quick_int_allocs++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 else
Pablo Galindo49c75a82018-10-28 15:02:17 +000063 _Py_quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000064#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000066}
Guido van Rossumddefaf32007-01-14 03:31:43 +000067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069maybe_small_long(PyLongObject *v)
70{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020071 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080073 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 Py_DECREF(v);
75 return (PyLongObject *)get_small_int(ival);
76 }
77 }
78 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000079}
Guido van Rossumddefaf32007-01-14 03:31:43 +000080#else
animalize6b519982019-09-06 14:00:56 +080081#define IS_SMALL_INT(ival) 0
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +050082#define IS_SMALL_UINT(ival) 0
animalize6b519982019-09-06 14:00:56 +080083#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000084#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000085#endif
86
Serhiy Storchaka95949422013-08-27 19:40:23 +030087/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000088 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020089Py_LOCAL_INLINE(void)
90_PyLong_Negate(PyLongObject **x_p)
91{
92 PyLongObject *x;
93
94 x = (PyLongObject *)*x_p;
95 if (Py_REFCNT(x) == 1) {
96 Py_SIZE(x) = -Py_SIZE(x);
97 return;
98 }
99
100 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
101 Py_DECREF(x);
102}
103
Serhiy Storchaka95949422013-08-27 19:40:23 +0300104/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +0000105 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +0300106 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +0000107 */
Tim Peters0973b992004-08-29 22:16:50 +0000108#define KARATSUBA_CUTOFF 70
109#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +0000110
Tim Peters47e52ee2004-08-30 02:44:38 +0000111/* For exponentiation, use the binary left-to-right algorithm
112 * unless the exponent contains more than FIVEARY_CUTOFF digits.
113 * In that case, do 5 bits at a time. The potential drawback is that
114 * a table of 2**5 intermediate results is computed.
115 */
116#define FIVEARY_CUTOFF 8
117
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000118#define SIGCHECK(PyTryBlock) \
119 do { \
120 if (PyErr_CheckSignals()) PyTryBlock \
121 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000122
Serhiy Storchaka95949422013-08-27 19:40:23 +0300123/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000124 Doesn't attempt to free the storage--in most cases, due to the nature
125 of the algorithms used, this could save at most be one word anyway. */
126
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200128long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000129{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200130 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 while (i > 0 && v->ob_digit[i-1] == 0)
134 --i;
135 if (i != j)
136 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
137 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000138}
139
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200140/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
141 using the nb_int slot, if available. Raise TypeError if either the
142 nb_int slot is not available or the result of the call to nb_int
143 returns something not of type int.
144*/
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200145PyObject *
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200146_PyLong_FromNbInt(PyObject *integral)
147{
148 PyNumberMethods *nb;
149 PyObject *result;
150
151 /* Fast path for the case that we already have an int. */
152 if (PyLong_CheckExact(integral)) {
153 Py_INCREF(integral);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200154 return integral;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200155 }
156
157 nb = Py_TYPE(integral)->tp_as_number;
158 if (nb == NULL || nb->nb_int == NULL) {
159 PyErr_Format(PyExc_TypeError,
160 "an integer is required (got type %.200s)",
161 Py_TYPE(integral)->tp_name);
162 return NULL;
163 }
164
165 /* Convert using the nb_int slot, which should return something
166 of exact type int. */
167 result = nb->nb_int(integral);
168 if (!result || PyLong_CheckExact(result))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200169 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200170 if (!PyLong_Check(result)) {
171 PyErr_Format(PyExc_TypeError,
172 "__int__ returned non-int (type %.200s)",
173 result->ob_type->tp_name);
174 Py_DECREF(result);
175 return NULL;
176 }
177 /* Issue #17576: warn if 'result' not of exact type int. */
178 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
179 "__int__ returned non-int (type %.200s). "
180 "The ability to return an instance of a strict subclass of int "
181 "is deprecated, and may be removed in a future version of Python.",
182 result->ob_type->tp_name)) {
183 Py_DECREF(result);
184 return NULL;
185 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200186 return result;
187}
188
189/* Convert the given object to a PyLongObject using the nb_index or
190 nb_int slots, if available (the latter is deprecated).
191 Raise TypeError if either nb_index and nb_int slots are not
192 available or the result of the call to nb_index or nb_int
193 returns something not of type int.
194 Should be replaced with PyNumber_Index after the end of the
195 deprecation period.
196*/
197PyObject *
198_PyLong_FromNbIndexOrNbInt(PyObject *integral)
199{
200 PyNumberMethods *nb;
201 PyObject *result;
202
203 /* Fast path for the case that we already have an int. */
204 if (PyLong_CheckExact(integral)) {
205 Py_INCREF(integral);
206 return integral;
207 }
208
209 nb = Py_TYPE(integral)->tp_as_number;
210 if (nb == NULL || (nb->nb_index == NULL && nb->nb_int == NULL)) {
211 PyErr_Format(PyExc_TypeError,
212 "an integer is required (got type %.200s)",
213 Py_TYPE(integral)->tp_name);
214 return NULL;
215 }
216
217 if (nb->nb_index) {
218 /* Convert using the nb_index slot, which should return something
219 of exact type int. */
220 result = nb->nb_index(integral);
221 if (!result || PyLong_CheckExact(result))
222 return result;
223 if (!PyLong_Check(result)) {
224 PyErr_Format(PyExc_TypeError,
225 "__index__ returned non-int (type %.200s)",
226 result->ob_type->tp_name);
227 Py_DECREF(result);
228 return NULL;
229 }
230 /* Issue #17576: warn if 'result' not of exact type int. */
231 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
232 "__index__ returned non-int (type %.200s). "
233 "The ability to return an instance of a strict subclass of int "
234 "is deprecated, and may be removed in a future version of Python.",
235 result->ob_type->tp_name))
236 {
237 Py_DECREF(result);
238 return NULL;
239 }
240 return result;
241 }
242
243 result = _PyLong_FromNbInt(integral);
244 if (result && PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
245 "an integer is required (got type %.200s). "
246 "Implicit conversion to integers using __int__ is deprecated, "
247 "and may be removed in a future version of Python.",
248 Py_TYPE(integral)->tp_name))
249 {
250 Py_DECREF(result);
251 return NULL;
252 }
253 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200254}
255
256
Serhiy Storchaka95949422013-08-27 19:40:23 +0300257/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000258 Return NULL and set exception if we run out of memory. */
259
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000260#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000262
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000263PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000264_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 PyLongObject *result;
267 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
268 sizeof(digit)*size. Previous incarnations of this code used
269 sizeof(PyVarObject) instead of the offsetof, but this risks being
270 incorrect in the presence of padding between the PyVarObject header
271 and the digits. */
272 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
273 PyErr_SetString(PyExc_OverflowError,
274 "too many digits in integer");
275 return NULL;
276 }
277 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
278 size*sizeof(digit));
279 if (!result) {
280 PyErr_NoMemory();
281 return NULL;
282 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100283 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000284}
285
Tim Peters64b5ce32001-09-10 20:52:51 +0000286PyObject *
287_PyLong_Copy(PyLongObject *src)
288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 PyLongObject *result;
290 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 assert(src != NULL);
293 i = Py_SIZE(src);
294 if (i < 0)
295 i = -(i);
296 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100297 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800298 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700299 return get_small_int(ival);
300 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 }
302 result = _PyLong_New(i);
303 if (result != NULL) {
304 Py_SIZE(result) = Py_SIZE(src);
305 while (--i >= 0)
306 result->ob_digit[i] = src->ob_digit[i];
307 }
308 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000309}
310
Serhiy Storchaka95949422013-08-27 19:40:23 +0300311/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000312
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000313PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000314PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 PyLongObject *v;
317 unsigned long abs_ival;
318 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
319 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100320 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000321
animalize6b519982019-09-06 14:00:56 +0800322 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700323 return get_small_int((sdigit)ival);
324 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (ival < 0) {
327 /* negate: can't write this as abs_ival = -ival since that
328 invokes undefined behaviour when ival is LONG_MIN */
329 abs_ival = 0U-(unsigned long)ival;
330 sign = -1;
331 }
332 else {
333 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100334 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 /* Fast path for single-digit ints */
338 if (!(abs_ival >> PyLong_SHIFT)) {
339 v = _PyLong_New(1);
340 if (v) {
341 Py_SIZE(v) = sign;
342 v->ob_digit[0] = Py_SAFE_DOWNCAST(
343 abs_ival, unsigned long, digit);
344 }
345 return (PyObject*)v;
346 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000347
Mark Dickinson249b8982009-04-27 19:41:00 +0000348#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 /* 2 digits */
350 if (!(abs_ival >> 2*PyLong_SHIFT)) {
351 v = _PyLong_New(2);
352 if (v) {
353 Py_SIZE(v) = 2*sign;
354 v->ob_digit[0] = Py_SAFE_DOWNCAST(
355 abs_ival & PyLong_MASK, unsigned long, digit);
356 v->ob_digit[1] = Py_SAFE_DOWNCAST(
357 abs_ival >> PyLong_SHIFT, unsigned long, digit);
358 }
359 return (PyObject*)v;
360 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000361#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 /* Larger numbers: loop to determine number of digits */
364 t = abs_ival;
365 while (t) {
366 ++ndigits;
367 t >>= PyLong_SHIFT;
368 }
369 v = _PyLong_New(ndigits);
370 if (v != NULL) {
371 digit *p = v->ob_digit;
372 Py_SIZE(v) = ndigits*sign;
373 t = abs_ival;
374 while (t) {
375 *p++ = Py_SAFE_DOWNCAST(
376 t & PyLong_MASK, unsigned long, digit);
377 t >>= PyLong_SHIFT;
378 }
379 }
380 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000381}
382
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500383#define PYLONG_FROM_UINT(INT_TYPE, ival) \
384 do { \
385 if (IS_SMALL_UINT(ival)) { \
386 return get_small_int((ival)); \
387 } \
388 /* Count the number of Python digits. */ \
389 Py_ssize_t ndigits = 0; \
390 INT_TYPE t = (ival); \
391 while (t) { \
392 ++ndigits; \
393 t >>= PyLong_SHIFT; \
394 } \
395 PyLongObject *v = _PyLong_New(ndigits); \
396 if (v == NULL) { \
397 return NULL; \
398 } \
399 digit *p = v->ob_digit; \
400 while ((ival)) { \
401 *p++ = (digit)((ival) & PyLong_MASK); \
402 (ival) >>= PyLong_SHIFT; \
403 } \
404 return (PyObject *)v; \
405 } while(0)
406
Serhiy Storchaka95949422013-08-27 19:40:23 +0300407/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000408
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000410PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000411{
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500412 PYLONG_FROM_UINT(unsigned long, ival);
413}
Tim Petersce9de2f2001-06-14 04:56:19 +0000414
Sergey Fedoseevc6734ee2019-09-12 19:41:14 +0500415/* Create a new int object from a C unsigned long long int. */
416
417PyObject *
418PyLong_FromUnsignedLongLong(unsigned long long ival)
419{
420 PYLONG_FROM_UINT(unsigned long long, ival);
421}
422
423/* Create a new int object from a C size_t. */
424
425PyObject *
426PyLong_FromSize_t(size_t ival)
427{
428 PYLONG_FROM_UINT(size_t, ival);
Guido van Rossum53756b11997-01-03 17:14:46 +0000429}
430
Serhiy Storchaka95949422013-08-27 19:40:23 +0300431/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000432
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 PyLongObject *v;
437 double frac;
438 int i, ndig, expo, neg;
439 neg = 0;
440 if (Py_IS_INFINITY(dval)) {
441 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000442 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 return NULL;
444 }
445 if (Py_IS_NAN(dval)) {
446 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000447 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 return NULL;
449 }
450 if (dval < 0.0) {
451 neg = 1;
452 dval = -dval;
453 }
454 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
455 if (expo <= 0)
456 return PyLong_FromLong(0L);
457 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
458 v = _PyLong_New(ndig);
459 if (v == NULL)
460 return NULL;
461 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
462 for (i = ndig; --i >= 0; ) {
463 digit bits = (digit)frac;
464 v->ob_digit[i] = bits;
465 frac = frac - (double)bits;
466 frac = ldexp(frac, PyLong_SHIFT);
467 }
468 if (neg)
469 Py_SIZE(v) = -(Py_SIZE(v));
470 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000471}
472
Thomas Wouters89f507f2006-12-13 04:49:30 +0000473/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
474 * anything about what happens when a signed integer operation overflows,
475 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700476 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000477 * (unsigned long)LONG_MAX, and for the smallest negative signed long
478 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
479 * However, some other compilers warn about applying unary minus to an
480 * unsigned operand. Hence the weird "0-".
481 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
483#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000484
Serhiy Storchaka95949422013-08-27 19:40:23 +0300485/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100486 method.
487
488 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
489 the result. Otherwise *overflow is 0.
490
491 For other errors (e.g., TypeError), return -1 and set an error condition.
492 In this case *overflow will be 0.
493*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000494
495long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000496PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200499 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 unsigned long x, prev;
501 long res;
502 Py_ssize_t i;
503 int sign;
504 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 *overflow = 0;
507 if (vv == NULL) {
508 PyErr_BadInternalCall();
509 return -1;
510 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000511
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200512 if (PyLong_Check(vv)) {
513 v = (PyLongObject *)vv;
514 }
515 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200516 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200517 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return -1;
519 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 switch (i) {
526 case -1:
527 res = -(sdigit)v->ob_digit[0];
528 break;
529 case 0:
530 res = 0;
531 break;
532 case 1:
533 res = v->ob_digit[0];
534 break;
535 default:
536 sign = 1;
537 x = 0;
538 if (i < 0) {
539 sign = -1;
540 i = -(i);
541 }
542 while (--i >= 0) {
543 prev = x;
544 x = (x << PyLong_SHIFT) | v->ob_digit[i];
545 if ((x >> PyLong_SHIFT) != prev) {
546 *overflow = sign;
547 goto exit;
548 }
549 }
550 /* Haven't lost any bits, but casting to long requires extra
551 * care (see comment above).
552 */
553 if (x <= (unsigned long)LONG_MAX) {
554 res = (long)x * sign;
555 }
556 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
557 res = LONG_MIN;
558 }
559 else {
560 *overflow = sign;
561 /* res is already set to -1 */
562 }
563 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000564 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200566 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 }
568 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000569}
570
Serhiy Storchaka95949422013-08-27 19:40:23 +0300571/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100572 method. Return -1 and set an error if overflow occurs. */
573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000575PyLong_AsLong(PyObject *obj)
576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 int overflow;
578 long result = PyLong_AsLongAndOverflow(obj, &overflow);
579 if (overflow) {
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 long");
584 }
585 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000586}
587
Serhiy Storchaka95949422013-08-27 19:40:23 +0300588/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200589 method. Return -1 and set an error if overflow occurs. */
590
591int
592_PyLong_AsInt(PyObject *obj)
593{
594 int overflow;
595 long result = PyLong_AsLongAndOverflow(obj, &overflow);
596 if (overflow || result > INT_MAX || result < INT_MIN) {
597 /* XXX: could be cute and give a different
598 message for overflow == -1 */
599 PyErr_SetString(PyExc_OverflowError,
600 "Python int too large to convert to C int");
601 return -1;
602 }
603 return (int)result;
604}
605
Serhiy Storchaka95949422013-08-27 19:40:23 +0300606/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000607 Returns -1 and sets an error condition if overflow occurs. */
608
609Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000610PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200611 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 size_t x, prev;
613 Py_ssize_t i;
614 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (vv == NULL) {
617 PyErr_BadInternalCall();
618 return -1;
619 }
620 if (!PyLong_Check(vv)) {
621 PyErr_SetString(PyExc_TypeError, "an integer is required");
622 return -1;
623 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 v = (PyLongObject *)vv;
626 i = Py_SIZE(v);
627 switch (i) {
628 case -1: return -(sdigit)v->ob_digit[0];
629 case 0: return 0;
630 case 1: return v->ob_digit[0];
631 }
632 sign = 1;
633 x = 0;
634 if (i < 0) {
635 sign = -1;
636 i = -(i);
637 }
638 while (--i >= 0) {
639 prev = x;
640 x = (x << PyLong_SHIFT) | v->ob_digit[i];
641 if ((x >> PyLong_SHIFT) != prev)
642 goto overflow;
643 }
644 /* Haven't lost any bits, but casting to a signed type requires
645 * extra care (see comment above).
646 */
647 if (x <= (size_t)PY_SSIZE_T_MAX) {
648 return (Py_ssize_t)x * sign;
649 }
650 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
651 return PY_SSIZE_T_MIN;
652 }
653 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000654
Mark Dickinson22b20182010-05-10 21:27:53 +0000655 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 PyErr_SetString(PyExc_OverflowError,
657 "Python int too large to convert to C ssize_t");
658 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000659}
660
Serhiy Storchaka95949422013-08-27 19:40:23 +0300661/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000662 Returns -1 and sets an error condition if overflow occurs. */
663
664unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000665PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000666{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200667 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 unsigned long x, prev;
669 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (vv == NULL) {
672 PyErr_BadInternalCall();
673 return (unsigned long)-1;
674 }
675 if (!PyLong_Check(vv)) {
676 PyErr_SetString(PyExc_TypeError, "an integer is required");
677 return (unsigned long)-1;
678 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 v = (PyLongObject *)vv;
681 i = Py_SIZE(v);
682 x = 0;
683 if (i < 0) {
684 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000685 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 return (unsigned long) -1;
687 }
688 switch (i) {
689 case 0: return 0;
690 case 1: return v->ob_digit[0];
691 }
692 while (--i >= 0) {
693 prev = x;
694 x = (x << PyLong_SHIFT) | v->ob_digit[i];
695 if ((x >> PyLong_SHIFT) != prev) {
696 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100697 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000698 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 return (unsigned long) -1;
700 }
701 }
702 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000703}
704
Serhiy Storchaka95949422013-08-27 19:40:23 +0300705/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200706 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000707
708size_t
709PyLong_AsSize_t(PyObject *vv)
710{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200711 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 size_t x, prev;
713 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (vv == NULL) {
716 PyErr_BadInternalCall();
717 return (size_t) -1;
718 }
719 if (!PyLong_Check(vv)) {
720 PyErr_SetString(PyExc_TypeError, "an integer is required");
721 return (size_t)-1;
722 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 v = (PyLongObject *)vv;
725 i = Py_SIZE(v);
726 x = 0;
727 if (i < 0) {
728 PyErr_SetString(PyExc_OverflowError,
729 "can't convert negative value to size_t");
730 return (size_t) -1;
731 }
732 switch (i) {
733 case 0: return 0;
734 case 1: return v->ob_digit[0];
735 }
736 while (--i >= 0) {
737 prev = x;
738 x = (x << PyLong_SHIFT) | v->ob_digit[i];
739 if ((x >> PyLong_SHIFT) != prev) {
740 PyErr_SetString(PyExc_OverflowError,
741 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200742 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 }
744 }
745 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000746}
747
Serhiy Storchaka95949422013-08-27 19:40:23 +0300748/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000749 Returns -1 and sets an error condition if an error occurs. */
750
Guido van Rossumddefaf32007-01-14 03:31:43 +0000751static unsigned long
752_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000753{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200754 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 unsigned long x;
756 Py_ssize_t i;
757 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 if (vv == NULL || !PyLong_Check(vv)) {
760 PyErr_BadInternalCall();
761 return (unsigned long) -1;
762 }
763 v = (PyLongObject *)vv;
764 i = Py_SIZE(v);
765 switch (i) {
766 case 0: return 0;
767 case 1: return v->ob_digit[0];
768 }
769 sign = 1;
770 x = 0;
771 if (i < 0) {
772 sign = -1;
773 i = -i;
774 }
775 while (--i >= 0) {
776 x = (x << PyLong_SHIFT) | v->ob_digit[i];
777 }
778 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000779}
780
Guido van Rossumddefaf32007-01-14 03:31:43 +0000781unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200782PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyLongObject *lo;
785 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000786
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200787 if (op == NULL) {
788 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 return (unsigned long)-1;
790 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000791
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200792 if (PyLong_Check(op)) {
793 return _PyLong_AsUnsignedLongMask(op);
794 }
795
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200796 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 if (lo == NULL)
798 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200799
800 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
801 Py_DECREF(lo);
802 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000803}
804
Tim Peters5b8132f2003-01-31 15:52:05 +0000805int
806_PyLong_Sign(PyObject *vv)
807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 assert(v != NULL);
811 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000814}
815
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200816/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
817 2**k if d is nonzero, else 0. */
818
819static const unsigned char BitLengthTable[32] = {
820 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
821 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
822};
823
824static int
825bits_in_digit(digit d)
826{
827 int d_bits = 0;
828 while (d >= 32) {
829 d_bits += 6;
830 d >>= 6;
831 }
832 d_bits += (int)BitLengthTable[d];
833 return d_bits;
834}
835
Tim Petersbaefd9e2003-01-28 20:37:45 +0000836size_t
837_PyLong_NumBits(PyObject *vv)
838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyLongObject *v = (PyLongObject *)vv;
840 size_t result = 0;
841 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200842 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 assert(v != NULL);
845 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200846 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
848 if (ndigits > 0) {
849 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700850 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100852 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200853 msd_bits = bits_in_digit(msd);
854 if (SIZE_MAX - msd_bits < result)
855 goto Overflow;
856 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 }
858 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000859
Mark Dickinson22b20182010-05-10 21:27:53 +0000860 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
862 "to express in a platform size_t");
863 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000864}
865
Tim Peters2a9b3672001-06-11 21:23:58 +0000866PyObject *
867_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000869{
Mark Dickinson22b20182010-05-10 21:27:53 +0000870 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 int incr; /* direction to move pstartbyte */
872 const unsigned char* pendbyte; /* MSB of bytes */
873 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300874 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 PyLongObject* v; /* result */
876 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (n == 0)
879 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (little_endian) {
882 pstartbyte = bytes;
883 pendbyte = bytes + n - 1;
884 incr = 1;
885 }
886 else {
887 pstartbyte = bytes + n - 1;
888 pendbyte = bytes;
889 incr = -1;
890 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (is_signed)
893 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200896 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 is positive, and leading 0xff bytes if negative. */
898 {
899 size_t i;
900 const unsigned char* p = pendbyte;
901 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000902 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000905 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 break;
907 }
908 numsignificantbytes = n - i;
909 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
910 actually has 2 significant bytes. OTOH, 0xff0001 ==
911 -0x00ffff, so we wouldn't *need* to bump it there; but we
912 do for 0xffff = -0x0001. To be safe without bothering to
913 check every case, bump it regardless. */
914 if (is_signed && numsignificantbytes < n)
915 ++numsignificantbytes;
916 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000917
Serhiy Storchaka95949422013-08-27 19:40:23 +0300918 /* How many Python int digits do we need? We have
919 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
921 /* catch overflow before it happens */
922 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
923 PyErr_SetString(PyExc_OverflowError,
924 "byte array too long to convert to int");
925 return NULL;
926 }
927 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
928 v = _PyLong_New(ndigits);
929 if (v == NULL)
930 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 /* Copy the bits over. The tricky parts are computing 2's-comp on
933 the fly for signed numbers, and dealing with the mismatch between
934 8-bit bytes and (probably) 15-bit Python digits.*/
935 {
936 size_t i;
937 twodigits carry = 1; /* for 2's-comp calculation */
938 twodigits accum = 0; /* sliding register */
939 unsigned int accumbits = 0; /* number of bits in accum */
940 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
943 twodigits thisbyte = *p;
944 /* Compute correction for 2's comp, if needed. */
945 if (is_signed) {
946 thisbyte = (0xff ^ thisbyte) + carry;
947 carry = thisbyte >> 8;
948 thisbyte &= 0xff;
949 }
950 /* Because we're going LSB to MSB, thisbyte is
951 more significant than what's already in accum,
952 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200953 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 accumbits += 8;
955 if (accumbits >= PyLong_SHIFT) {
956 /* There's enough to fill a Python digit. */
957 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000958 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 ++idigit;
960 accum >>= PyLong_SHIFT;
961 accumbits -= PyLong_SHIFT;
962 assert(accumbits < PyLong_SHIFT);
963 }
964 }
965 assert(accumbits < PyLong_SHIFT);
966 if (accumbits) {
967 assert(idigit < ndigits);
968 v->ob_digit[idigit] = (digit)accum;
969 ++idigit;
970 }
971 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 Py_SIZE(v) = is_signed ? -idigit : idigit;
974 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000975}
976
977int
978_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 unsigned char* bytes, size_t n,
980 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000983 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000985 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
987 digit carry; /* for computing 2's-comp */
988 size_t j; /* # bytes filled */
989 unsigned char* p; /* pointer to next byte in bytes */
990 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 if (Py_SIZE(v) < 0) {
995 ndigits = -(Py_SIZE(v));
996 if (!is_signed) {
997 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000998 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 return -1;
1000 }
1001 do_twos_comp = 1;
1002 }
1003 else {
1004 ndigits = Py_SIZE(v);
1005 do_twos_comp = 0;
1006 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (little_endian) {
1009 p = bytes;
1010 pincr = 1;
1011 }
1012 else {
1013 p = bytes + n - 1;
1014 pincr = -1;
1015 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* Copy over all the Python digits.
1018 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +03001019 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 normalized. */
1021 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
1022 j = 0;
1023 accum = 0;
1024 accumbits = 0;
1025 carry = do_twos_comp ? 1 : 0;
1026 for (i = 0; i < ndigits; ++i) {
1027 digit thisdigit = v->ob_digit[i];
1028 if (do_twos_comp) {
1029 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
1030 carry = thisdigit >> PyLong_SHIFT;
1031 thisdigit &= PyLong_MASK;
1032 }
1033 /* Because we're going LSB to MSB, thisdigit is more
1034 significant than what's already in accum, so needs to be
1035 prepended to accum. */
1036 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 /* The most-significant digit may be (probably is) at least
1039 partly empty. */
1040 if (i == ndigits - 1) {
1041 /* Count # of sign bits -- they needn't be stored,
1042 * although for signed conversion we need later to
1043 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +00001044 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 while (s != 0) {
1046 s >>= 1;
1047 accumbits++;
1048 }
1049 }
1050 else
1051 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 /* Store as many bytes as possible. */
1054 while (accumbits >= 8) {
1055 if (j >= n)
1056 goto Overflow;
1057 ++j;
1058 *p = (unsigned char)(accum & 0xff);
1059 p += pincr;
1060 accumbits -= 8;
1061 accum >>= 8;
1062 }
1063 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 /* Store the straggler (if any). */
1066 assert(accumbits < 8);
1067 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1068 if (accumbits > 0) {
1069 if (j >= n)
1070 goto Overflow;
1071 ++j;
1072 if (do_twos_comp) {
1073 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +03001074 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 infinite supply of sign bits). */
1076 accum |= (~(twodigits)0) << accumbits;
1077 }
1078 *p = (unsigned char)(accum & 0xff);
1079 p += pincr;
1080 }
1081 else if (j == n && n > 0 && is_signed) {
1082 /* The main loop filled the byte array exactly, so the code
1083 just above didn't get to ensure there's a sign bit, and the
1084 loop below wouldn't add one either. Make sure a sign bit
1085 exists. */
1086 unsigned char msb = *(p - pincr);
1087 int sign_bit_set = msb >= 0x80;
1088 assert(accumbits == 0);
1089 if (sign_bit_set == do_twos_comp)
1090 return 0;
1091 else
1092 goto Overflow;
1093 }
Tim Peters05607ad2001-06-13 21:01:27 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 /* Fill remaining bytes with copies of the sign bit. */
1096 {
1097 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1098 for ( ; j < n; ++j, p += pincr)
1099 *p = signbyte;
1100 }
Tim Peters05607ad2001-06-13 21:01:27 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001103
Mark Dickinson22b20182010-05-10 21:27:53 +00001104 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1106 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001107
Tim Peters2a9b3672001-06-11 21:23:58 +00001108}
1109
Serhiy Storchaka95949422013-08-27 19:40:23 +03001110/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001111
1112PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001113PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001114{
Mark Dickinson91044792012-10-18 19:21:43 +01001115#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001116 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001117#else
1118
Tim Peters70128a12001-06-16 08:48:40 +00001119#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001120# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001121#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001122 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001123#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001124
Guido van Rossum78694d91998-09-18 14:14:13 +00001125}
1126
Serhiy Storchaka95949422013-08-27 19:40:23 +03001127/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001128
1129void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001130PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001131{
Tim Peters70128a12001-06-16 08:48:40 +00001132#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1136 x = PyLong_AsLong(vv);
1137 else
1138 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001139#else
Tim Peters70128a12001-06-16 08:48:40 +00001140
Tim Peters70128a12001-06-16 08:48:40 +00001141#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001142# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001143#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001144 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1147 x = PyLong_AsLongLong(vv);
1148 else
1149 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001150
1151#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (x == -1 && PyErr_Occurred())
1154 return NULL;
1155 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001156}
1157
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001158/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001159 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001160 */
1161
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001162#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001163
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001164/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001165
1166PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001167PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001170 unsigned long long abs_ival;
1171 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 int ndigits = 0;
1173 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001174
animalize6b519982019-09-06 14:00:56 +08001175 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001176 return get_small_int((sdigit)ival);
1177 }
1178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (ival < 0) {
1180 /* avoid signed overflow on negation; see comments
1181 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001182 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 negative = 1;
1184 }
1185 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001186 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 /* Count the number of Python digits.
1190 We used to pick 5 ("big enough for anything"), but that's a
1191 waste of time and space given that 5*15 = 75 bits are rarely
1192 needed. */
1193 t = abs_ival;
1194 while (t) {
1195 ++ndigits;
1196 t >>= PyLong_SHIFT;
1197 }
1198 v = _PyLong_New(ndigits);
1199 if (v != NULL) {
1200 digit *p = v->ob_digit;
1201 Py_SIZE(v) = negative ? -ndigits : ndigits;
1202 t = abs_ival;
1203 while (t) {
1204 *p++ = (digit)(t & PyLong_MASK);
1205 t >>= PyLong_SHIFT;
1206 }
1207 }
1208 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001209}
1210
Serhiy Storchaka95949422013-08-27 19:40:23 +03001211/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001212
1213PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001214PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyLongObject *v;
1217 size_t abs_ival;
1218 size_t t; /* unsigned so >> doesn't propagate sign bit */
1219 int ndigits = 0;
1220 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001221
animalize6b519982019-09-06 14:00:56 +08001222 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001223 return get_small_int((sdigit)ival);
1224 }
1225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 if (ival < 0) {
1227 /* avoid signed overflow when ival = SIZE_T_MIN */
1228 abs_ival = (size_t)(-1-ival)+1;
1229 negative = 1;
1230 }
1231 else {
1232 abs_ival = (size_t)ival;
1233 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 /* Count the number of Python digits. */
1236 t = abs_ival;
1237 while (t) {
1238 ++ndigits;
1239 t >>= PyLong_SHIFT;
1240 }
1241 v = _PyLong_New(ndigits);
1242 if (v != NULL) {
1243 digit *p = v->ob_digit;
1244 Py_SIZE(v) = negative ? -ndigits : ndigits;
1245 t = abs_ival;
1246 while (t) {
1247 *p++ = (digit)(t & PyLong_MASK);
1248 t >>= PyLong_SHIFT;
1249 }
1250 }
1251 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001252}
1253
Serhiy Storchaka95949422013-08-27 19:40:23 +03001254/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001255 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001256
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001257long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001258PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001261 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001263 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (vv == NULL) {
1266 PyErr_BadInternalCall();
1267 return -1;
1268 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001269
1270 if (PyLong_Check(vv)) {
1271 v = (PyLongObject *)vv;
1272 }
1273 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001274 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001275 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001277 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001279
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001280 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001282 case -1:
1283 bytes = -(sdigit)v->ob_digit[0];
1284 break;
1285 case 0:
1286 bytes = 0;
1287 break;
1288 case 1:
1289 bytes = v->ob_digit[0];
1290 break;
1291 default:
1292 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001293 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001295 if (do_decref) {
1296 Py_DECREF(v);
1297 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001298
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001299 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001301 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 else
1303 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001304}
1305
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001306/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001307 Return -1 and set an error if overflow occurs. */
1308
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001309unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001310PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001313 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001315
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001316 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001318 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001320 if (!PyLong_Check(vv)) {
1321 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001322 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001323 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 v = (PyLongObject*)vv;
1326 switch(Py_SIZE(v)) {
1327 case 0: return 0;
1328 case 1: return v->ob_digit[0];
1329 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001330
Mark Dickinson22b20182010-05-10 21:27:53 +00001331 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001332 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001333
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001334 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001336 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 else
1338 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001339}
Tim Petersd1a7da62001-06-13 00:35:57 +00001340
Serhiy Storchaka95949422013-08-27 19:40:23 +03001341/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001342 Returns -1 and sets an error condition if an error occurs. */
1343
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001344static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001345_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001346{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001347 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001348 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 Py_ssize_t i;
1350 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 if (vv == NULL || !PyLong_Check(vv)) {
1353 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001354 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 }
1356 v = (PyLongObject *)vv;
1357 switch(Py_SIZE(v)) {
1358 case 0: return 0;
1359 case 1: return v->ob_digit[0];
1360 }
1361 i = Py_SIZE(v);
1362 sign = 1;
1363 x = 0;
1364 if (i < 0) {
1365 sign = -1;
1366 i = -i;
1367 }
1368 while (--i >= 0) {
1369 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1370 }
1371 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001372}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001373
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001374unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001375PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001378 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001379
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001380 if (op == NULL) {
1381 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001382 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001384
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001385 if (PyLong_Check(op)) {
1386 return _PyLong_AsUnsignedLongLongMask(op);
1387 }
1388
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001389 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001391 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001392
1393 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1394 Py_DECREF(lo);
1395 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001396}
Tim Petersd1a7da62001-06-13 00:35:57 +00001397
Serhiy Storchaka95949422013-08-27 19:40:23 +03001398/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001399 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001400
Mark Dickinson8d48b432011-10-23 20:47:14 +01001401 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1402 the result. Otherwise *overflow is 0.
1403
1404 For other errors (e.g., TypeError), return -1 and set an error condition.
1405 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001406*/
1407
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001408long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001409PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001412 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001413 unsigned long long x, prev;
1414 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 Py_ssize_t i;
1416 int sign;
1417 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 *overflow = 0;
1420 if (vv == NULL) {
1421 PyErr_BadInternalCall();
1422 return -1;
1423 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001424
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001425 if (PyLong_Check(vv)) {
1426 v = (PyLongObject *)vv;
1427 }
1428 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001429 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001430 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 return -1;
1432 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 switch (i) {
1439 case -1:
1440 res = -(sdigit)v->ob_digit[0];
1441 break;
1442 case 0:
1443 res = 0;
1444 break;
1445 case 1:
1446 res = v->ob_digit[0];
1447 break;
1448 default:
1449 sign = 1;
1450 x = 0;
1451 if (i < 0) {
1452 sign = -1;
1453 i = -(i);
1454 }
1455 while (--i >= 0) {
1456 prev = x;
1457 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1458 if ((x >> PyLong_SHIFT) != prev) {
1459 *overflow = sign;
1460 goto exit;
1461 }
1462 }
1463 /* Haven't lost any bits, but casting to long requires extra
1464 * care (see comment above).
1465 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001466 if (x <= (unsigned long long)PY_LLONG_MAX) {
1467 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 }
1469 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1470 res = PY_LLONG_MIN;
1471 }
1472 else {
1473 *overflow = sign;
1474 /* res is already set to -1 */
1475 }
1476 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001477 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001479 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 }
1481 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001482}
1483
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001484int
1485_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1486{
1487 unsigned long uval;
1488
1489 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1490 PyErr_SetString(PyExc_ValueError, "value must be positive");
1491 return 0;
1492 }
1493 uval = PyLong_AsUnsignedLong(obj);
1494 if (uval == (unsigned long)-1 && PyErr_Occurred())
1495 return 0;
1496 if (uval > USHRT_MAX) {
1497 PyErr_SetString(PyExc_OverflowError,
1498 "Python int too large for C unsigned short");
1499 return 0;
1500 }
1501
1502 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1503 return 1;
1504}
1505
1506int
1507_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1508{
1509 unsigned long uval;
1510
1511 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1512 PyErr_SetString(PyExc_ValueError, "value must be positive");
1513 return 0;
1514 }
1515 uval = PyLong_AsUnsignedLong(obj);
1516 if (uval == (unsigned long)-1 && PyErr_Occurred())
1517 return 0;
1518 if (uval > UINT_MAX) {
1519 PyErr_SetString(PyExc_OverflowError,
1520 "Python int too large for C unsigned int");
1521 return 0;
1522 }
1523
1524 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1525 return 1;
1526}
1527
1528int
1529_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1530{
1531 unsigned long uval;
1532
1533 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1534 PyErr_SetString(PyExc_ValueError, "value must be positive");
1535 return 0;
1536 }
1537 uval = PyLong_AsUnsignedLong(obj);
1538 if (uval == (unsigned long)-1 && PyErr_Occurred())
1539 return 0;
1540
1541 *(unsigned long *)ptr = uval;
1542 return 1;
1543}
1544
1545int
1546_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1547{
1548 unsigned long long uval;
1549
1550 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1551 PyErr_SetString(PyExc_ValueError, "value must be positive");
1552 return 0;
1553 }
1554 uval = PyLong_AsUnsignedLongLong(obj);
1555 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1556 return 0;
1557
1558 *(unsigned long long *)ptr = uval;
1559 return 1;
1560}
1561
1562int
1563_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1564{
1565 size_t uval;
1566
1567 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1568 PyErr_SetString(PyExc_ValueError, "value must be positive");
1569 return 0;
1570 }
1571 uval = PyLong_AsSize_t(obj);
1572 if (uval == (size_t)-1 && PyErr_Occurred())
1573 return 0;
1574
1575 *(size_t *)ptr = uval;
1576 return 1;
1577}
1578
1579
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001580#define CHECK_BINOP(v,w) \
1581 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001582 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1583 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001584 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001585
Tim Peters877a2122002-08-12 05:09:36 +00001586/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1587 * is modified in place, by adding y to it. Carries are propagated as far as
1588 * x[m-1], and the remaining carry (0 or 1) is returned.
1589 */
1590static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001591v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 Py_ssize_t i;
1594 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 assert(m >= n);
1597 for (i = 0; i < n; ++i) {
1598 carry += x[i] + y[i];
1599 x[i] = carry & PyLong_MASK;
1600 carry >>= PyLong_SHIFT;
1601 assert((carry & 1) == carry);
1602 }
1603 for (; carry && i < m; ++i) {
1604 carry += x[i];
1605 x[i] = carry & PyLong_MASK;
1606 carry >>= PyLong_SHIFT;
1607 assert((carry & 1) == carry);
1608 }
1609 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001610}
1611
1612/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1613 * is modified in place, by subtracting y from it. Borrows are propagated as
1614 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1615 */
1616static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001617v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 Py_ssize_t i;
1620 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 assert(m >= n);
1623 for (i = 0; i < n; ++i) {
1624 borrow = x[i] - y[i] - borrow;
1625 x[i] = borrow & PyLong_MASK;
1626 borrow >>= PyLong_SHIFT;
1627 borrow &= 1; /* keep only 1 sign bit */
1628 }
1629 for (; borrow && i < m; ++i) {
1630 borrow = x[i] - borrow;
1631 x[i] = borrow & PyLong_MASK;
1632 borrow >>= PyLong_SHIFT;
1633 borrow &= 1;
1634 }
1635 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001636}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001637
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001638/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1639 * result in z[0:m], and return the d bits shifted out of the top.
1640 */
1641static digit
1642v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 Py_ssize_t i;
1645 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 assert(0 <= d && d < PyLong_SHIFT);
1648 for (i=0; i < m; i++) {
1649 twodigits acc = (twodigits)a[i] << d | carry;
1650 z[i] = (digit)acc & PyLong_MASK;
1651 carry = (digit)(acc >> PyLong_SHIFT);
1652 }
1653 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001654}
1655
1656/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1657 * result in z[0:m], and return the d bits shifted out of the bottom.
1658 */
1659static digit
1660v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 Py_ssize_t i;
1663 digit carry = 0;
1664 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 assert(0 <= d && d < PyLong_SHIFT);
1667 for (i=m; i-- > 0;) {
1668 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1669 carry = (digit)acc & mask;
1670 z[i] = (digit)(acc >> d);
1671 }
1672 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001673}
1674
Tim Peters212e6142001-07-14 12:23:19 +00001675/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1676 in pout, and returning the remainder. pin and pout point at the LSD.
1677 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001678 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001679 immutable. */
1680
1681static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001682inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 assert(n > 0 && n <= PyLong_MASK);
1687 pin += size;
1688 pout += size;
1689 while (--size >= 0) {
1690 digit hi;
1691 rem = (rem << PyLong_SHIFT) | *--pin;
1692 *--pout = hi = (digit)(rem / n);
1693 rem -= (twodigits)hi * n;
1694 }
1695 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001696}
1697
Serhiy Storchaka95949422013-08-27 19:40:23 +03001698/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001699 (as function result) and the remainder (through *prem).
1700 The sign of a is ignored; n should not be zero. */
1701
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001702static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001703divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001704{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001705 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 assert(n > 0 && n <= PyLong_MASK);
1709 z = _PyLong_New(size);
1710 if (z == NULL)
1711 return NULL;
1712 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1713 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001714}
1715
Serhiy Storchaka95949422013-08-27 19:40:23 +03001716/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001717 string. (Return value is non-shared so that callers can modify the
1718 returned value if necessary.) */
1719
Victor Stinnerd3f08822012-05-29 12:57:52 +02001720static int
1721long_to_decimal_string_internal(PyObject *aa,
1722 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001723 _PyUnicodeWriter *writer,
1724 _PyBytesWriter *bytes_writer,
1725 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001728 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 Py_ssize_t size, strlen, size_a, i, j;
1730 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001732 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001733 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 a = (PyLongObject *)aa;
1736 if (a == NULL || !PyLong_Check(a)) {
1737 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001738 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001740 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 /* quick and dirty upper bound for the number of digits
1744 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 But log2(a) < size_a * PyLong_SHIFT, and
1749 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001750 > 3.3 * _PyLong_DECIMAL_SHIFT
1751
1752 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1753 size_a + size_a / d < size_a + size_a / floor(d),
1754 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1755 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001757 d = (33 * _PyLong_DECIMAL_SHIFT) /
1758 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1759 assert(size_a < PY_SSIZE_T_MAX/2);
1760 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 scratch = _PyLong_New(size);
1762 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001763 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 /* convert array of base _PyLong_BASE digits in pin to an array of
1766 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1767 Volume 2 (3rd edn), section 4.4, Method 1b). */
1768 pin = a->ob_digit;
1769 pout = scratch->ob_digit;
1770 size = 0;
1771 for (i = size_a; --i >= 0; ) {
1772 digit hi = pin[i];
1773 for (j = 0; j < size; j++) {
1774 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1775 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1776 pout[j] = (digit)(z - (twodigits)hi *
1777 _PyLong_DECIMAL_BASE);
1778 }
1779 while (hi) {
1780 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1781 hi /= _PyLong_DECIMAL_BASE;
1782 }
1783 /* check for keyboard interrupt */
1784 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001785 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001786 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001787 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 }
1789 /* pout should have at least one digit, so that the case when a = 0
1790 works correctly */
1791 if (size == 0)
1792 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 /* calculate exact length of output string, and allocate */
1795 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1796 tenpow = 10;
1797 rem = pout[size-1];
1798 while (rem >= tenpow) {
1799 tenpow *= 10;
1800 strlen++;
1801 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001802 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001803 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1804 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001805 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001806 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001807 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001809 else if (bytes_writer) {
1810 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1811 if (*bytes_str == NULL) {
1812 Py_DECREF(scratch);
1813 return -1;
1814 }
1815 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001816 else {
1817 str = PyUnicode_New(strlen, '9');
1818 if (str == NULL) {
1819 Py_DECREF(scratch);
1820 return -1;
1821 }
1822 kind = PyUnicode_KIND(str);
1823 }
1824
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001825#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001826 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001827 /* pout[0] through pout[size-2] contribute exactly \
1828 _PyLong_DECIMAL_SHIFT digits each */ \
1829 for (i=0; i < size - 1; i++) { \
1830 rem = pout[i]; \
1831 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1832 *--p = '0' + rem % 10; \
1833 rem /= 10; \
1834 } \
1835 } \
1836 /* pout[size-1]: always produce at least one decimal digit */ \
1837 rem = pout[i]; \
1838 do { \
1839 *--p = '0' + rem % 10; \
1840 rem /= 10; \
1841 } while (rem != 0); \
1842 \
1843 /* and sign */ \
1844 if (negative) \
1845 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001846 } while (0)
1847
1848#define WRITE_UNICODE_DIGITS(TYPE) \
1849 do { \
1850 if (writer) \
1851 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1852 else \
1853 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1854 \
1855 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001856 \
1857 /* check we've counted correctly */ \
1858 if (writer) \
1859 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1860 else \
1861 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1862 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001865 if (bytes_writer) {
1866 char *p = *bytes_str + strlen;
1867 WRITE_DIGITS(p);
1868 assert(p == *bytes_str);
1869 }
1870 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001871 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001872 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001874 else if (kind == PyUnicode_2BYTE_KIND) {
1875 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001876 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001877 }
1878 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001879 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001880 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001881 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001882 }
1883#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001884#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001887 if (writer) {
1888 writer->pos += strlen;
1889 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001890 else if (bytes_writer) {
1891 (*bytes_str) += strlen;
1892 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001893 else {
1894 assert(_PyUnicode_CheckConsistency(str, 1));
1895 *p_output = (PyObject *)str;
1896 }
1897 return 0;
1898}
1899
1900static PyObject *
1901long_to_decimal_string(PyObject *aa)
1902{
1903 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001904 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001905 return NULL;
1906 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001907}
1908
Serhiy Storchaka95949422013-08-27 19:40:23 +03001909/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001910 which should be one of 2, 8 or 16. Return a string object.
1911 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1912 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001913
Victor Stinnerd3f08822012-05-29 12:57:52 +02001914static int
1915long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001916 PyObject **p_output, _PyUnicodeWriter *writer,
1917 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001918{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001919 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001920 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001921 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001923 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001924 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001926
Victor Stinnerd3f08822012-05-29 12:57:52 +02001927 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 if (a == NULL || !PyLong_Check(a)) {
1929 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001930 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001932 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001933 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 /* Compute a rough upper bound for the length of the string */
1936 switch (base) {
1937 case 16:
1938 bits = 4;
1939 break;
1940 case 8:
1941 bits = 3;
1942 break;
1943 case 2:
1944 bits = 1;
1945 break;
1946 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001947 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001949
Mark Dickinsone2846542012-04-20 21:21:24 +01001950 /* Compute exact length 'sz' of output string. */
1951 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001952 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001953 }
1954 else {
1955 Py_ssize_t size_a_in_bits;
1956 /* Ensure overflow doesn't occur during computation of sz. */
1957 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1958 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001959 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001960 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001961 }
1962 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1963 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001964 /* Allow 1 character for a '-' sign. */
1965 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1966 }
1967 if (alternate) {
1968 /* 2 characters for prefix */
1969 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001970 }
1971
Victor Stinnerd3f08822012-05-29 12:57:52 +02001972 if (writer) {
1973 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1974 return -1;
1975 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001977 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001978 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1979 if (*bytes_str == NULL)
1980 return -1;
1981 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001983 v = PyUnicode_New(sz, 'x');
1984 if (v == NULL)
1985 return -1;
1986 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001988
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001989#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001990 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001991 if (size_a == 0) { \
1992 *--p = '0'; \
1993 } \
1994 else { \
1995 /* JRH: special case for power-of-2 bases */ \
1996 twodigits accum = 0; \
1997 int accumbits = 0; /* # of bits in accum */ \
1998 Py_ssize_t i; \
1999 for (i = 0; i < size_a; ++i) { \
2000 accum |= (twodigits)a->ob_digit[i] << accumbits; \
2001 accumbits += PyLong_SHIFT; \
2002 assert(accumbits >= bits); \
2003 do { \
2004 char cdigit; \
2005 cdigit = (char)(accum & (base - 1)); \
2006 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
2007 *--p = cdigit; \
2008 accumbits -= bits; \
2009 accum >>= bits; \
2010 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
2011 } \
2012 } \
2013 \
2014 if (alternate) { \
2015 if (base == 16) \
2016 *--p = 'x'; \
2017 else if (base == 8) \
2018 *--p = 'o'; \
2019 else /* (base == 2) */ \
2020 *--p = 'b'; \
2021 *--p = '0'; \
2022 } \
2023 if (negative) \
2024 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002025 } while (0)
2026
2027#define WRITE_UNICODE_DIGITS(TYPE) \
2028 do { \
2029 if (writer) \
2030 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
2031 else \
2032 p = (TYPE*)PyUnicode_DATA(v) + sz; \
2033 \
2034 WRITE_DIGITS(p); \
2035 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002036 if (writer) \
2037 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2038 else \
2039 assert(p == (TYPE*)PyUnicode_DATA(v)); \
2040 } while (0)
2041
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002042 if (bytes_writer) {
2043 char *p = *bytes_str + sz;
2044 WRITE_DIGITS(p);
2045 assert(p == *bytes_str);
2046 }
2047 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002048 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002049 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002050 }
2051 else if (kind == PyUnicode_2BYTE_KIND) {
2052 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002053 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002054 }
2055 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002056 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002057 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002058 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002059 }
2060#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002061#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002062
2063 if (writer) {
2064 writer->pos += sz;
2065 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002066 else if (bytes_writer) {
2067 (*bytes_str) += sz;
2068 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002069 else {
2070 assert(_PyUnicode_CheckConsistency(v, 1));
2071 *p_output = v;
2072 }
2073 return 0;
2074}
2075
2076PyObject *
2077_PyLong_Format(PyObject *obj, int base)
2078{
2079 PyObject *str;
2080 int err;
2081 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002082 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002083 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002084 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002085 if (err == -1)
2086 return NULL;
2087 return str;
2088}
2089
2090int
2091_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2092 PyObject *obj,
2093 int base, int alternate)
2094{
2095 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002096 return long_to_decimal_string_internal(obj, NULL, writer,
2097 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002098 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002099 return long_format_binary(obj, base, alternate, NULL, writer,
2100 NULL, NULL);
2101}
2102
2103char*
2104_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2105 PyObject *obj,
2106 int base, int alternate)
2107{
2108 char *str2;
2109 int res;
2110 str2 = str;
2111 if (base == 10)
2112 res = long_to_decimal_string_internal(obj, NULL, NULL,
2113 writer, &str2);
2114 else
2115 res = long_format_binary(obj, base, alternate, NULL, NULL,
2116 writer, &str2);
2117 if (res < 0)
2118 return NULL;
2119 assert(str2 != NULL);
2120 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002121}
2122
Thomas Wouters477c8d52006-05-27 19:21:47 +00002123/* Table of digit values for 8-bit string -> integer conversion.
2124 * '0' maps to 0, ..., '9' maps to 9.
2125 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2126 * All other indices map to 37.
2127 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002128 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002129 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002130unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2132 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2133 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2134 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2135 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2136 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2137 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2138 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2139 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2140 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2141 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2142 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2143 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2144 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2145 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2146 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002147};
2148
2149/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002150 * 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 +03002151 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002152 * The point to this routine is that it takes time linear in the number of
2153 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002154 *
2155 * Return values:
2156 * -1 on syntax error (exception needs to be set, *res is untouched)
2157 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002158 */
Brett Cannona721aba2016-09-09 14:57:09 -07002159static int
2160long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002161{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002162 const char *p = *str;
2163 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002164 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002165 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 int bits_per_char;
2167 Py_ssize_t n;
2168 PyLongObject *z;
2169 twodigits accum;
2170 int bits_in_accum;
2171 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2174 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002175 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002177 }
2178 /* count digits and set p to end-of-string */
2179 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2180 if (*p == '_') {
2181 if (prev == '_') {
2182 *str = p - 1;
2183 return -1;
2184 }
2185 } else {
2186 ++digits;
2187 }
2188 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002190 }
2191 if (prev == '_') {
2192 /* Trailing underscore not allowed. */
2193 *str = p - 1;
2194 return -1;
2195 }
2196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002198 /* n <- the number of Python digits needed,
2199 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2200 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 PyErr_SetString(PyExc_ValueError,
2202 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002203 *res = NULL;
2204 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002206 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002208 if (z == NULL) {
2209 *res = NULL;
2210 return 0;
2211 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002212 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 * from least to most significant in both.
2214 */
2215 accum = 0;
2216 bits_in_accum = 0;
2217 pdigit = z->ob_digit;
2218 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002219 int k;
2220 if (*p == '_') {
2221 continue;
2222 }
2223 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 assert(k >= 0 && k < base);
2225 accum |= (twodigits)k << bits_in_accum;
2226 bits_in_accum += bits_per_char;
2227 if (bits_in_accum >= PyLong_SHIFT) {
2228 *pdigit++ = (digit)(accum & PyLong_MASK);
2229 assert(pdigit - z->ob_digit <= n);
2230 accum >>= PyLong_SHIFT;
2231 bits_in_accum -= PyLong_SHIFT;
2232 assert(bits_in_accum < PyLong_SHIFT);
2233 }
2234 }
2235 if (bits_in_accum) {
2236 assert(bits_in_accum <= PyLong_SHIFT);
2237 *pdigit++ = (digit)accum;
2238 assert(pdigit - z->ob_digit <= n);
2239 }
2240 while (pdigit - z->ob_digit < n)
2241 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002242 *res = long_normalize(z);
2243 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002244}
2245
Serhiy Storchaka95949422013-08-27 19:40:23 +03002246/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002247 * ignored.
2248 *
2249 * If successful, a PyLong object will be returned and 'pend' will be pointing
2250 * to the first unused byte unless it's NULL.
2251 *
2252 * If unsuccessful, NULL will be returned.
2253 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002254PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002255PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002258 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 PyLongObject *z = NULL;
2260 PyObject *strobj;
2261 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 if ((base != 0 && base < 2) || base > 36) {
2264 PyErr_SetString(PyExc_ValueError,
2265 "int() arg 2 must be >= 2 and <= 36");
2266 return NULL;
2267 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002268 while (*str != '\0' && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002270 }
2271 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002273 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 else if (*str == '-') {
2275 ++str;
2276 sign = -1;
2277 }
2278 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002279 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002281 }
2282 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002284 }
2285 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002287 }
2288 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 else {
2292 /* "old" (C-style) octal literal, now invalid.
2293 it might still be zero though */
2294 error_if_nonzero = 1;
2295 base = 10;
2296 }
2297 }
2298 if (str[0] == '0' &&
2299 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2300 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002301 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002303 /* One underscore allowed here. */
2304 if (*str == '_') {
2305 ++str;
2306 }
2307 }
2308 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002309 /* May not start with underscores. */
2310 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002311 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002314 if ((base & (base - 1)) == 0) {
2315 int res = long_from_binary_base(&str, base, &z);
2316 if (res < 0) {
2317 /* Syntax error. */
2318 goto onError;
2319 }
2320 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002322/***
2323Binary bases can be converted in time linear in the number of digits, because
2324Python's representation base is binary. Other bases (including decimal!) use
2325the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002326
Thomas Wouters477c8d52006-05-27 19:21:47 +00002327First some math: the largest integer that can be expressed in N base-B digits
2328is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2329case number of Python digits needed to hold it is the smallest integer n s.t.
2330
2331 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2332 BASE**n >= B**N [taking logs to base BASE]
2333 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2334
2335The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002336this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002337and the result is computed into it.
2338
2339The input string is actually treated as being in base base**i (i.e., i digits
2340are processed at a time), where two more static arrays hold:
2341
2342 convwidth_base[base] = the largest integer i such that base**i <= BASE
2343 convmultmax_base[base] = base ** convwidth_base[base]
2344
2345The first of these is the largest i such that i consecutive input digits
2346must fit in a single Python digit. The second is effectively the input
2347base we're really using.
2348
2349Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2350convmultmax_base[base], the result is "simply"
2351
2352 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2353
2354where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002355
2356Error analysis: as above, the number of Python digits `n` needed is worst-
2357case
2358
2359 n >= N * log(B)/log(BASE)
2360
2361where `N` is the number of input digits in base `B`. This is computed via
2362
2363 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2364
2365below. Two numeric concerns are how much space this can waste, and whether
2366the computed result can be too small. To be concrete, assume BASE = 2**15,
2367which is the default (and it's unlikely anyone changes that).
2368
2369Waste isn't a problem: provided the first input digit isn't 0, the difference
2370between the worst-case input with N digits and the smallest input with N
2371digits is about a factor of B, but B is small compared to BASE so at most
2372one allocated Python digit can remain unused on that count. If
2373N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2374and adding 1 returns a result 1 larger than necessary. However, that can't
2375happen: whenever B is a power of 2, long_from_binary_base() is called
2376instead, and it's impossible for B**i to be an integer power of 2**15 when
2377B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2378an exact integer when B is not a power of 2, since B**i has a prime factor
2379other than 2 in that case, but (2**15)**j's only prime factor is 2).
2380
2381The computed result can be too small if the true value of N*log(B)/log(BASE)
2382is a little bit larger than an exact integer, but due to roundoff errors (in
2383computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2384yields a numeric result a little less than that integer. Unfortunately, "how
2385close can a transcendental function get to an integer over some range?"
2386questions are generally theoretically intractable. Computer analysis via
2387continued fractions is practical: expand log(B)/log(BASE) via continued
2388fractions, giving a sequence i/j of "the best" rational approximations. Then
2389j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2390we can get very close to being in trouble, but very rarely. For example,
239176573 is a denominator in one of the continued-fraction approximations to
2392log(10)/log(2**15), and indeed:
2393
2394 >>> log(10)/log(2**15)*76573
2395 16958.000000654003
2396
2397is very close to an integer. If we were working with IEEE single-precision,
2398rounding errors could kill us. Finding worst cases in IEEE double-precision
2399requires better-than-double-precision log() functions, and Tim didn't bother.
2400Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002401new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002402This should happen extremely rarely, and in fact I don't have a test case
2403that triggers it(!). Instead the code was tested by artificially allocating
2404just 1 digit at the start, so that the copying code was exercised for every
2405digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002406***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002407 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002409 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 int i;
2411 int convwidth;
2412 twodigits convmultmax, convmult;
2413 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002414 const char *scan, *lastdigit;
2415 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 static double log_base_BASE[37] = {0.0e0,};
2418 static int convwidth_base[37] = {0,};
2419 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 if (log_base_BASE[base] == 0.0) {
2422 twodigits convmax = base;
2423 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002424
Mark Dickinson22b20182010-05-10 21:27:53 +00002425 log_base_BASE[base] = (log((double)base) /
2426 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 for (;;) {
2428 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002429 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 convmax = next;
2433 ++i;
2434 }
2435 convmultmax_base[base] = convmax;
2436 assert(i > 0);
2437 convwidth_base[base] = i;
2438 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 /* Find length of the string of numeric characters. */
2441 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002442 lastdigit = str;
2443
2444 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2445 if (*scan == '_') {
2446 if (prev == '_') {
2447 /* Only one underscore allowed. */
2448 str = lastdigit + 1;
2449 goto onError;
2450 }
2451 }
2452 else {
2453 ++digits;
2454 lastdigit = scan;
2455 }
2456 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002458 }
2459 if (prev == '_') {
2460 /* Trailing underscore not allowed. */
2461 /* Set error pointer to first underscore. */
2462 str = lastdigit + 1;
2463 goto onError;
2464 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002465
Serhiy Storchaka95949422013-08-27 19:40:23 +03002466 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 * integer with this base and length. Note that there's no
2468 * need to initialize z->ob_digit -- no slot is read up before
2469 * being stored into.
2470 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002471 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2472 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002473 /* The same exception as in _PyLong_New(). */
2474 PyErr_SetString(PyExc_OverflowError,
2475 "too many digits in integer");
2476 return NULL;
2477 }
2478 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 /* Uncomment next line to test exceedingly rare copy code */
2480 /* size_z = 1; */
2481 assert(size_z > 0);
2482 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002483 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002485 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 /* `convwidth` consecutive input digits are treated as a single
2489 * digit in base `convmultmax`.
2490 */
2491 convwidth = convwidth_base[base];
2492 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* Work ;-) */
2495 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002496 if (*str == '_') {
2497 str++;
2498 continue;
2499 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 /* grab up to convwidth digits from the input string */
2501 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002502 for (i = 1; i < convwidth && str != scan; ++str) {
2503 if (*str == '_') {
2504 continue;
2505 }
2506 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002508 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 assert(c < PyLong_BASE);
2510 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 convmult = convmultmax;
2513 /* Calculate the shift only if we couldn't get
2514 * convwidth digits.
2515 */
2516 if (i != convwidth) {
2517 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002518 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002520 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 /* Multiply z by convmult, and add c. */
2524 pz = z->ob_digit;
2525 pzstop = pz + Py_SIZE(z);
2526 for (; pz < pzstop; ++pz) {
2527 c += (twodigits)*pz * convmult;
2528 *pz = (digit)(c & PyLong_MASK);
2529 c >>= PyLong_SHIFT;
2530 }
2531 /* carry off the current end? */
2532 if (c) {
2533 assert(c < PyLong_BASE);
2534 if (Py_SIZE(z) < size_z) {
2535 *pz = (digit)c;
2536 ++Py_SIZE(z);
2537 }
2538 else {
2539 PyLongObject *tmp;
2540 /* Extremely rare. Get more space. */
2541 assert(Py_SIZE(z) == size_z);
2542 tmp = _PyLong_New(size_z + 1);
2543 if (tmp == NULL) {
2544 Py_DECREF(z);
2545 return NULL;
2546 }
2547 memcpy(tmp->ob_digit,
2548 z->ob_digit,
2549 sizeof(digit) * size_z);
2550 Py_DECREF(z);
2551 z = tmp;
2552 z->ob_digit[size_z] = (digit)c;
2553 ++size_z;
2554 }
2555 }
2556 }
2557 }
Brett Cannona721aba2016-09-09 14:57:09 -07002558 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 if (error_if_nonzero) {
2562 /* reset the base to 0, else the exception message
2563 doesn't make too much sense */
2564 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002565 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002567 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 /* there might still be other problems, therefore base
2569 remains zero here for the same reason */
2570 }
Brett Cannona721aba2016-09-09 14:57:09 -07002571 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002573 }
2574 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002576 }
Jordon Xu2ec70102019-09-11 00:04:08 +08002577 while (*str && Py_ISSPACE(*str)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002579 }
2580 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002582 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002584 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002585 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002586 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002587 }
2588 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002589 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002590 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002591 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002592
Mark Dickinson22b20182010-05-10 21:27:53 +00002593 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002594 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002595 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002596 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 Py_XDECREF(z);
2598 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2599 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002600 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002602 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002604 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 base, strobj);
2606 Py_DECREF(strobj);
2607 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002608}
2609
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002610/* Since PyLong_FromString doesn't have a length parameter,
2611 * check here for possible NULs in the string.
2612 *
2613 * Reports an invalid literal as a bytes object.
2614 */
2615PyObject *
2616_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2617{
2618 PyObject *result, *strobj;
2619 char *end = NULL;
2620
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002621 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002622 if (end == NULL || (result != NULL && end == s + len))
2623 return result;
2624 Py_XDECREF(result);
2625 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2626 if (strobj != NULL) {
2627 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002628 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002629 base, strobj);
2630 Py_DECREF(strobj);
2631 }
2632 return NULL;
2633}
2634
Guido van Rossum9e896b32000-04-05 20:11:21 +00002635PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002636PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002637{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002638 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002639 if (unicode == NULL)
2640 return NULL;
2641 v = PyLong_FromUnicodeObject(unicode, base);
2642 Py_DECREF(unicode);
2643 return v;
2644}
2645
2646PyObject *
2647PyLong_FromUnicodeObject(PyObject *u, int base)
2648{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002649 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002650 const char *buffer;
2651 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002652 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002654 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002655 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002657 assert(PyUnicode_IS_ASCII(asciidig));
2658 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002659 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002660 assert(buffer != NULL);
2661
2662 result = PyLong_FromString(buffer, &end, base);
2663 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002664 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002665 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002667 Py_DECREF(asciidig);
2668 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002669 PyErr_Format(PyExc_ValueError,
2670 "invalid literal for int() with base %d: %.200R",
2671 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002672 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002673}
2674
Tim Peters9f688bf2000-07-07 15:53:28 +00002675/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002676static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002678static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002679
Serhiy Storchaka95949422013-08-27 19:40:23 +03002680/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002681
Guido van Rossume32e0141992-01-19 16:31:05 +00002682static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002683long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002685{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002686 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 if (size_b == 0) {
2690 PyErr_SetString(PyExc_ZeroDivisionError,
2691 "integer division or modulo by zero");
2692 return -1;
2693 }
2694 if (size_a < size_b ||
2695 (size_a == size_b &&
2696 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2697 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002698 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002699 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002700 return -1;
2701 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002702 Py_INCREF(_PyLong_Zero);
2703 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 return 0;
2705 }
2706 if (size_b == 1) {
2707 digit rem = 0;
2708 z = divrem1(a, b->ob_digit[0], &rem);
2709 if (z == NULL)
2710 return -1;
2711 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2712 if (*prem == NULL) {
2713 Py_DECREF(z);
2714 return -1;
2715 }
2716 }
2717 else {
2718 z = x_divrem(a, b, prem);
2719 if (z == NULL)
2720 return -1;
2721 }
2722 /* Set the signs.
2723 The quotient z has the sign of a*b;
2724 the remainder r has the sign of a,
2725 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002726 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2727 _PyLong_Negate(&z);
2728 if (z == NULL) {
2729 Py_CLEAR(*prem);
2730 return -1;
2731 }
2732 }
2733 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2734 _PyLong_Negate(prem);
2735 if (*prem == NULL) {
2736 Py_DECREF(z);
2737 Py_CLEAR(*prem);
2738 return -1;
2739 }
2740 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 *pdiv = maybe_small_long(z);
2742 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002743}
2744
Serhiy Storchaka95949422013-08-27 19:40:23 +03002745/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002746 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002747
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002748static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002749x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 PyLongObject *v, *w, *a;
2752 Py_ssize_t i, k, size_v, size_w;
2753 int d;
2754 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2755 twodigits vv;
2756 sdigit zhi;
2757 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2760 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2761 handle the special case when the initial estimate q for a quotient
2762 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2763 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002766 size_v = Py_ABS(Py_SIZE(v1));
2767 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2769 v = _PyLong_New(size_v+1);
2770 if (v == NULL) {
2771 *prem = NULL;
2772 return NULL;
2773 }
2774 w = _PyLong_New(size_w);
2775 if (w == NULL) {
2776 Py_DECREF(v);
2777 *prem = NULL;
2778 return NULL;
2779 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2782 shift v1 left by the same amount. Results go into w and v. */
2783 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2784 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2785 assert(carry == 0);
2786 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2787 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2788 v->ob_digit[size_v] = carry;
2789 size_v++;
2790 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2793 at most (and usually exactly) k = size_v - size_w digits. */
2794 k = size_v - size_w;
2795 assert(k >= 0);
2796 a = _PyLong_New(k);
2797 if (a == NULL) {
2798 Py_DECREF(w);
2799 Py_DECREF(v);
2800 *prem = NULL;
2801 return NULL;
2802 }
2803 v0 = v->ob_digit;
2804 w0 = w->ob_digit;
2805 wm1 = w0[size_w-1];
2806 wm2 = w0[size_w-2];
2807 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2808 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2809 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002812 Py_DECREF(a);
2813 Py_DECREF(w);
2814 Py_DECREF(v);
2815 *prem = NULL;
2816 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002817 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 /* estimate quotient digit q; may overestimate by 1 (rare) */
2820 vtop = vk[size_w];
2821 assert(vtop <= wm1);
2822 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2823 q = (digit)(vv / wm1);
2824 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2825 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2826 | vk[size_w-2])) {
2827 --q;
2828 r += wm1;
2829 if (r >= PyLong_BASE)
2830 break;
2831 }
2832 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2835 zhi = 0;
2836 for (i = 0; i < size_w; ++i) {
2837 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2838 -PyLong_BASE * q <= z < PyLong_BASE */
2839 z = (sdigit)vk[i] + zhi -
2840 (stwodigits)q * (stwodigits)w0[i];
2841 vk[i] = (digit)z & PyLong_MASK;
2842 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002843 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 /* add w back if q was too large (this branch taken rarely) */
2847 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2848 if ((sdigit)vtop + zhi < 0) {
2849 carry = 0;
2850 for (i = 0; i < size_w; ++i) {
2851 carry += vk[i] + w0[i];
2852 vk[i] = carry & PyLong_MASK;
2853 carry >>= PyLong_SHIFT;
2854 }
2855 --q;
2856 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 /* store quotient digit */
2859 assert(q < PyLong_BASE);
2860 *--ak = q;
2861 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 /* unshift remainder; we reuse w to store the result */
2864 carry = v_rshift(w0, v0, size_w, d);
2865 assert(carry==0);
2866 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 *prem = long_normalize(w);
2869 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002870}
2871
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002872/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2873 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2874 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2875 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2876 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2877 -1.0. */
2878
2879/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2880#if DBL_MANT_DIG == 53
2881#define EXP2_DBL_MANT_DIG 9007199254740992.0
2882#else
2883#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2884#endif
2885
2886double
2887_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2890 /* See below for why x_digits is always large enough. */
2891 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2892 double dx;
2893 /* Correction term for round-half-to-even rounding. For a digit x,
2894 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2895 multiple of 4, rounding ties to a multiple of 8. */
2896 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002897
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002898 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 if (a_size == 0) {
2900 /* Special case for 0: significand 0.0, exponent 0. */
2901 *e = 0;
2902 return 0.0;
2903 }
2904 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2905 /* The following is an overflow-free version of the check
2906 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2907 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2908 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2909 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002910 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2914 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 Number of digits needed for result: write // for floor division.
2917 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2926 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2929 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2930 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 in both cases.
2937 */
2938 if (a_bits <= DBL_MANT_DIG + 2) {
2939 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2940 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2941 x_size = 0;
2942 while (x_size < shift_digits)
2943 x_digits[x_size++] = 0;
2944 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2945 (int)shift_bits);
2946 x_size += a_size;
2947 x_digits[x_size++] = rem;
2948 }
2949 else {
2950 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2951 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2952 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2953 a_size - shift_digits, (int)shift_bits);
2954 x_size = a_size - shift_digits;
2955 /* For correct rounding below, we need the least significant
2956 bit of x to be 'sticky' for this shift: if any of the bits
2957 shifted out was nonzero, we set the least significant bit
2958 of x. */
2959 if (rem)
2960 x_digits[0] |= 1;
2961 else
2962 while (shift_digits > 0)
2963 if (a->ob_digit[--shift_digits]) {
2964 x_digits[0] |= 1;
2965 break;
2966 }
2967 }
Victor Stinner63941882011-09-29 00:42:28 +02002968 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 /* Round, and convert to double. */
2971 x_digits[0] += half_even_correction[x_digits[0] & 7];
2972 dx = x_digits[--x_size];
2973 while (x_size > 0)
2974 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 /* Rescale; make correction if result is 1.0. */
2977 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2978 if (dx == 1.0) {
2979 if (a_bits == PY_SSIZE_T_MAX)
2980 goto overflow;
2981 dx = 0.5;
2982 a_bits += 1;
2983 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 *e = a_bits;
2986 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002987
2988 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 /* exponent > PY_SSIZE_T_MAX */
2990 PyErr_SetString(PyExc_OverflowError,
2991 "huge integer: number of bits overflows a Py_ssize_t");
2992 *e = 0;
2993 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002994}
2995
Serhiy Storchaka95949422013-08-27 19:40:23 +03002996/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002997 using the round-half-to-even rule in the case of a tie. */
2998
2999double
3000PyLong_AsDouble(PyObject *v)
3001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 Py_ssize_t exponent;
3003 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003004
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02003005 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 PyErr_BadInternalCall();
3007 return -1.0;
3008 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02003009 if (!PyLong_Check(v)) {
3010 PyErr_SetString(PyExc_TypeError, "an integer is required");
3011 return -1.0;
3012 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05003013 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05003014 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01003015 to double. This improves performance of FP/long operations
3016 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05003017 */
3018 return (double)MEDIUM_VALUE((PyLongObject *)v);
3019 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
3021 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
3022 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01003023 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 return -1.0;
3025 }
3026 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003027}
3028
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003029/* Methods */
3030
HongWeipeng42acb7b2019-09-18 23:10:15 +08003031/* if a < b, return a negative number
3032 if a == b, return 0
3033 if a > b, return a positive number */
3034
3035static Py_ssize_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003036long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003037{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003038 Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
3039 if (sign == 0) {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003040 Py_ssize_t i = Py_ABS(Py_SIZE(a));
HongWeipeng42acb7b2019-09-18 23:10:15 +08003041 sdigit diff = 0;
3042 while (--i >= 0) {
3043 diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
3044 if (diff) {
3045 break;
3046 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003048 sign = Py_SIZE(a) < 0 ? -diff : diff;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 }
HongWeipeng42acb7b2019-09-18 23:10:15 +08003050 return sign;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003051}
3052
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003053static PyObject *
3054long_richcompare(PyObject *self, PyObject *other, int op)
3055{
HongWeipeng42acb7b2019-09-18 23:10:15 +08003056 Py_ssize_t result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 CHECK_BINOP(self, other);
3058 if (self == other)
3059 result = 0;
3060 else
3061 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003062 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003063}
3064
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003065static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003066long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003067{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003068 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 Py_ssize_t i;
3070 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 i = Py_SIZE(v);
3073 switch(i) {
3074 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3075 case 0: return 0;
3076 case 1: return v->ob_digit[0];
3077 }
3078 sign = 1;
3079 x = 0;
3080 if (i < 0) {
3081 sign = -1;
3082 i = -(i);
3083 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003085 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3086 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3087 _PyHASH_MODULUS.
3088
3089 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3090 amounts to a rotation of the bits of x. To see this, write
3091
3092 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3093
3094 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3095 PyLong_SHIFT bits of x (those that are shifted out of the
3096 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3097 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3098 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3099 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3100 congruent to y modulo _PyHASH_MODULUS. So
3101
3102 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3103
3104 The right-hand side is just the result of rotating the
3105 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3106 not all _PyHASH_BITS bits of x are 1s, the same is true
3107 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3108 the reduction of x*2**PyLong_SHIFT modulo
3109 _PyHASH_MODULUS. */
3110 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3111 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003113 if (x >= _PyHASH_MODULUS)
3114 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 }
3116 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003117 if (x == (Py_uhash_t)-1)
3118 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003119 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003120}
3121
3122
Serhiy Storchaka95949422013-08-27 19:40:23 +03003123/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003124
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003125static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003126x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003127{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003128 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 PyLongObject *z;
3130 Py_ssize_t i;
3131 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 /* Ensure a is the larger of the two: */
3134 if (size_a < size_b) {
3135 { PyLongObject *temp = a; a = b; b = temp; }
3136 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003137 size_a = size_b;
3138 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 }
3140 z = _PyLong_New(size_a+1);
3141 if (z == NULL)
3142 return NULL;
3143 for (i = 0; i < size_b; ++i) {
3144 carry += a->ob_digit[i] + b->ob_digit[i];
3145 z->ob_digit[i] = carry & PyLong_MASK;
3146 carry >>= PyLong_SHIFT;
3147 }
3148 for (; i < size_a; ++i) {
3149 carry += a->ob_digit[i];
3150 z->ob_digit[i] = carry & PyLong_MASK;
3151 carry >>= PyLong_SHIFT;
3152 }
3153 z->ob_digit[i] = carry;
3154 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003155}
3156
3157/* Subtract the absolute values of two integers. */
3158
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003159static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003160x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003161{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003162 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 PyLongObject *z;
3164 Py_ssize_t i;
3165 int sign = 1;
3166 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 /* Ensure a is the larger of the two: */
3169 if (size_a < size_b) {
3170 sign = -1;
3171 { PyLongObject *temp = a; a = b; b = temp; }
3172 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003173 size_a = size_b;
3174 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 }
3176 else if (size_a == size_b) {
3177 /* Find highest digit where a and b differ: */
3178 i = size_a;
3179 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3180 ;
3181 if (i < 0)
3182 return (PyLongObject *)PyLong_FromLong(0);
3183 if (a->ob_digit[i] < b->ob_digit[i]) {
3184 sign = -1;
3185 { PyLongObject *temp = a; a = b; b = temp; }
3186 }
3187 size_a = size_b = i+1;
3188 }
3189 z = _PyLong_New(size_a);
3190 if (z == NULL)
3191 return NULL;
3192 for (i = 0; i < size_b; ++i) {
3193 /* The following assumes unsigned arithmetic
3194 works module 2**N for some N>PyLong_SHIFT. */
3195 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3196 z->ob_digit[i] = borrow & PyLong_MASK;
3197 borrow >>= PyLong_SHIFT;
3198 borrow &= 1; /* Keep only one sign bit */
3199 }
3200 for (; i < size_a; ++i) {
3201 borrow = a->ob_digit[i] - borrow;
3202 z->ob_digit[i] = borrow & PyLong_MASK;
3203 borrow >>= PyLong_SHIFT;
3204 borrow &= 1; /* Keep only one sign bit */
3205 }
3206 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003207 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003208 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003209 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003211}
3212
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003213static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003214long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003219
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003220 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003221 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 }
3223 if (Py_SIZE(a) < 0) {
3224 if (Py_SIZE(b) < 0) {
3225 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003226 if (z != NULL) {
3227 /* x_add received at least one multiple-digit int,
3228 and thus z must be a multiple-digit int.
3229 That also means z is not an element of
3230 small_ints, so negating it in-place is safe. */
3231 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003233 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 }
3235 else
3236 z = x_sub(b, a);
3237 }
3238 else {
3239 if (Py_SIZE(b) < 0)
3240 z = x_sub(a, b);
3241 else
3242 z = x_add(a, b);
3243 }
3244 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003245}
3246
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003247static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003248long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003253
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003254 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003255 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 }
3257 if (Py_SIZE(a) < 0) {
3258 if (Py_SIZE(b) < 0)
3259 z = x_sub(a, b);
3260 else
3261 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003262 if (z != NULL) {
3263 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003265 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 }
3267 else {
3268 if (Py_SIZE(b) < 0)
3269 z = x_add(a, b);
3270 else
3271 z = x_sub(a, b);
3272 }
3273 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003274}
3275
Tim Peters5af4e6c2002-08-12 02:31:19 +00003276/* Grade school multiplication, ignoring the signs.
3277 * Returns the absolute value of the product, or NULL if error.
3278 */
3279static PyLongObject *
3280x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003283 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3284 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 z = _PyLong_New(size_a + size_b);
3288 if (z == NULL)
3289 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3292 if (a == b) {
3293 /* Efficient squaring per HAC, Algorithm 14.16:
3294 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3295 * Gives slightly less than a 2x speedup when a == b,
3296 * via exploiting that each entry in the multiplication
3297 * pyramid appears twice (except for the size_a squares).
3298 */
3299 for (i = 0; i < size_a; ++i) {
3300 twodigits carry;
3301 twodigits f = a->ob_digit[i];
3302 digit *pz = z->ob_digit + (i << 1);
3303 digit *pa = a->ob_digit + i + 1;
3304 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003307 Py_DECREF(z);
3308 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003309 });
Tim Peters0973b992004-08-29 22:16:50 +00003310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 carry = *pz + f * f;
3312 *pz++ = (digit)(carry & PyLong_MASK);
3313 carry >>= PyLong_SHIFT;
3314 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 /* Now f is added in twice in each column of the
3317 * pyramid it appears. Same as adding f<<1 once.
3318 */
3319 f <<= 1;
3320 while (pa < paend) {
3321 carry += *pz + *pa++ * f;
3322 *pz++ = (digit)(carry & PyLong_MASK);
3323 carry >>= PyLong_SHIFT;
3324 assert(carry <= (PyLong_MASK << 1));
3325 }
3326 if (carry) {
3327 carry += *pz;
3328 *pz++ = (digit)(carry & PyLong_MASK);
3329 carry >>= PyLong_SHIFT;
3330 }
3331 if (carry)
3332 *pz += (digit)(carry & PyLong_MASK);
3333 assert((carry >> PyLong_SHIFT) == 0);
3334 }
3335 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003336 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 for (i = 0; i < size_a; ++i) {
3338 twodigits carry = 0;
3339 twodigits f = a->ob_digit[i];
3340 digit *pz = z->ob_digit + i;
3341 digit *pb = b->ob_digit;
3342 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003345 Py_DECREF(z);
3346 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003347 });
Tim Peters0973b992004-08-29 22:16:50 +00003348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 while (pb < pbend) {
3350 carry += *pz + *pb++ * f;
3351 *pz++ = (digit)(carry & PyLong_MASK);
3352 carry >>= PyLong_SHIFT;
3353 assert(carry <= PyLong_MASK);
3354 }
3355 if (carry)
3356 *pz += (digit)(carry & PyLong_MASK);
3357 assert((carry >> PyLong_SHIFT) == 0);
3358 }
3359 }
3360 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003361}
3362
3363/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003364 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003365 split, and sets low and high such that abs(n) == (high << size) + low,
3366 viewing the shift as being by digits. The sign bit is ignored, and
3367 the return values are >= 0.
3368 Returns 0 on success, -1 on failure.
3369*/
3370static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003371kmul_split(PyLongObject *n,
3372 Py_ssize_t size,
3373 PyLongObject **high,
3374 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 PyLongObject *hi, *lo;
3377 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003378 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003379
Victor Stinner640c35c2013-06-04 23:14:37 +02003380 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 if ((hi = _PyLong_New(size_hi)) == NULL)
3384 return -1;
3385 if ((lo = _PyLong_New(size_lo)) == NULL) {
3386 Py_DECREF(hi);
3387 return -1;
3388 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3391 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 *high = long_normalize(hi);
3394 *low = long_normalize(lo);
3395 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003396}
3397
Tim Peters60004642002-08-12 22:01:34 +00003398static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3399
Tim Peters5af4e6c2002-08-12 02:31:19 +00003400/* Karatsuba multiplication. Ignores the input signs, and returns the
3401 * absolute value of the product (or NULL if error).
3402 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3403 */
3404static PyLongObject *
3405k_mul(PyLongObject *a, PyLongObject *b)
3406{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003407 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3408 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 PyLongObject *ah = NULL;
3410 PyLongObject *al = NULL;
3411 PyLongObject *bh = NULL;
3412 PyLongObject *bl = NULL;
3413 PyLongObject *ret = NULL;
3414 PyLongObject *t1, *t2, *t3;
3415 Py_ssize_t shift; /* the number of digits we split off */
3416 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3419 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3420 * Then the original product is
3421 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3422 * By picking X to be a power of 2, "*X" is just shifting, and it's
3423 * been reduced to 3 multiplies on numbers half the size.
3424 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 /* We want to split based on the larger number; fiddle so that b
3427 * is largest.
3428 */
3429 if (asize > bsize) {
3430 t1 = a;
3431 a = b;
3432 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 i = asize;
3435 asize = bsize;
3436 bsize = i;
3437 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 /* Use gradeschool math when either number is too small. */
3440 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3441 if (asize <= i) {
3442 if (asize == 0)
3443 return (PyLongObject *)PyLong_FromLong(0);
3444 else
3445 return x_mul(a, b);
3446 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 /* If a is small compared to b, splitting on b gives a degenerate
3449 * case with ah==0, and Karatsuba may be (even much) less efficient
3450 * than "grade school" then. However, we can still win, by viewing
3451 * b as a string of "big digits", each of width a->ob_size. That
3452 * leads to a sequence of balanced calls to k_mul.
3453 */
3454 if (2 * asize <= bsize)
3455 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 /* Split a & b into hi & lo pieces. */
3458 shift = bsize >> 1;
3459 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3460 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 if (a == b) {
3463 bh = ah;
3464 bl = al;
3465 Py_INCREF(bh);
3466 Py_INCREF(bl);
3467 }
3468 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 /* The plan:
3471 * 1. Allocate result space (asize + bsize digits: that's always
3472 * enough).
3473 * 2. Compute ah*bh, and copy into result at 2*shift.
3474 * 3. Compute al*bl, and copy into result at 0. Note that this
3475 * can't overlap with #2.
3476 * 4. Subtract al*bl from the result, starting at shift. This may
3477 * underflow (borrow out of the high digit), but we don't care:
3478 * we're effectively doing unsigned arithmetic mod
3479 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3480 * borrows and carries out of the high digit can be ignored.
3481 * 5. Subtract ah*bh from the result, starting at shift.
3482 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3483 * at shift.
3484 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 /* 1. Allocate result space. */
3487 ret = _PyLong_New(asize + bsize);
3488 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003489#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 /* Fill with trash, to catch reference to uninitialized digits. */
3491 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003492#endif
Tim Peters44121a62002-08-12 06:17:58 +00003493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3495 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3496 assert(Py_SIZE(t1) >= 0);
3497 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3498 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3499 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 /* Zero-out the digits higher than the ah*bh copy. */
3502 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3503 if (i)
3504 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3505 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 /* 3. t2 <- al*bl, and copy into the low digits. */
3508 if ((t2 = k_mul(al, bl)) == NULL) {
3509 Py_DECREF(t1);
3510 goto fail;
3511 }
3512 assert(Py_SIZE(t2) >= 0);
3513 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3514 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 /* Zero out remaining digits. */
3517 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3518 if (i)
3519 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3522 * because it's fresher in cache.
3523 */
3524 i = Py_SIZE(ret) - shift; /* # digits after shift */
3525 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3526 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3529 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3532 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3533 Py_DECREF(ah);
3534 Py_DECREF(al);
3535 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 if (a == b) {
3538 t2 = t1;
3539 Py_INCREF(t2);
3540 }
3541 else if ((t2 = x_add(bh, bl)) == NULL) {
3542 Py_DECREF(t1);
3543 goto fail;
3544 }
3545 Py_DECREF(bh);
3546 Py_DECREF(bl);
3547 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 t3 = k_mul(t1, t2);
3550 Py_DECREF(t1);
3551 Py_DECREF(t2);
3552 if (t3 == NULL) goto fail;
3553 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 /* Add t3. It's not obvious why we can't run out of room here.
3556 * See the (*) comment after this function.
3557 */
3558 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3559 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003562
Mark Dickinson22b20182010-05-10 21:27:53 +00003563 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 Py_XDECREF(ret);
3565 Py_XDECREF(ah);
3566 Py_XDECREF(al);
3567 Py_XDECREF(bh);
3568 Py_XDECREF(bl);
3569 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003570}
3571
Tim Petersd6974a52002-08-13 20:37:51 +00003572/* (*) Why adding t3 can't "run out of room" above.
3573
Tim Petersab86c2b2002-08-15 20:06:00 +00003574Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3575to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003576
Tim Petersab86c2b2002-08-15 20:06:00 +000035771. For any integer i, i = c(i/2) + f(i/2). In particular,
3578 bsize = c(bsize/2) + f(bsize/2).
35792. shift = f(bsize/2)
35803. asize <= bsize
35814. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3582 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003583
Tim Petersab86c2b2002-08-15 20:06:00 +00003584We allocated asize + bsize result digits, and add t3 into them at an offset
3585of shift. This leaves asize+bsize-shift allocated digit positions for t3
3586to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3587asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003588
Tim Petersab86c2b2002-08-15 20:06:00 +00003589bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3590at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003591
Tim Petersab86c2b2002-08-15 20:06:00 +00003592If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3593digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3594most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003595
Tim Petersab86c2b2002-08-15 20:06:00 +00003596The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003597
Tim Petersab86c2b2002-08-15 20:06:00 +00003598 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003599
Tim Petersab86c2b2002-08-15 20:06:00 +00003600and we have asize + c(bsize/2) available digit positions. We need to show
3601this is always enough. An instance of c(bsize/2) cancels out in both, so
3602the question reduces to whether asize digits is enough to hold
3603(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3604then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3605asize 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 +00003606digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003607asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003608c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3609is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3610bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003611
Tim Peters48d52c02002-08-14 17:07:32 +00003612Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3613clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3614ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003615*/
3616
Tim Peters60004642002-08-12 22:01:34 +00003617/* b has at least twice the digits of a, and a is big enough that Karatsuba
3618 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3619 * of slices, each with a->ob_size digits, and multiply the slices by a,
3620 * one at a time. This gives k_mul balanced inputs to work with, and is
3621 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003622 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003623 * single-width slice overlap between successive partial sums).
3624 */
3625static PyLongObject *
3626k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3627{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003628 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3629 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 Py_ssize_t nbdone; /* # of b digits already multiplied */
3631 PyLongObject *ret;
3632 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 assert(asize > KARATSUBA_CUTOFF);
3635 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 /* Allocate result space, and zero it out. */
3638 ret = _PyLong_New(asize + bsize);
3639 if (ret == NULL)
3640 return NULL;
3641 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 /* Successive slices of b are copied into bslice. */
3644 bslice = _PyLong_New(asize);
3645 if (bslice == NULL)
3646 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 nbdone = 0;
3649 while (bsize > 0) {
3650 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003651 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 /* Multiply the next slice of b by a. */
3654 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3655 nbtouse * sizeof(digit));
3656 Py_SIZE(bslice) = nbtouse;
3657 product = k_mul(a, bslice);
3658 if (product == NULL)
3659 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 /* Add into result. */
3662 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3663 product->ob_digit, Py_SIZE(product));
3664 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 bsize -= nbtouse;
3667 nbdone += nbtouse;
3668 }
Tim Peters60004642002-08-12 22:01:34 +00003669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 Py_DECREF(bslice);
3671 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003672
Mark Dickinson22b20182010-05-10 21:27:53 +00003673 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 Py_DECREF(ret);
3675 Py_XDECREF(bslice);
3676 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003677}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003678
3679static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003680long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003687 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003689 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 z = k_mul(a, b);
3693 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003694 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3695 _PyLong_Negate(&z);
3696 if (z == NULL)
3697 return NULL;
3698 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003700}
3701
Yury Selivanove0b23092016-02-11 10:26:27 -05003702/* Fast modulo division for single-digit longs. */
3703static PyObject *
3704fast_mod(PyLongObject *a, PyLongObject *b)
3705{
3706 sdigit left = a->ob_digit[0];
3707 sdigit right = b->ob_digit[0];
3708 sdigit mod;
3709
3710 assert(Py_ABS(Py_SIZE(a)) == 1);
3711 assert(Py_ABS(Py_SIZE(b)) == 1);
3712
3713 if (Py_SIZE(a) == Py_SIZE(b)) {
3714 /* 'a' and 'b' have the same sign. */
3715 mod = left % right;
3716 }
3717 else {
3718 /* Either 'a' or 'b' is negative. */
3719 mod = right - 1 - (left - 1) % right;
3720 }
3721
Victor Stinnerf963c132016-03-23 18:36:54 +01003722 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003723}
3724
3725/* Fast floor division for single-digit longs. */
3726static PyObject *
3727fast_floor_div(PyLongObject *a, PyLongObject *b)
3728{
3729 sdigit left = a->ob_digit[0];
3730 sdigit right = b->ob_digit[0];
3731 sdigit div;
3732
3733 assert(Py_ABS(Py_SIZE(a)) == 1);
3734 assert(Py_ABS(Py_SIZE(b)) == 1);
3735
3736 if (Py_SIZE(a) == Py_SIZE(b)) {
3737 /* 'a' and 'b' have the same sign. */
3738 div = left / right;
3739 }
3740 else {
3741 /* Either 'a' or 'b' is negative. */
3742 div = -1 - (left - 1) / right;
3743 }
3744
3745 return PyLong_FromLong(div);
3746}
3747
Guido van Rossume32e0141992-01-19 16:31:05 +00003748/* The / and % operators are now defined in terms of divmod().
3749 The expression a mod b has the value a - b*floor(a/b).
3750 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003751 |a| by |b|, with the sign of a. This is also expressed
3752 as a - b*trunc(a/b), if trunc truncates towards zero.
3753 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 a b a rem b a mod b
3755 13 10 3 3
3756 -13 10 -3 7
3757 13 -10 3 -7
3758 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003759 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003760 have different signs. We then subtract one from the 'div'
3761 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003762
Tim Peters47e52ee2004-08-30 02:44:38 +00003763/* Compute
3764 * *pdiv, *pmod = divmod(v, w)
3765 * NULL can be passed for pdiv or pmod, in which case that part of
3766 * the result is simply thrown away. The caller owns a reference to
3767 * each of these it requests (does not pass NULL for).
3768 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003769static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003770l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003774
Yury Selivanove0b23092016-02-11 10:26:27 -05003775 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3776 /* Fast path for single-digit longs */
3777 div = NULL;
3778 if (pdiv != NULL) {
3779 div = (PyLongObject *)fast_floor_div(v, w);
3780 if (div == NULL) {
3781 return -1;
3782 }
3783 }
3784 if (pmod != NULL) {
3785 mod = (PyLongObject *)fast_mod(v, w);
3786 if (mod == NULL) {
3787 Py_XDECREF(div);
3788 return -1;
3789 }
3790 *pmod = mod;
3791 }
3792 if (pdiv != NULL) {
3793 /* We only want to set `*pdiv` when `*pmod` is
3794 set successfully. */
3795 *pdiv = div;
3796 }
3797 return 0;
3798 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 if (long_divrem(v, w, &div, &mod) < 0)
3800 return -1;
3801 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3802 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3803 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 temp = (PyLongObject *) long_add(mod, w);
3805 Py_DECREF(mod);
3806 mod = temp;
3807 if (mod == NULL) {
3808 Py_DECREF(div);
3809 return -1;
3810 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003811 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3812 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 Py_DECREF(mod);
3814 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 return -1;
3816 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 Py_DECREF(div);
3818 div = temp;
3819 }
3820 if (pdiv != NULL)
3821 *pdiv = div;
3822 else
3823 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 if (pmod != NULL)
3826 *pmod = mod;
3827 else
3828 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003831}
3832
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003833static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003834long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003839
3840 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3841 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3842 }
3843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3845 div = NULL;
3846 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003847}
3848
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003849/* PyLong/PyLong -> float, with correctly rounded result. */
3850
3851#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3852#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3853
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003854static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003855long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 PyLongObject *a, *b, *x;
3858 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3859 digit mask, low;
3860 int inexact, negate, a_is_small, b_is_small;
3861 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 CHECK_BINOP(v, w);
3864 a = (PyLongObject *)v;
3865 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 /*
3868 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3871 1. choose a suitable integer 'shift'
3872 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3873 3. adjust x for correct rounding
3874 4. convert x to a double dx with the same value
3875 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3880 returns either 0.0 or -0.0, depending on the sign of b. For a and
3881 b both nonzero, ignore signs of a and b, and add the sign back in
3882 at the end. Now write a_bits and b_bits for the bit lengths of a
3883 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3884 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3889 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3890 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3891 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 1. The integer 'shift' is chosen so that x has the right number of
3896 bits for a double, plus two or three extra bits that will be used
3897 in the rounding decisions. Writing a_bits and b_bits for the
3898 number of significant bits in a and b respectively, a
3899 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 This is fine in the usual case, but if a/b is smaller than the
3904 smallest normal float then it can lead to double rounding on an
3905 IEEE 754 platform, giving incorrectly rounded results. So we
3906 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 2. The quantity x is computed by first shifting a (left -shift bits
3911 if shift <= 0, right shift bits if shift > 0) and then dividing by
3912 b. For both the shift and the division, we keep track of whether
3913 the result is inexact, in a flag 'inexact'; this information is
3914 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 With the choice of shift above, together with our assumption that
3917 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3918 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3921 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 For float representability, we need x/2**extra_bits <
3926 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3927 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 To round, we just modify the bottom digit of x in-place; this can
3932 end up giving a digit with value > PyLONG_MASK, but that's not a
3933 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 With the original choices for shift above, extra_bits will always
3936 be 2 or 3. Then rounding under the round-half-to-even rule, we
3937 round up iff the most significant of the extra bits is 1, and
3938 either: (a) the computation of x in step 2 had an inexact result,
3939 or (b) at least one other of the extra bits is 1, or (c) the least
3940 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 4. Conversion to a double is straightforward; all floating-point
3943 operations involved in the conversion are exact, so there's no
3944 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3947 The result will always be exactly representable as a double, except
3948 in the case that it overflows. To avoid dependence on the exact
3949 behaviour of ldexp on overflow, we check for overflow before
3950 applying ldexp. The result of ldexp is adjusted for sign before
3951 returning.
3952 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003955 a_size = Py_ABS(Py_SIZE(a));
3956 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3958 if (b_size == 0) {
3959 PyErr_SetString(PyExc_ZeroDivisionError,
3960 "division by zero");
3961 goto error;
3962 }
3963 if (a_size == 0)
3964 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 /* Fast path for a and b small (exactly representable in a double).
3967 Relies on floating-point division being correctly rounded; results
3968 may be subject to double rounding on x86 machines that operate with
3969 the x87 FPU set to 64-bit precision. */
3970 a_is_small = a_size <= MANT_DIG_DIGITS ||
3971 (a_size == MANT_DIG_DIGITS+1 &&
3972 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3973 b_is_small = b_size <= MANT_DIG_DIGITS ||
3974 (b_size == MANT_DIG_DIGITS+1 &&
3975 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3976 if (a_is_small && b_is_small) {
3977 double da, db;
3978 da = a->ob_digit[--a_size];
3979 while (a_size > 0)
3980 da = da * PyLong_BASE + a->ob_digit[--a_size];
3981 db = b->ob_digit[--b_size];
3982 while (b_size > 0)
3983 db = db * PyLong_BASE + b->ob_digit[--b_size];
3984 result = da / db;
3985 goto success;
3986 }
Tim Peterse2a60002001-09-04 06:17:36 +00003987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 /* Catch obvious cases of underflow and overflow */
3989 diff = a_size - b_size;
3990 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3991 /* Extreme overflow */
3992 goto overflow;
3993 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3994 /* Extreme underflow */
3995 goto underflow_or_zero;
3996 /* Next line is now safe from overflowing a Py_ssize_t */
3997 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3998 bits_in_digit(b->ob_digit[b_size - 1]);
3999 /* Now diff = a_bits - b_bits. */
4000 if (diff > DBL_MAX_EXP)
4001 goto overflow;
4002 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
4003 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00004004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004006 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 /* x = abs(a * 2**-shift) */
4011 if (shift <= 0) {
4012 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
4013 digit rem;
4014 /* x = a << -shift */
4015 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
4016 /* In practice, it's probably impossible to end up
4017 here. Both a and b would have to be enormous,
4018 using close to SIZE_T_MAX bytes of memory each. */
4019 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004020 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 goto error;
4022 }
4023 x = _PyLong_New(a_size + shift_digits + 1);
4024 if (x == NULL)
4025 goto error;
4026 for (i = 0; i < shift_digits; i++)
4027 x->ob_digit[i] = 0;
4028 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
4029 a_size, -shift % PyLong_SHIFT);
4030 x->ob_digit[a_size + shift_digits] = rem;
4031 }
4032 else {
4033 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
4034 digit rem;
4035 /* x = a >> shift */
4036 assert(a_size >= shift_digits);
4037 x = _PyLong_New(a_size - shift_digits);
4038 if (x == NULL)
4039 goto error;
4040 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4041 a_size - shift_digits, shift % PyLong_SHIFT);
4042 /* set inexact if any of the bits shifted out is nonzero */
4043 if (rem)
4044 inexact = 1;
4045 while (!inexact && shift_digits > 0)
4046 if (a->ob_digit[--shift_digits])
4047 inexact = 1;
4048 }
4049 long_normalize(x);
4050 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4053 reference to x, so it's safe to modify it in-place. */
4054 if (b_size == 1) {
4055 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4056 b->ob_digit[0]);
4057 long_normalize(x);
4058 if (rem)
4059 inexact = 1;
4060 }
4061 else {
4062 PyLongObject *div, *rem;
4063 div = x_divrem(x, b, &rem);
4064 Py_DECREF(x);
4065 x = div;
4066 if (x == NULL)
4067 goto error;
4068 if (Py_SIZE(rem))
4069 inexact = 1;
4070 Py_DECREF(rem);
4071 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004072 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 assert(x_size > 0); /* result of division is never zero */
4074 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004077 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 /* Round by directly modifying the low digit of x. */
4081 mask = (digit)1 << (extra_bits - 1);
4082 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004083 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004085 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 /* Convert x to a double dx; the conversion is exact. */
4088 dx = x->ob_digit[--x_size];
4089 while (x_size > 0)
4090 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4091 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 /* Check whether ldexp result will overflow a double. */
4094 if (shift + x_bits >= DBL_MAX_EXP &&
4095 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4096 goto overflow;
4097 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004098
4099 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004101
4102 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004104
4105 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 PyErr_SetString(PyExc_OverflowError,
4107 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004108 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004110}
4111
4112static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004113long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 CHECK_BINOP(a, b);
4118
Yury Selivanove0b23092016-02-11 10:26:27 -05004119 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4120 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4121 }
4122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4124 mod = NULL;
4125 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004126}
4127
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004128static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004129long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 PyLongObject *div, *mod;
4132 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4137 return NULL;
4138 }
4139 z = PyTuple_New(2);
4140 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004141 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4142 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 }
4144 else {
4145 Py_DECREF(div);
4146 Py_DECREF(mod);
4147 }
4148 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004149}
4150
Mark Dickinsonc5299672019-06-02 10:24:06 +01004151
4152/* Compute an inverse to a modulo n, or raise ValueError if a is not
4153 invertible modulo n. Assumes n is positive. The inverse returned
4154 is whatever falls out of the extended Euclidean algorithm: it may
4155 be either positive or negative, but will be smaller than n in
4156 absolute value.
4157
4158 Pure Python equivalent for long_invmod:
4159
4160 def invmod(a, n):
4161 b, c = 1, 0
4162 while n:
4163 q, r = divmod(a, n)
4164 a, b, c, n = n, c, b - q*c, r
4165
4166 # at this point a is the gcd of the original inputs
4167 if a == 1:
4168 return b
4169 raise ValueError("Not invertible")
4170*/
4171
4172static PyLongObject *
4173long_invmod(PyLongObject *a, PyLongObject *n)
4174{
4175 PyLongObject *b, *c;
4176
4177 /* Should only ever be called for positive n */
4178 assert(Py_SIZE(n) > 0);
4179
4180 b = (PyLongObject *)PyLong_FromLong(1L);
4181 if (b == NULL) {
4182 return NULL;
4183 }
4184 c = (PyLongObject *)PyLong_FromLong(0L);
4185 if (c == NULL) {
4186 Py_DECREF(b);
4187 return NULL;
4188 }
4189 Py_INCREF(a);
4190 Py_INCREF(n);
4191
4192 /* references now owned: a, b, c, n */
4193 while (Py_SIZE(n) != 0) {
4194 PyLongObject *q, *r, *s, *t;
4195
4196 if (l_divmod(a, n, &q, &r) == -1) {
4197 goto Error;
4198 }
4199 Py_DECREF(a);
4200 a = n;
4201 n = r;
4202 t = (PyLongObject *)long_mul(q, c);
4203 Py_DECREF(q);
4204 if (t == NULL) {
4205 goto Error;
4206 }
4207 s = (PyLongObject *)long_sub(b, t);
4208 Py_DECREF(t);
4209 if (s == NULL) {
4210 goto Error;
4211 }
4212 Py_DECREF(b);
4213 b = c;
4214 c = s;
4215 }
4216 /* references now owned: a, b, c, n */
4217
4218 Py_DECREF(c);
4219 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004220 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004221 /* a != 1; we don't have an inverse. */
4222 Py_DECREF(a);
4223 Py_DECREF(b);
4224 PyErr_SetString(PyExc_ValueError,
4225 "base is not invertible for the given modulus");
4226 return NULL;
4227 }
4228 else {
4229 /* a == 1; b gives an inverse modulo n */
4230 Py_DECREF(a);
4231 return b;
4232 }
4233
4234 Error:
4235 Py_DECREF(a);
4236 Py_DECREF(b);
4237 Py_DECREF(c);
4238 Py_DECREF(n);
4239 return NULL;
4240}
4241
4242
Tim Peters47e52ee2004-08-30 02:44:38 +00004243/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004244static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004245long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4248 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 PyLongObject *z = NULL; /* accumulated result */
4251 Py_ssize_t i, j, k; /* counters */
4252 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 /* 5-ary values. If the exponent is large enough, table is
4255 * precomputed so that table[i] == a**i % c for i in range(32).
4256 */
4257 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4258 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 /* a, b, c = v, w, x */
4261 CHECK_BINOP(v, w);
4262 a = (PyLongObject*)v; Py_INCREF(a);
4263 b = (PyLongObject*)w; Py_INCREF(b);
4264 if (PyLong_Check(x)) {
4265 c = (PyLongObject *)x;
4266 Py_INCREF(x);
4267 }
4268 else if (x == Py_None)
4269 c = NULL;
4270 else {
4271 Py_DECREF(a);
4272 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004273 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 }
Tim Peters4c483c42001-09-05 06:24:58 +00004275
Mark Dickinsonc5299672019-06-02 10:24:06 +01004276 if (Py_SIZE(b) < 0 && c == NULL) {
4277 /* if exponent is negative and there's no modulus:
4278 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004279 that this calls float_pow() which converts its
4280 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004281 Py_DECREF(a);
4282 Py_DECREF(b);
4283 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 if (c) {
4287 /* if modulus == 0:
4288 raise ValueError() */
4289 if (Py_SIZE(c) == 0) {
4290 PyErr_SetString(PyExc_ValueError,
4291 "pow() 3rd argument cannot be 0");
4292 goto Error;
4293 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 /* if modulus < 0:
4296 negativeOutput = True
4297 modulus = -modulus */
4298 if (Py_SIZE(c) < 0) {
4299 negativeOutput = 1;
4300 temp = (PyLongObject *)_PyLong_Copy(c);
4301 if (temp == NULL)
4302 goto Error;
4303 Py_DECREF(c);
4304 c = temp;
4305 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004306 _PyLong_Negate(&c);
4307 if (c == NULL)
4308 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 /* if modulus == 1:
4312 return 0 */
4313 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4314 z = (PyLongObject *)PyLong_FromLong(0L);
4315 goto Done;
4316 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004317
Mark Dickinsonc5299672019-06-02 10:24:06 +01004318 /* if exponent is negative, negate the exponent and
4319 replace the base with a modular inverse */
4320 if (Py_SIZE(b) < 0) {
4321 temp = (PyLongObject *)_PyLong_Copy(b);
4322 if (temp == NULL)
4323 goto Error;
4324 Py_DECREF(b);
4325 b = temp;
4326 temp = NULL;
4327 _PyLong_Negate(&b);
4328 if (b == NULL)
4329 goto Error;
4330
4331 temp = long_invmod(a, c);
4332 if (temp == NULL)
4333 goto Error;
4334 Py_DECREF(a);
4335 a = temp;
4336 }
4337
Tim Peters81a93152013-10-05 16:53:52 -05004338 /* Reduce base by modulus in some cases:
4339 1. If base < 0. Forcing the base non-negative makes things easier.
4340 2. If base is obviously larger than the modulus. The "small
4341 exponent" case later can multiply directly by base repeatedly,
4342 while the "large exponent" case multiplies directly by base 31
4343 times. It can be unboundedly faster to multiply by
4344 base % modulus instead.
4345 We could _always_ do this reduction, but l_divmod() isn't cheap,
4346 so we only do it when it buys something. */
4347 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 if (l_divmod(a, c, NULL, &temp) < 0)
4349 goto Error;
4350 Py_DECREF(a);
4351 a = temp;
4352 temp = NULL;
4353 }
4354 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 /* At this point a, b, and c are guaranteed non-negative UNLESS
4357 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 z = (PyLongObject *)PyLong_FromLong(1L);
4360 if (z == NULL)
4361 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 /* Perform a modular reduction, X = X % c, but leave X alone if c
4364 * is NULL.
4365 */
4366#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004367 do { \
4368 if (c != NULL) { \
4369 if (l_divmod(X, c, NULL, &temp) < 0) \
4370 goto Error; \
4371 Py_XDECREF(X); \
4372 X = temp; \
4373 temp = NULL; \
4374 } \
4375 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 /* Multiply two values, then reduce the result:
4378 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004379#define MULT(X, Y, result) \
4380 do { \
4381 temp = (PyLongObject *)long_mul(X, Y); \
4382 if (temp == NULL) \
4383 goto Error; \
4384 Py_XDECREF(result); \
4385 result = temp; \
4386 temp = NULL; \
4387 REDUCE(result); \
4388 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4391 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4392 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4393 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4394 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004397 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004399 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 }
4401 }
4402 }
4403 else {
4404 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4405 Py_INCREF(z); /* still holds 1L */
4406 table[0] = z;
4407 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004408 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4411 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4414 const int index = (bi >> j) & 0x1f;
4415 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004416 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004418 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 }
4420 }
4421 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 if (negativeOutput && (Py_SIZE(z) != 0)) {
4424 temp = (PyLongObject *)long_sub(z, c);
4425 if (temp == NULL)
4426 goto Error;
4427 Py_DECREF(z);
4428 z = temp;
4429 temp = NULL;
4430 }
4431 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004432
Mark Dickinson22b20182010-05-10 21:27:53 +00004433 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004434 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004436 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4438 for (i = 0; i < 32; ++i)
4439 Py_XDECREF(table[i]);
4440 }
4441 Py_DECREF(a);
4442 Py_DECREF(b);
4443 Py_XDECREF(c);
4444 Py_XDECREF(temp);
4445 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004446}
4447
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004448static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004449long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 /* Implement ~x as -(x+1) */
4452 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004453 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004455 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 if (x == NULL)
4457 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004458 _PyLong_Negate(&x);
4459 /* No need for maybe_small_long here, since any small
4460 longs will have been caught in the Py_SIZE <= 1 fast path. */
4461 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004462}
4463
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004464static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004465long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004468 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 return PyLong_FromLong(-MEDIUM_VALUE(v));
4470 z = (PyLongObject *)_PyLong_Copy(v);
4471 if (z != NULL)
4472 Py_SIZE(z) = -(Py_SIZE(v));
4473 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004474}
4475
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004476static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004477long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 if (Py_SIZE(v) < 0)
4480 return long_neg(v);
4481 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004482 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004483}
4484
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004485static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004486long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004488 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004489}
4490
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004491/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4492static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004493divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004494{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004495 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004496 assert(Py_SIZE(shiftby) >= 0);
4497 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4498 if (lshiftby >= 0) {
4499 *wordshift = lshiftby / PyLong_SHIFT;
4500 *remshift = lshiftby % PyLong_SHIFT;
4501 return 0;
4502 }
4503 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4504 be that PyLong_AsSsize_t raised an OverflowError. */
4505 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4506 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004507 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004508 if (wordshift_obj == NULL) {
4509 return -1;
4510 }
4511 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4512 Py_DECREF(wordshift_obj);
4513 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4514 return 0;
4515 }
4516 PyErr_Clear();
4517 /* Clip the value. With such large wordshift the right shift
4518 returns 0 and the left shift raises an error in _PyLong_New(). */
4519 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4520 *remshift = 0;
4521 return 0;
4522}
4523
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004524static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004525long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004527 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004528 Py_ssize_t newsize, hishift, i, j;
4529 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 if (Py_SIZE(a) < 0) {
4532 /* Right shifting negative numbers is harder */
4533 PyLongObject *a1, *a2;
4534 a1 = (PyLongObject *) long_invert(a);
4535 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004536 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004537 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 Py_DECREF(a1);
4539 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004540 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 z = (PyLongObject *) long_invert(a2);
4542 Py_DECREF(a2);
4543 }
4544 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004545 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 if (newsize <= 0)
4547 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004548 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 lomask = ((digit)1 << hishift) - 1;
4550 himask = PyLong_MASK ^ lomask;
4551 z = _PyLong_New(newsize);
4552 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004553 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004555 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004557 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004559 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004561 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004562}
4563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004564static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004565long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004566{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004567 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004568 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004571
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004572 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004574 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004576 if (Py_SIZE(a) == 0) {
4577 return PyLong_FromLong(0);
4578 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004579 if (divmod_shift(b, &wordshift, &remshift) < 0)
4580 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004581 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4582}
4583
4584/* Return a >> shiftby. */
4585PyObject *
4586_PyLong_Rshift(PyObject *a, size_t shiftby)
4587{
4588 Py_ssize_t wordshift;
4589 digit remshift;
4590
4591 assert(PyLong_Check(a));
4592 if (Py_SIZE(a) == 0) {
4593 return PyLong_FromLong(0);
4594 }
4595 wordshift = shiftby / PyLong_SHIFT;
4596 remshift = shiftby % PyLong_SHIFT;
4597 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4598}
4599
4600static PyObject *
4601long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4602{
4603 /* This version due to Tim Peters */
4604 PyLongObject *z = NULL;
4605 Py_ssize_t oldsize, newsize, i, j;
4606 twodigits accum;
4607
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004608 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004609 newsize = oldsize + wordshift;
4610 if (remshift)
4611 ++newsize;
4612 z = _PyLong_New(newsize);
4613 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004614 return NULL;
4615 if (Py_SIZE(a) < 0) {
4616 assert(Py_REFCNT(z) == 1);
4617 Py_SIZE(z) = -Py_SIZE(z);
4618 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 for (i = 0; i < wordshift; i++)
4620 z->ob_digit[i] = 0;
4621 accum = 0;
4622 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4623 accum |= (twodigits)a->ob_digit[j] << remshift;
4624 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4625 accum >>= PyLong_SHIFT;
4626 }
4627 if (remshift)
4628 z->ob_digit[newsize-1] = (digit)accum;
4629 else
4630 assert(!accum);
4631 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004633}
4634
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004635static PyObject *
4636long_lshift(PyObject *a, PyObject *b)
4637{
4638 Py_ssize_t wordshift;
4639 digit remshift;
4640
4641 CHECK_BINOP(a, b);
4642
4643 if (Py_SIZE(b) < 0) {
4644 PyErr_SetString(PyExc_ValueError, "negative shift count");
4645 return NULL;
4646 }
4647 if (Py_SIZE(a) == 0) {
4648 return PyLong_FromLong(0);
4649 }
4650 if (divmod_shift(b, &wordshift, &remshift) < 0)
4651 return NULL;
4652 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4653}
4654
4655/* Return a << shiftby. */
4656PyObject *
4657_PyLong_Lshift(PyObject *a, size_t shiftby)
4658{
4659 Py_ssize_t wordshift;
4660 digit remshift;
4661
4662 assert(PyLong_Check(a));
4663 if (Py_SIZE(a) == 0) {
4664 return PyLong_FromLong(0);
4665 }
4666 wordshift = shiftby / PyLong_SHIFT;
4667 remshift = shiftby % PyLong_SHIFT;
4668 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4669}
4670
Mark Dickinson27a87a22009-10-25 20:43:34 +00004671/* Compute two's complement of digit vector a[0:m], writing result to
4672 z[0:m]. The digit vector a need not be normalized, but should not
4673 be entirely zero. a and z may point to the same digit vector. */
4674
4675static void
4676v_complement(digit *z, digit *a, Py_ssize_t m)
4677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 Py_ssize_t i;
4679 digit carry = 1;
4680 for (i = 0; i < m; ++i) {
4681 carry += a[i] ^ PyLong_MASK;
4682 z[i] = carry & PyLong_MASK;
4683 carry >>= PyLong_SHIFT;
4684 }
4685 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004686}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004687
4688/* Bitwise and/xor/or operations */
4689
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004690static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004691long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004692 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004693 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 int nega, negb, negz;
4696 Py_ssize_t size_a, size_b, size_z, i;
4697 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 /* Bitwise operations for negative numbers operate as though
4700 on a two's complement representation. So convert arguments
4701 from sign-magnitude to two's complement, and convert the
4702 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004705 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 nega = Py_SIZE(a) < 0;
4707 if (nega) {
4708 z = _PyLong_New(size_a);
4709 if (z == NULL)
4710 return NULL;
4711 v_complement(z->ob_digit, a->ob_digit, size_a);
4712 a = z;
4713 }
4714 else
4715 /* Keep reference count consistent. */
4716 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004719 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 negb = Py_SIZE(b) < 0;
4721 if (negb) {
4722 z = _PyLong_New(size_b);
4723 if (z == NULL) {
4724 Py_DECREF(a);
4725 return NULL;
4726 }
4727 v_complement(z->ob_digit, b->ob_digit, size_b);
4728 b = z;
4729 }
4730 else
4731 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 /* Swap a and b if necessary to ensure size_a >= size_b. */
4734 if (size_a < size_b) {
4735 z = a; a = b; b = z;
4736 size_z = size_a; size_a = size_b; size_b = size_z;
4737 negz = nega; nega = negb; negb = negz;
4738 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 /* JRH: The original logic here was to allocate the result value (z)
4741 as the longer of the two operands. However, there are some cases
4742 where the result is guaranteed to be shorter than that: AND of two
4743 positives, OR of two negatives: use the shorter number. AND with
4744 mixed signs: use the positive number. OR with mixed signs: use the
4745 negative number.
4746 */
4747 switch (op) {
4748 case '^':
4749 negz = nega ^ negb;
4750 size_z = size_a;
4751 break;
4752 case '&':
4753 negz = nega & negb;
4754 size_z = negb ? size_a : size_b;
4755 break;
4756 case '|':
4757 negz = nega | negb;
4758 size_z = negb ? size_b : size_a;
4759 break;
4760 default:
stratakisa10d4262019-03-18 18:59:20 +01004761 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 /* We allow an extra digit if z is negative, to make sure that
4765 the final two's complement of z doesn't overflow. */
4766 z = _PyLong_New(size_z + negz);
4767 if (z == NULL) {
4768 Py_DECREF(a);
4769 Py_DECREF(b);
4770 return NULL;
4771 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004773 /* Compute digits for overlap of a and b. */
4774 switch(op) {
4775 case '&':
4776 for (i = 0; i < size_b; ++i)
4777 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4778 break;
4779 case '|':
4780 for (i = 0; i < size_b; ++i)
4781 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4782 break;
4783 case '^':
4784 for (i = 0; i < size_b; ++i)
4785 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4786 break;
4787 default:
stratakisa10d4262019-03-18 18:59:20 +01004788 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 /* Copy any remaining digits of a, inverting if necessary. */
4792 if (op == '^' && negb)
4793 for (; i < size_z; ++i)
4794 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4795 else if (i < size_z)
4796 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4797 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 /* Complement result if negative. */
4800 if (negz) {
4801 Py_SIZE(z) = -(Py_SIZE(z));
4802 z->ob_digit[size_z] = PyLong_MASK;
4803 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4804 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 Py_DECREF(a);
4807 Py_DECREF(b);
4808 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004809}
4810
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004811static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004812long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004814 PyObject *c;
4815 CHECK_BINOP(a, b);
4816 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4817 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004818}
4819
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004820static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004821long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 PyObject *c;
4824 CHECK_BINOP(a, b);
4825 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4826 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004827}
4828
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004829static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004830long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 PyObject *c;
4833 CHECK_BINOP(a, b);
4834 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4835 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004836}
4837
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004838static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004839long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004841 if (PyLong_CheckExact(v))
4842 Py_INCREF(v);
4843 else
4844 v = _PyLong_Copy((PyLongObject *)v);
4845 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004846}
4847
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004848PyObject *
4849_PyLong_GCD(PyObject *aarg, PyObject *barg)
4850{
4851 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4852 stwodigits x, y, q, s, t, c_carry, d_carry;
4853 stwodigits A, B, C, D, T;
4854 int nbits, k;
4855 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4856 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4857
4858 a = (PyLongObject *)aarg;
4859 b = (PyLongObject *)barg;
4860 size_a = Py_SIZE(a);
4861 size_b = Py_SIZE(b);
4862 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4863 Py_INCREF(a);
4864 Py_INCREF(b);
4865 goto simple;
4866 }
4867
4868 /* Initial reduction: make sure that 0 <= b <= a. */
4869 a = (PyLongObject *)long_abs(a);
4870 if (a == NULL)
4871 return NULL;
4872 b = (PyLongObject *)long_abs(b);
4873 if (b == NULL) {
4874 Py_DECREF(a);
4875 return NULL;
4876 }
4877 if (long_compare(a, b) < 0) {
4878 r = a;
4879 a = b;
4880 b = r;
4881 }
4882 /* We now own references to a and b */
4883
4884 alloc_a = Py_SIZE(a);
4885 alloc_b = Py_SIZE(b);
4886 /* reduce until a fits into 2 digits */
4887 while ((size_a = Py_SIZE(a)) > 2) {
4888 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4889 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4890 corresponding bits of b into y */
4891 size_b = Py_SIZE(b);
4892 assert(size_b <= size_a);
4893 if (size_b == 0) {
4894 if (size_a < alloc_a) {
4895 r = (PyLongObject *)_PyLong_Copy(a);
4896 Py_DECREF(a);
4897 }
4898 else
4899 r = a;
4900 Py_DECREF(b);
4901 Py_XDECREF(c);
4902 Py_XDECREF(d);
4903 return (PyObject *)r;
4904 }
4905 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4906 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4907 (a->ob_digit[size_a-3] >> nbits));
4908
4909 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4910 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4911 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4912
4913 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4914 larger than PyLong_MASK during the algorithm. */
4915 A = 1; B = 0; C = 0; D = 1;
4916 for (k=0;; k++) {
4917 if (y-C == 0)
4918 break;
4919 q = (x+(A-1))/(y-C);
4920 s = B+q*D;
4921 t = x-q*y;
4922 if (s > t)
4923 break;
4924 x = y; y = t;
4925 t = A+q*C; A = D; B = C; C = s; D = t;
4926 }
4927
4928 if (k == 0) {
4929 /* no progress; do a Euclidean step */
4930 if (l_divmod(a, b, NULL, &r) < 0)
4931 goto error;
4932 Py_DECREF(a);
4933 a = b;
4934 b = r;
4935 alloc_a = alloc_b;
4936 alloc_b = Py_SIZE(b);
4937 continue;
4938 }
4939
4940 /*
4941 a, b = A*b-B*a, D*a-C*b if k is odd
4942 a, b = A*a-B*b, D*b-C*a if k is even
4943 */
4944 if (k&1) {
4945 T = -A; A = -B; B = T;
4946 T = -C; C = -D; D = T;
4947 }
4948 if (c != NULL)
4949 Py_SIZE(c) = size_a;
4950 else if (Py_REFCNT(a) == 1) {
4951 Py_INCREF(a);
4952 c = a;
4953 }
4954 else {
4955 alloc_a = size_a;
4956 c = _PyLong_New(size_a);
4957 if (c == NULL)
4958 goto error;
4959 }
4960
4961 if (d != NULL)
4962 Py_SIZE(d) = size_a;
4963 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4964 Py_INCREF(b);
4965 d = b;
4966 Py_SIZE(d) = size_a;
4967 }
4968 else {
4969 alloc_b = size_a;
4970 d = _PyLong_New(size_a);
4971 if (d == NULL)
4972 goto error;
4973 }
4974 a_end = a->ob_digit + size_a;
4975 b_end = b->ob_digit + size_b;
4976
4977 /* compute new a and new b in parallel */
4978 a_digit = a->ob_digit;
4979 b_digit = b->ob_digit;
4980 c_digit = c->ob_digit;
4981 d_digit = d->ob_digit;
4982 c_carry = 0;
4983 d_carry = 0;
4984 while (b_digit < b_end) {
4985 c_carry += (A * *a_digit) - (B * *b_digit);
4986 d_carry += (D * *b_digit++) - (C * *a_digit++);
4987 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4988 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4989 c_carry >>= PyLong_SHIFT;
4990 d_carry >>= PyLong_SHIFT;
4991 }
4992 while (a_digit < a_end) {
4993 c_carry += A * *a_digit;
4994 d_carry -= C * *a_digit++;
4995 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4996 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4997 c_carry >>= PyLong_SHIFT;
4998 d_carry >>= PyLong_SHIFT;
4999 }
5000 assert(c_carry == 0);
5001 assert(d_carry == 0);
5002
5003 Py_INCREF(c);
5004 Py_INCREF(d);
5005 Py_DECREF(a);
5006 Py_DECREF(b);
5007 a = long_normalize(c);
5008 b = long_normalize(d);
5009 }
5010 Py_XDECREF(c);
5011 Py_XDECREF(d);
5012
5013simple:
5014 assert(Py_REFCNT(a) > 0);
5015 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02005016/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
5017 undefined behaviour when LONG_MAX type is smaller than 60 bits */
5018#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005019 /* a fits into a long, so b must too */
5020 x = PyLong_AsLong((PyObject *)a);
5021 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07005022#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005023 x = PyLong_AsLongLong((PyObject *)a);
5024 y = PyLong_AsLongLong((PyObject *)b);
5025#else
5026# error "_PyLong_GCD"
5027#endif
5028 x = Py_ABS(x);
5029 y = Py_ABS(y);
5030 Py_DECREF(a);
5031 Py_DECREF(b);
5032
5033 /* usual Euclidean algorithm for longs */
5034 while (y != 0) {
5035 t = y;
5036 y = x % y;
5037 x = t;
5038 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005039#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005040 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07005041#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005042 return PyLong_FromLongLong(x);
5043#else
5044# error "_PyLong_GCD"
5045#endif
5046
5047error:
5048 Py_DECREF(a);
5049 Py_DECREF(b);
5050 Py_XDECREF(c);
5051 Py_XDECREF(d);
5052 return NULL;
5053}
5054
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005055static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005056long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 double result;
5059 result = PyLong_AsDouble(v);
5060 if (result == -1.0 && PyErr_Occurred())
5061 return NULL;
5062 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005063}
5064
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005065static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005066long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5067
5068/*[clinic input]
5069@classmethod
5070int.__new__ as long_new
5071 x: object(c_default="NULL") = 0
5072 /
5073 base as obase: object(c_default="NULL") = 10
5074[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005075
Tim Peters6d6c1a32001-08-02 04:15:00 +00005076static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005077long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5078/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005079{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005080 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005083 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005084 if (x == NULL) {
5085 if (obase != NULL) {
5086 PyErr_SetString(PyExc_TypeError,
5087 "int() missing string argument");
5088 return NULL;
5089 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005090 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005091 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005092 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005094
Gregory P. Smitha689e522012-12-25 22:38:32 -08005095 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005096 if (base == -1 && PyErr_Occurred())
5097 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005098 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005099 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305100 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005101 return NULL;
5102 }
5103
5104 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005105 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005107 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 if (PyByteArray_Check(x))
5109 string = PyByteArray_AS_STRING(x);
5110 else
5111 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005112 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 }
5114 else {
5115 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005116 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 return NULL;
5118 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005119}
5120
Serhiy Storchaka95949422013-08-27 19:40:23 +03005121/* Wimpy, slow approach to tp_new calls for subtypes of int:
5122 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005123 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005124 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005125*/
5126static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005127long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 PyLongObject *tmp, *newobj;
5130 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005132 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005133 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 if (tmp == NULL)
5135 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005136 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 n = Py_SIZE(tmp);
5138 if (n < 0)
5139 n = -n;
5140 newobj = (PyLongObject *)type->tp_alloc(type, n);
5141 if (newobj == NULL) {
5142 Py_DECREF(tmp);
5143 return NULL;
5144 }
5145 assert(PyLong_Check(newobj));
5146 Py_SIZE(newobj) = Py_SIZE(tmp);
5147 for (i = 0; i < n; i++)
5148 newobj->ob_digit[i] = tmp->ob_digit[i];
5149 Py_DECREF(tmp);
5150 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005151}
5152
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005153/*[clinic input]
5154int.__getnewargs__
5155[clinic start generated code]*/
5156
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005157static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005158int___getnewargs___impl(PyObject *self)
5159/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005160{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005161 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005162}
5163
Guido van Rossumb43daf72007-08-01 18:08:08 +00005164static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005165long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005168}
5169
5170static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005171long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005174}
5175
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005176/*[clinic input]
5177int.__format__
5178
5179 format_spec: unicode
5180 /
5181[clinic start generated code]*/
5182
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005183static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005184int___format___impl(PyObject *self, PyObject *format_spec)
5185/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005186{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005187 _PyUnicodeWriter writer;
5188 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005189
Victor Stinner8f674cc2013-04-17 23:02:17 +02005190 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005191 ret = _PyLong_FormatAdvancedWriter(
5192 &writer,
5193 self,
5194 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5195 if (ret == -1) {
5196 _PyUnicodeWriter_Dealloc(&writer);
5197 return NULL;
5198 }
5199 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005200}
5201
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005202/* Return a pair (q, r) such that a = b * q + r, and
5203 abs(r) <= abs(b)/2, with equality possible only if q is even.
5204 In other words, q == a / b, rounded to the nearest integer using
5205 round-half-to-even. */
5206
5207PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005208_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005209{
5210 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005211 PyObject *twice_rem, *result, *temp;
HongWeipeng42acb7b2019-09-18 23:10:15 +08005212 int quo_is_odd, quo_is_neg;
5213 Py_ssize_t cmp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005214
5215 /* Equivalent Python code:
5216
5217 def divmod_near(a, b):
5218 q, r = divmod(a, b)
5219 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5220 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5221 # positive, 2 * r < b if b negative.
5222 greater_than_half = 2*r > b if b > 0 else 2*r < b
5223 exactly_half = 2*r == b
5224 if greater_than_half or exactly_half and q % 2 == 1:
5225 q += 1
5226 r -= b
5227 return q, r
5228
5229 */
5230 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5231 PyErr_SetString(PyExc_TypeError,
5232 "non-integer arguments in division");
5233 return NULL;
5234 }
5235
5236 /* Do a and b have different signs? If so, quotient is negative. */
5237 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5238
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005239 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5240 goto error;
5241
5242 /* compare twice the remainder with the divisor, to see
5243 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005244 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005245 if (twice_rem == NULL)
5246 goto error;
5247 if (quo_is_neg) {
5248 temp = long_neg((PyLongObject*)twice_rem);
5249 Py_DECREF(twice_rem);
5250 twice_rem = temp;
5251 if (twice_rem == NULL)
5252 goto error;
5253 }
5254 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5255 Py_DECREF(twice_rem);
5256
5257 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5258 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5259 /* fix up quotient */
5260 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005261 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005262 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005263 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005264 Py_DECREF(quo);
5265 quo = (PyLongObject *)temp;
5266 if (quo == NULL)
5267 goto error;
5268 /* and remainder */
5269 if (quo_is_neg)
5270 temp = long_add(rem, (PyLongObject *)b);
5271 else
5272 temp = long_sub(rem, (PyLongObject *)b);
5273 Py_DECREF(rem);
5274 rem = (PyLongObject *)temp;
5275 if (rem == NULL)
5276 goto error;
5277 }
5278
5279 result = PyTuple_New(2);
5280 if (result == NULL)
5281 goto error;
5282
5283 /* PyTuple_SET_ITEM steals references */
5284 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5285 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005286 return result;
5287
5288 error:
5289 Py_XDECREF(quo);
5290 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005291 return NULL;
5292}
5293
Eric Smith8c663262007-08-25 02:26:07 +00005294static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005295long_round(PyObject *self, PyObject *args)
5296{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005297 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005298
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005299 /* To round an integer m to the nearest 10**n (n positive), we make use of
5300 * the divmod_near operation, defined by:
5301 *
5302 * divmod_near(a, b) = (q, r)
5303 *
5304 * where q is the nearest integer to the quotient a / b (the
5305 * nearest even integer in the case of a tie) and r == a - q * b.
5306 * Hence q * b = a - r is the nearest multiple of b to a,
5307 * preferring even multiples in the case of a tie.
5308 *
5309 * So the nearest multiple of 10**n to m is:
5310 *
5311 * m - divmod_near(m, 10**n)[1].
5312 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5314 return NULL;
5315 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005316 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005317
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005318 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 if (ndigits == NULL)
5320 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005321
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005322 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 if (Py_SIZE(ndigits) >= 0) {
5324 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005325 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005327
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005328 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5329 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005331 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005333 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005334
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005335 result = PyLong_FromLong(10L);
5336 if (result == NULL) {
5337 Py_DECREF(ndigits);
5338 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005340
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005341 temp = long_pow(result, ndigits, Py_None);
5342 Py_DECREF(ndigits);
5343 Py_DECREF(result);
5344 result = temp;
5345 if (result == NULL)
5346 return NULL;
5347
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005348 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005349 Py_DECREF(result);
5350 result = temp;
5351 if (result == NULL)
5352 return NULL;
5353
5354 temp = long_sub((PyLongObject *)self,
5355 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5356 Py_DECREF(result);
5357 result = temp;
5358
5359 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005360}
5361
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005362/*[clinic input]
5363int.__sizeof__ -> Py_ssize_t
5364
5365Returns size in memory, in bytes.
5366[clinic start generated code]*/
5367
5368static Py_ssize_t
5369int___sizeof___impl(PyObject *self)
5370/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005373
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005374 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5375 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005376}
5377
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005378/*[clinic input]
5379int.bit_length
5380
5381Number of bits necessary to represent self in binary.
5382
5383>>> bin(37)
5384'0b100101'
5385>>> (37).bit_length()
53866
5387[clinic start generated code]*/
5388
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005389static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005390int_bit_length_impl(PyObject *self)
5391/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005394 Py_ssize_t ndigits;
5395 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005397
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005398 assert(self != NULL);
5399 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005400
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005401 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 if (ndigits == 0)
5403 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005404
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005405 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005406 msd_bits = bits_in_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005408 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5409 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 /* expression above may overflow; use Python integers instead */
5412 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5413 if (result == NULL)
5414 return NULL;
5415 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5416 if (x == NULL)
5417 goto error;
5418 y = (PyLongObject *)long_mul(result, x);
5419 Py_DECREF(x);
5420 if (y == NULL)
5421 goto error;
5422 Py_DECREF(result);
5423 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5426 if (x == NULL)
5427 goto error;
5428 y = (PyLongObject *)long_add(result, x);
5429 Py_DECREF(x);
5430 if (y == NULL)
5431 goto error;
5432 Py_DECREF(result);
5433 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005436
Mark Dickinson22b20182010-05-10 21:27:53 +00005437 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 Py_DECREF(result);
5439 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005440}
5441
Christian Heimes53876d92008-04-19 00:31:39 +00005442#if 0
5443static PyObject *
5444long_is_finite(PyObject *v)
5445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005447}
5448#endif
5449
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005450/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005451int.as_integer_ratio
5452
5453Return integer ratio.
5454
5455Return a pair of integers, whose ratio is exactly equal to the original int
5456and with a positive denominator.
5457
5458>>> (10).as_integer_ratio()
5459(10, 1)
5460>>> (-10).as_integer_ratio()
5461(-10, 1)
5462>>> (0).as_integer_ratio()
5463(0, 1)
5464[clinic start generated code]*/
5465
5466static PyObject *
5467int_as_integer_ratio_impl(PyObject *self)
5468/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5469{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005470 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005471 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005472 if (numerator == NULL) {
5473 return NULL;
5474 }
5475 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5476 Py_DECREF(numerator);
5477 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005478}
5479
5480/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005481int.to_bytes
5482
5483 length: Py_ssize_t
5484 Length of bytes object to use. An OverflowError is raised if the
5485 integer is not representable with the given number of bytes.
5486 byteorder: unicode
5487 The byte order used to represent the integer. If byteorder is 'big',
5488 the most significant byte is at the beginning of the byte array. If
5489 byteorder is 'little', the most significant byte is at the end of the
5490 byte array. To request the native byte order of the host system, use
5491 `sys.byteorder' as the byte order value.
5492 *
5493 signed as is_signed: bool = False
5494 Determines whether two's complement is used to represent the integer.
5495 If signed is False and a negative integer is given, an OverflowError
5496 is raised.
5497
5498Return an array of bytes representing an integer.
5499[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005500
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005501static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005502int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5503 int is_signed)
5504/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005508
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005509 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005511 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 little_endian = 0;
5513 else {
5514 PyErr_SetString(PyExc_ValueError,
5515 "byteorder must be either 'little' or 'big'");
5516 return NULL;
5517 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 if (length < 0) {
5520 PyErr_SetString(PyExc_ValueError,
5521 "length argument must be non-negative");
5522 return NULL;
5523 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 bytes = PyBytes_FromStringAndSize(NULL, length);
5526 if (bytes == NULL)
5527 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005528
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005529 if (_PyLong_AsByteArray((PyLongObject *)self,
5530 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 length, little_endian, is_signed) < 0) {
5532 Py_DECREF(bytes);
5533 return NULL;
5534 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005537}
5538
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005539/*[clinic input]
5540@classmethod
5541int.from_bytes
5542
5543 bytes as bytes_obj: object
5544 Holds the array of bytes to convert. The argument must either
5545 support the buffer protocol or be an iterable object producing bytes.
5546 Bytes and bytearray are examples of built-in objects that support the
5547 buffer protocol.
5548 byteorder: unicode
5549 The byte order used to represent the integer. If byteorder is 'big',
5550 the most significant byte is at the beginning of the byte array. If
5551 byteorder is 'little', the most significant byte is at the end of the
5552 byte array. To request the native byte order of the host system, use
5553 `sys.byteorder' as the byte order value.
5554 *
5555 signed as is_signed: bool = False
5556 Indicates whether two's complement is used to represent the integer.
5557
5558Return the integer represented by the given array of bytes.
5559[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005560
5561static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005562int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5563 PyObject *byteorder, int is_signed)
5564/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005567 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005568
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005569 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005571 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 little_endian = 0;
5573 else {
5574 PyErr_SetString(PyExc_ValueError,
5575 "byteorder must be either 'little' or 'big'");
5576 return NULL;
5577 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005578
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005579 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005580 if (bytes == NULL)
5581 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583 long_obj = _PyLong_FromByteArray(
5584 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5585 little_endian, is_signed);
5586 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005587
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005588 if (long_obj != NULL && type != &PyLong_Type) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02005589 Py_SETREF(long_obj, _PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005590 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005592 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005593}
5594
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005595static PyObject *
5596long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5597{
5598 return long_long(self);
5599}
5600
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005601static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005602 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005603 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005604 INT_BIT_LENGTH_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00005605#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5607 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005608#endif
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005609 INT_TO_BYTES_METHODDEF
5610 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005611 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005612 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005613 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005614 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005615 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005616 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005617 "Ceiling of an Integral returns itself."},
5618 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5619 "Rounding an Integral returns itself.\n"
5620 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005621 INT___GETNEWARGS___METHODDEF
5622 INT___FORMAT___METHODDEF
5623 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005624 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005625};
5626
Guido van Rossumb43daf72007-08-01 18:08:08 +00005627static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005628 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005629 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005630 "the real part of a complex number",
5631 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005632 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005633 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005634 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005635 NULL},
5636 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005637 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005638 "the numerator of a rational number in lowest terms",
5639 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005640 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005641 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005642 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005643 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005644 {NULL} /* Sentinel */
5645};
5646
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005647PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005648"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005649int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005650\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005651Convert a number or string to an integer, or return 0 if no arguments\n\
5652are given. If x is a number, return x.__int__(). For floating point\n\
5653numbers, this truncates towards zero.\n\
5654\n\
5655If x is not a number or if base is given, then x must be a string,\n\
5656bytes, or bytearray instance representing an integer literal in the\n\
5657given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5658by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5659Base 0 means to interpret the base from the string as an integer literal.\n\
5660>>> int('0b100', base=0)\n\
56614");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005662
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005663static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005664 (binaryfunc)long_add, /*nb_add*/
5665 (binaryfunc)long_sub, /*nb_subtract*/
5666 (binaryfunc)long_mul, /*nb_multiply*/
5667 long_mod, /*nb_remainder*/
5668 long_divmod, /*nb_divmod*/
5669 long_pow, /*nb_power*/
5670 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005671 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005672 (unaryfunc)long_abs, /*tp_absolute*/
5673 (inquiry)long_bool, /*tp_bool*/
5674 (unaryfunc)long_invert, /*nb_invert*/
5675 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005676 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005677 long_and, /*nb_and*/
5678 long_xor, /*nb_xor*/
5679 long_or, /*nb_or*/
5680 long_long, /*nb_int*/
5681 0, /*nb_reserved*/
5682 long_float, /*nb_float*/
5683 0, /* nb_inplace_add */
5684 0, /* nb_inplace_subtract */
5685 0, /* nb_inplace_multiply */
5686 0, /* nb_inplace_remainder */
5687 0, /* nb_inplace_power */
5688 0, /* nb_inplace_lshift */
5689 0, /* nb_inplace_rshift */
5690 0, /* nb_inplace_and */
5691 0, /* nb_inplace_xor */
5692 0, /* nb_inplace_or */
5693 long_div, /* nb_floor_divide */
5694 long_true_divide, /* nb_true_divide */
5695 0, /* nb_inplace_floor_divide */
5696 0, /* nb_inplace_true_divide */
5697 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005698};
5699
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005700PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5702 "int", /* tp_name */
5703 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5704 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005705 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005706 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 0, /* tp_getattr */
5708 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005709 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 long_to_decimal_string, /* tp_repr */
5711 &long_as_number, /* tp_as_number */
5712 0, /* tp_as_sequence */
5713 0, /* tp_as_mapping */
5714 (hashfunc)long_hash, /* tp_hash */
5715 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005716 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005717 PyObject_GenericGetAttr, /* tp_getattro */
5718 0, /* tp_setattro */
5719 0, /* tp_as_buffer */
5720 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5721 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5722 long_doc, /* tp_doc */
5723 0, /* tp_traverse */
5724 0, /* tp_clear */
5725 long_richcompare, /* tp_richcompare */
5726 0, /* tp_weaklistoffset */
5727 0, /* tp_iter */
5728 0, /* tp_iternext */
5729 long_methods, /* tp_methods */
5730 0, /* tp_members */
5731 long_getset, /* tp_getset */
5732 0, /* tp_base */
5733 0, /* tp_dict */
5734 0, /* tp_descr_get */
5735 0, /* tp_descr_set */
5736 0, /* tp_dictoffset */
5737 0, /* tp_init */
5738 0, /* tp_alloc */
5739 long_new, /* tp_new */
5740 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005741};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005742
Mark Dickinsonbd792642009-03-18 20:06:12 +00005743static PyTypeObject Int_InfoType;
5744
5745PyDoc_STRVAR(int_info__doc__,
5746"sys.int_info\n\
5747\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07005748A named tuple that holds information about Python's\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00005749internal representation of integers. The attributes are read only.");
5750
5751static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005753 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005755};
5756
5757static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 "sys.int_info", /* name */
5759 int_info__doc__, /* doc */
5760 int_info_fields, /* fields */
5761 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005762};
5763
5764PyObject *
5765PyLong_GetInfo(void)
5766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005767 PyObject* int_info;
5768 int field = 0;
5769 int_info = PyStructSequence_New(&Int_InfoType);
5770 if (int_info == NULL)
5771 return NULL;
5772 PyStructSequence_SET_ITEM(int_info, field++,
5773 PyLong_FromLong(PyLong_SHIFT));
5774 PyStructSequence_SET_ITEM(int_info, field++,
5775 PyLong_FromLong(sizeof(digit)));
5776 if (PyErr_Occurred()) {
5777 Py_CLEAR(int_info);
5778 return NULL;
5779 }
5780 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005781}
5782
Guido van Rossumddefaf32007-01-14 03:31:43 +00005783int
5784_PyLong_Init(void)
5785{
5786#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005787 int ival, size;
5788 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005790 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5791 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5792 if (Py_TYPE(v) == &PyLong_Type) {
5793 /* The element is already initialized, most likely
5794 * the Python interpreter was initialized before.
5795 */
5796 Py_ssize_t refcnt;
5797 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005799 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5800 _Py_NewReference(op);
5801 /* _Py_NewReference sets the ref count to 1 but
5802 * the ref count might be larger. Set the refcnt
5803 * to the original refcnt + 1 */
5804 Py_REFCNT(op) = refcnt + 1;
5805 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005806 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 }
5808 else {
Victor Stinnerb509d522018-11-23 14:27:38 +01005809 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005810 }
5811 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005812 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005813 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005814#endif
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005815 _PyLong_Zero = PyLong_FromLong(0);
5816 if (_PyLong_Zero == NULL)
5817 return 0;
5818 _PyLong_One = PyLong_FromLong(1);
5819 if (_PyLong_One == NULL)
5820 return 0;
5821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005823 if (Int_InfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005824 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005825 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005826 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005827 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005829 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005830}
5831
5832void
Victor Stinnerbed48172019-08-27 00:12:32 +02005833_PyLong_Fini(void)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005835 /* Integers are currently statically allocated. Py_DECREF is not
5836 needed, but Python must forget about the reference or multiple
5837 reinitializations will fail. */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005838 Py_CLEAR(_PyLong_One);
5839 Py_CLEAR(_PyLong_Zero);
Guido van Rossumddefaf32007-01-14 03:31:43 +00005840#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 int i;
5842 PyLongObject *v = small_ints;
5843 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5844 _Py_DEC_REFTOTAL;
5845 _Py_ForgetReference((PyObject*)v);
5846 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005847#endif
5848}