blob: 74037be7a1ea3fc5c6d43aa70fbdda68fcba4797 [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
45static inline int
46is_small_int(long long ival)
47{
48 return -NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS;
49}
50
Guido van Rossumddefaf32007-01-14 03:31:43 +000051#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +000052Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000053#endif
54
Guido van Rossum7eaf8222007-06-18 17:58:50 +000055static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000056get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000057{
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050058 PyObject *v;
Greg Price5e63ab02019-08-24 10:19:37 -070059 assert(is_small_int(ival));
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050060 v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000062#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 if (ival >= 0)
Pablo Galindo49c75a82018-10-28 15:02:17 +000064 _Py_quick_int_allocs++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 else
Pablo Galindo49c75a82018-10-28 15:02:17 +000066 _Py_quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000067#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000069}
Guido van Rossumddefaf32007-01-14 03:31:43 +000070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000072maybe_small_long(PyLongObject *v)
73{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020074 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 sdigit ival = MEDIUM_VALUE(v);
Greg Price5e63ab02019-08-24 10:19:37 -070076 if (is_small_int(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 Py_DECREF(v);
78 return (PyLongObject *)get_small_int(ival);
79 }
80 }
81 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000082}
Guido van Rossumddefaf32007-01-14 03:31:43 +000083#else
Greg Price5e63ab02019-08-24 10:19:37 -070084#define is_small_int(ival) 0
85#define get_small_int(ival) (assert(0), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000086#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000087#endif
88
Serhiy Storchaka95949422013-08-27 19:40:23 +030089/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000090 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020091Py_LOCAL_INLINE(void)
92_PyLong_Negate(PyLongObject **x_p)
93{
94 PyLongObject *x;
95
96 x = (PyLongObject *)*x_p;
97 if (Py_REFCNT(x) == 1) {
98 Py_SIZE(x) = -Py_SIZE(x);
99 return;
100 }
101
102 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
103 Py_DECREF(x);
104}
105
Serhiy Storchaka95949422013-08-27 19:40:23 +0300106/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +0000107 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +0300108 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +0000109 */
Tim Peters0973b992004-08-29 22:16:50 +0000110#define KARATSUBA_CUTOFF 70
111#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +0000112
Tim Peters47e52ee2004-08-30 02:44:38 +0000113/* For exponentiation, use the binary left-to-right algorithm
114 * unless the exponent contains more than FIVEARY_CUTOFF digits.
115 * In that case, do 5 bits at a time. The potential drawback is that
116 * a table of 2**5 intermediate results is computed.
117 */
118#define FIVEARY_CUTOFF 8
119
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000120#define SIGCHECK(PyTryBlock) \
121 do { \
122 if (PyErr_CheckSignals()) PyTryBlock \
123 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000124
Serhiy Storchaka95949422013-08-27 19:40:23 +0300125/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000126 Doesn't attempt to free the storage--in most cases, due to the nature
127 of the algorithms used, this could save at most be one word anyway. */
128
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000129static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200130long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000131{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200132 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 while (i > 0 && v->ob_digit[i-1] == 0)
136 --i;
137 if (i != j)
138 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
139 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000140}
141
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200142/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
143 using the nb_int slot, if available. Raise TypeError if either the
144 nb_int slot is not available or the result of the call to nb_int
145 returns something not of type int.
146*/
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200147PyObject *
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200148_PyLong_FromNbInt(PyObject *integral)
149{
150 PyNumberMethods *nb;
151 PyObject *result;
152
153 /* Fast path for the case that we already have an int. */
154 if (PyLong_CheckExact(integral)) {
155 Py_INCREF(integral);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200156 return integral;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200157 }
158
159 nb = Py_TYPE(integral)->tp_as_number;
160 if (nb == NULL || nb->nb_int == NULL) {
161 PyErr_Format(PyExc_TypeError,
162 "an integer is required (got type %.200s)",
163 Py_TYPE(integral)->tp_name);
164 return NULL;
165 }
166
167 /* Convert using the nb_int slot, which should return something
168 of exact type int. */
169 result = nb->nb_int(integral);
170 if (!result || PyLong_CheckExact(result))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200171 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200172 if (!PyLong_Check(result)) {
173 PyErr_Format(PyExc_TypeError,
174 "__int__ returned non-int (type %.200s)",
175 result->ob_type->tp_name);
176 Py_DECREF(result);
177 return NULL;
178 }
179 /* Issue #17576: warn if 'result' not of exact type int. */
180 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
181 "__int__ returned non-int (type %.200s). "
182 "The ability to return an instance of a strict subclass of int "
183 "is deprecated, and may be removed in a future version of Python.",
184 result->ob_type->tp_name)) {
185 Py_DECREF(result);
186 return NULL;
187 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200188 return result;
189}
190
191/* Convert the given object to a PyLongObject using the nb_index or
192 nb_int slots, if available (the latter is deprecated).
193 Raise TypeError if either nb_index and nb_int slots are not
194 available or the result of the call to nb_index or nb_int
195 returns something not of type int.
196 Should be replaced with PyNumber_Index after the end of the
197 deprecation period.
198*/
199PyObject *
200_PyLong_FromNbIndexOrNbInt(PyObject *integral)
201{
202 PyNumberMethods *nb;
203 PyObject *result;
204
205 /* Fast path for the case that we already have an int. */
206 if (PyLong_CheckExact(integral)) {
207 Py_INCREF(integral);
208 return integral;
209 }
210
211 nb = Py_TYPE(integral)->tp_as_number;
212 if (nb == NULL || (nb->nb_index == NULL && nb->nb_int == NULL)) {
213 PyErr_Format(PyExc_TypeError,
214 "an integer is required (got type %.200s)",
215 Py_TYPE(integral)->tp_name);
216 return NULL;
217 }
218
219 if (nb->nb_index) {
220 /* Convert using the nb_index slot, which should return something
221 of exact type int. */
222 result = nb->nb_index(integral);
223 if (!result || PyLong_CheckExact(result))
224 return result;
225 if (!PyLong_Check(result)) {
226 PyErr_Format(PyExc_TypeError,
227 "__index__ returned non-int (type %.200s)",
228 result->ob_type->tp_name);
229 Py_DECREF(result);
230 return NULL;
231 }
232 /* Issue #17576: warn if 'result' not of exact type int. */
233 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
234 "__index__ returned non-int (type %.200s). "
235 "The ability to return an instance of a strict subclass of int "
236 "is deprecated, and may be removed in a future version of Python.",
237 result->ob_type->tp_name))
238 {
239 Py_DECREF(result);
240 return NULL;
241 }
242 return result;
243 }
244
245 result = _PyLong_FromNbInt(integral);
246 if (result && PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
247 "an integer is required (got type %.200s). "
248 "Implicit conversion to integers using __int__ is deprecated, "
249 "and may be removed in a future version of Python.",
250 Py_TYPE(integral)->tp_name))
251 {
252 Py_DECREF(result);
253 return NULL;
254 }
255 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200256}
257
258
Serhiy Storchaka95949422013-08-27 19:40:23 +0300259/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000260 Return NULL and set exception if we run out of memory. */
261
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000262#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000264
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000265PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000266_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 PyLongObject *result;
269 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
270 sizeof(digit)*size. Previous incarnations of this code used
271 sizeof(PyVarObject) instead of the offsetof, but this risks being
272 incorrect in the presence of padding between the PyVarObject header
273 and the digits. */
274 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
275 PyErr_SetString(PyExc_OverflowError,
276 "too many digits in integer");
277 return NULL;
278 }
279 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
280 size*sizeof(digit));
281 if (!result) {
282 PyErr_NoMemory();
283 return NULL;
284 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100285 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000286}
287
Tim Peters64b5ce32001-09-10 20:52:51 +0000288PyObject *
289_PyLong_Copy(PyLongObject *src)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 PyLongObject *result;
292 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 assert(src != NULL);
295 i = Py_SIZE(src);
296 if (i < 0)
297 i = -(i);
298 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100299 sdigit ival = MEDIUM_VALUE(src);
Greg Price5e63ab02019-08-24 10:19:37 -0700300 if (is_small_int(ival)) {
301 return get_small_int(ival);
302 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 }
304 result = _PyLong_New(i);
305 if (result != NULL) {
306 Py_SIZE(result) = Py_SIZE(src);
307 while (--i >= 0)
308 result->ob_digit[i] = src->ob_digit[i];
309 }
310 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000311}
312
Serhiy Storchaka95949422013-08-27 19:40:23 +0300313/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000314
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000315PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000316PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 PyLongObject *v;
319 unsigned long abs_ival;
320 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
321 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100322 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000323
Greg Price5e63ab02019-08-24 10:19:37 -0700324 if (is_small_int(ival)) {
325 return get_small_int((sdigit)ival);
326 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (ival < 0) {
329 /* negate: can't write this as abs_ival = -ival since that
330 invokes undefined behaviour when ival is LONG_MIN */
331 abs_ival = 0U-(unsigned long)ival;
332 sign = -1;
333 }
334 else {
335 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100336 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* Fast path for single-digit ints */
340 if (!(abs_ival >> PyLong_SHIFT)) {
341 v = _PyLong_New(1);
342 if (v) {
343 Py_SIZE(v) = sign;
344 v->ob_digit[0] = Py_SAFE_DOWNCAST(
345 abs_ival, unsigned long, digit);
346 }
347 return (PyObject*)v;
348 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000349
Mark Dickinson249b8982009-04-27 19:41:00 +0000350#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* 2 digits */
352 if (!(abs_ival >> 2*PyLong_SHIFT)) {
353 v = _PyLong_New(2);
354 if (v) {
355 Py_SIZE(v) = 2*sign;
356 v->ob_digit[0] = Py_SAFE_DOWNCAST(
357 abs_ival & PyLong_MASK, unsigned long, digit);
358 v->ob_digit[1] = Py_SAFE_DOWNCAST(
359 abs_ival >> PyLong_SHIFT, unsigned long, digit);
360 }
361 return (PyObject*)v;
362 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000363#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 /* Larger numbers: loop to determine number of digits */
366 t = abs_ival;
367 while (t) {
368 ++ndigits;
369 t >>= PyLong_SHIFT;
370 }
371 v = _PyLong_New(ndigits);
372 if (v != NULL) {
373 digit *p = v->ob_digit;
374 Py_SIZE(v) = ndigits*sign;
375 t = abs_ival;
376 while (t) {
377 *p++ = Py_SAFE_DOWNCAST(
378 t & PyLong_MASK, unsigned long, digit);
379 t >>= PyLong_SHIFT;
380 }
381 }
382 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000383}
384
Serhiy Storchaka95949422013-08-27 19:40:23 +0300385/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000386
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000387PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000388PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyLongObject *v;
391 unsigned long t;
392 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (ival < PyLong_BASE)
395 return PyLong_FromLong(ival);
396 /* Count the number of Python digits. */
orenmn86aa2692017-03-06 10:42:47 +0200397 t = ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 while (t) {
399 ++ndigits;
400 t >>= PyLong_SHIFT;
401 }
402 v = _PyLong_New(ndigits);
403 if (v != NULL) {
404 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 while (ival) {
406 *p++ = (digit)(ival & PyLong_MASK);
407 ival >>= PyLong_SHIFT;
408 }
409 }
410 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000411}
412
Serhiy Storchaka95949422013-08-27 19:40:23 +0300413/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000414
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 PyLongObject *v;
419 double frac;
420 int i, ndig, expo, neg;
421 neg = 0;
422 if (Py_IS_INFINITY(dval)) {
423 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000424 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 return NULL;
426 }
427 if (Py_IS_NAN(dval)) {
428 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000429 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 return NULL;
431 }
432 if (dval < 0.0) {
433 neg = 1;
434 dval = -dval;
435 }
436 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
437 if (expo <= 0)
438 return PyLong_FromLong(0L);
439 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
440 v = _PyLong_New(ndig);
441 if (v == NULL)
442 return NULL;
443 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
444 for (i = ndig; --i >= 0; ) {
445 digit bits = (digit)frac;
446 v->ob_digit[i] = bits;
447 frac = frac - (double)bits;
448 frac = ldexp(frac, PyLong_SHIFT);
449 }
450 if (neg)
451 Py_SIZE(v) = -(Py_SIZE(v));
452 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000453}
454
Thomas Wouters89f507f2006-12-13 04:49:30 +0000455/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
456 * anything about what happens when a signed integer operation overflows,
457 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700458 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000459 * (unsigned long)LONG_MAX, and for the smallest negative signed long
460 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
461 * However, some other compilers warn about applying unary minus to an
462 * unsigned operand. Hence the weird "0-".
463 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
465#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466
Serhiy Storchaka95949422013-08-27 19:40:23 +0300467/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100468 method.
469
470 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
471 the result. Otherwise *overflow is 0.
472
473 For other errors (e.g., TypeError), return -1 and set an error condition.
474 In this case *overflow will be 0.
475*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000476
477long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000478PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200481 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 unsigned long x, prev;
483 long res;
484 Py_ssize_t i;
485 int sign;
486 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 *overflow = 0;
489 if (vv == NULL) {
490 PyErr_BadInternalCall();
491 return -1;
492 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000493
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200494 if (PyLong_Check(vv)) {
495 v = (PyLongObject *)vv;
496 }
497 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200498 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200499 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return -1;
501 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 switch (i) {
508 case -1:
509 res = -(sdigit)v->ob_digit[0];
510 break;
511 case 0:
512 res = 0;
513 break;
514 case 1:
515 res = v->ob_digit[0];
516 break;
517 default:
518 sign = 1;
519 x = 0;
520 if (i < 0) {
521 sign = -1;
522 i = -(i);
523 }
524 while (--i >= 0) {
525 prev = x;
526 x = (x << PyLong_SHIFT) | v->ob_digit[i];
527 if ((x >> PyLong_SHIFT) != prev) {
528 *overflow = sign;
529 goto exit;
530 }
531 }
532 /* Haven't lost any bits, but casting to long requires extra
533 * care (see comment above).
534 */
535 if (x <= (unsigned long)LONG_MAX) {
536 res = (long)x * sign;
537 }
538 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
539 res = LONG_MIN;
540 }
541 else {
542 *overflow = sign;
543 /* res is already set to -1 */
544 }
545 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000546 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200548 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 }
550 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000551}
552
Serhiy Storchaka95949422013-08-27 19:40:23 +0300553/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100554 method. Return -1 and set an error if overflow occurs. */
555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000557PyLong_AsLong(PyObject *obj)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 int overflow;
560 long result = PyLong_AsLongAndOverflow(obj, &overflow);
561 if (overflow) {
562 /* XXX: could be cute and give a different
563 message for overflow == -1 */
564 PyErr_SetString(PyExc_OverflowError,
565 "Python int too large to convert to C long");
566 }
567 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000568}
569
Serhiy Storchaka95949422013-08-27 19:40:23 +0300570/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200571 method. Return -1 and set an error if overflow occurs. */
572
573int
574_PyLong_AsInt(PyObject *obj)
575{
576 int overflow;
577 long result = PyLong_AsLongAndOverflow(obj, &overflow);
578 if (overflow || result > INT_MAX || result < INT_MIN) {
579 /* XXX: could be cute and give a different
580 message for overflow == -1 */
581 PyErr_SetString(PyExc_OverflowError,
582 "Python int too large to convert to C int");
583 return -1;
584 }
585 return (int)result;
586}
587
Serhiy Storchaka95949422013-08-27 19:40:23 +0300588/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000589 Returns -1 and sets an error condition if overflow occurs. */
590
591Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000592PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200593 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 size_t x, prev;
595 Py_ssize_t i;
596 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (vv == NULL) {
599 PyErr_BadInternalCall();
600 return -1;
601 }
602 if (!PyLong_Check(vv)) {
603 PyErr_SetString(PyExc_TypeError, "an integer is required");
604 return -1;
605 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 v = (PyLongObject *)vv;
608 i = Py_SIZE(v);
609 switch (i) {
610 case -1: return -(sdigit)v->ob_digit[0];
611 case 0: return 0;
612 case 1: return v->ob_digit[0];
613 }
614 sign = 1;
615 x = 0;
616 if (i < 0) {
617 sign = -1;
618 i = -(i);
619 }
620 while (--i >= 0) {
621 prev = x;
622 x = (x << PyLong_SHIFT) | v->ob_digit[i];
623 if ((x >> PyLong_SHIFT) != prev)
624 goto overflow;
625 }
626 /* Haven't lost any bits, but casting to a signed type requires
627 * extra care (see comment above).
628 */
629 if (x <= (size_t)PY_SSIZE_T_MAX) {
630 return (Py_ssize_t)x * sign;
631 }
632 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
633 return PY_SSIZE_T_MIN;
634 }
635 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000636
Mark Dickinson22b20182010-05-10 21:27:53 +0000637 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyErr_SetString(PyExc_OverflowError,
639 "Python int too large to convert to C ssize_t");
640 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000641}
642
Serhiy Storchaka95949422013-08-27 19:40:23 +0300643/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000644 Returns -1 and sets an error condition if overflow occurs. */
645
646unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000647PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000648{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200649 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 unsigned long x, prev;
651 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (vv == NULL) {
654 PyErr_BadInternalCall();
655 return (unsigned long)-1;
656 }
657 if (!PyLong_Check(vv)) {
658 PyErr_SetString(PyExc_TypeError, "an integer is required");
659 return (unsigned long)-1;
660 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 v = (PyLongObject *)vv;
663 i = Py_SIZE(v);
664 x = 0;
665 if (i < 0) {
666 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000667 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 return (unsigned long) -1;
669 }
670 switch (i) {
671 case 0: return 0;
672 case 1: return v->ob_digit[0];
673 }
674 while (--i >= 0) {
675 prev = x;
676 x = (x << PyLong_SHIFT) | v->ob_digit[i];
677 if ((x >> PyLong_SHIFT) != prev) {
678 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100679 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000680 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return (unsigned long) -1;
682 }
683 }
684 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000685}
686
Serhiy Storchaka95949422013-08-27 19:40:23 +0300687/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200688 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000689
690size_t
691PyLong_AsSize_t(PyObject *vv)
692{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200693 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 size_t x, prev;
695 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (vv == NULL) {
698 PyErr_BadInternalCall();
699 return (size_t) -1;
700 }
701 if (!PyLong_Check(vv)) {
702 PyErr_SetString(PyExc_TypeError, "an integer is required");
703 return (size_t)-1;
704 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 v = (PyLongObject *)vv;
707 i = Py_SIZE(v);
708 x = 0;
709 if (i < 0) {
710 PyErr_SetString(PyExc_OverflowError,
711 "can't convert negative value to size_t");
712 return (size_t) -1;
713 }
714 switch (i) {
715 case 0: return 0;
716 case 1: return v->ob_digit[0];
717 }
718 while (--i >= 0) {
719 prev = x;
720 x = (x << PyLong_SHIFT) | v->ob_digit[i];
721 if ((x >> PyLong_SHIFT) != prev) {
722 PyErr_SetString(PyExc_OverflowError,
723 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200724 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 }
726 }
727 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000728}
729
Serhiy Storchaka95949422013-08-27 19:40:23 +0300730/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000731 Returns -1 and sets an error condition if an error occurs. */
732
Guido van Rossumddefaf32007-01-14 03:31:43 +0000733static unsigned long
734_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000735{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200736 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 unsigned long x;
738 Py_ssize_t i;
739 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 if (vv == NULL || !PyLong_Check(vv)) {
742 PyErr_BadInternalCall();
743 return (unsigned long) -1;
744 }
745 v = (PyLongObject *)vv;
746 i = Py_SIZE(v);
747 switch (i) {
748 case 0: return 0;
749 case 1: return v->ob_digit[0];
750 }
751 sign = 1;
752 x = 0;
753 if (i < 0) {
754 sign = -1;
755 i = -i;
756 }
757 while (--i >= 0) {
758 x = (x << PyLong_SHIFT) | v->ob_digit[i];
759 }
760 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000761}
762
Guido van Rossumddefaf32007-01-14 03:31:43 +0000763unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200764PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyLongObject *lo;
767 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000768
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200769 if (op == NULL) {
770 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 return (unsigned long)-1;
772 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000773
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200774 if (PyLong_Check(op)) {
775 return _PyLong_AsUnsignedLongMask(op);
776 }
777
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200778 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (lo == NULL)
780 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200781
782 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
783 Py_DECREF(lo);
784 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000785}
786
Tim Peters5b8132f2003-01-31 15:52:05 +0000787int
788_PyLong_Sign(PyObject *vv)
789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 assert(v != NULL);
793 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000796}
797
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200798/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
799 2**k if d is nonzero, else 0. */
800
801static const unsigned char BitLengthTable[32] = {
802 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
803 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
804};
805
806static int
807bits_in_digit(digit d)
808{
809 int d_bits = 0;
810 while (d >= 32) {
811 d_bits += 6;
812 d >>= 6;
813 }
814 d_bits += (int)BitLengthTable[d];
815 return d_bits;
816}
817
Tim Petersbaefd9e2003-01-28 20:37:45 +0000818size_t
819_PyLong_NumBits(PyObject *vv)
820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyLongObject *v = (PyLongObject *)vv;
822 size_t result = 0;
823 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200824 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 assert(v != NULL);
827 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200828 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
830 if (ndigits > 0) {
831 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700832 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100834 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200835 msd_bits = bits_in_digit(msd);
836 if (SIZE_MAX - msd_bits < result)
837 goto Overflow;
838 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 }
840 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000841
Mark Dickinson22b20182010-05-10 21:27:53 +0000842 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
844 "to express in a platform size_t");
845 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000846}
847
Tim Peters2a9b3672001-06-11 21:23:58 +0000848PyObject *
849_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000851{
Mark Dickinson22b20182010-05-10 21:27:53 +0000852 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 int incr; /* direction to move pstartbyte */
854 const unsigned char* pendbyte; /* MSB of bytes */
855 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300856 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyLongObject* v; /* result */
858 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 if (n == 0)
861 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 if (little_endian) {
864 pstartbyte = bytes;
865 pendbyte = bytes + n - 1;
866 incr = 1;
867 }
868 else {
869 pstartbyte = bytes + n - 1;
870 pendbyte = bytes;
871 incr = -1;
872 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (is_signed)
875 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200878 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 is positive, and leading 0xff bytes if negative. */
880 {
881 size_t i;
882 const unsigned char* p = pendbyte;
883 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000884 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000887 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 break;
889 }
890 numsignificantbytes = n - i;
891 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
892 actually has 2 significant bytes. OTOH, 0xff0001 ==
893 -0x00ffff, so we wouldn't *need* to bump it there; but we
894 do for 0xffff = -0x0001. To be safe without bothering to
895 check every case, bump it regardless. */
896 if (is_signed && numsignificantbytes < n)
897 ++numsignificantbytes;
898 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000899
Serhiy Storchaka95949422013-08-27 19:40:23 +0300900 /* How many Python int digits do we need? We have
901 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
903 /* catch overflow before it happens */
904 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
905 PyErr_SetString(PyExc_OverflowError,
906 "byte array too long to convert to int");
907 return NULL;
908 }
909 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
910 v = _PyLong_New(ndigits);
911 if (v == NULL)
912 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Copy the bits over. The tricky parts are computing 2's-comp on
915 the fly for signed numbers, and dealing with the mismatch between
916 8-bit bytes and (probably) 15-bit Python digits.*/
917 {
918 size_t i;
919 twodigits carry = 1; /* for 2's-comp calculation */
920 twodigits accum = 0; /* sliding register */
921 unsigned int accumbits = 0; /* number of bits in accum */
922 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
925 twodigits thisbyte = *p;
926 /* Compute correction for 2's comp, if needed. */
927 if (is_signed) {
928 thisbyte = (0xff ^ thisbyte) + carry;
929 carry = thisbyte >> 8;
930 thisbyte &= 0xff;
931 }
932 /* Because we're going LSB to MSB, thisbyte is
933 more significant than what's already in accum,
934 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200935 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 accumbits += 8;
937 if (accumbits >= PyLong_SHIFT) {
938 /* There's enough to fill a Python digit. */
939 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000940 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 ++idigit;
942 accum >>= PyLong_SHIFT;
943 accumbits -= PyLong_SHIFT;
944 assert(accumbits < PyLong_SHIFT);
945 }
946 }
947 assert(accumbits < PyLong_SHIFT);
948 if (accumbits) {
949 assert(idigit < ndigits);
950 v->ob_digit[idigit] = (digit)accum;
951 ++idigit;
952 }
953 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 Py_SIZE(v) = is_signed ? -idigit : idigit;
956 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000957}
958
959int
960_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 unsigned char* bytes, size_t n,
962 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000965 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000967 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
969 digit carry; /* for computing 2's-comp */
970 size_t j; /* # bytes filled */
971 unsigned char* p; /* pointer to next byte in bytes */
972 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (Py_SIZE(v) < 0) {
977 ndigits = -(Py_SIZE(v));
978 if (!is_signed) {
979 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000980 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 return -1;
982 }
983 do_twos_comp = 1;
984 }
985 else {
986 ndigits = Py_SIZE(v);
987 do_twos_comp = 0;
988 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (little_endian) {
991 p = bytes;
992 pincr = 1;
993 }
994 else {
995 p = bytes + n - 1;
996 pincr = -1;
997 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* Copy over all the Python digits.
1000 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +03001001 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 normalized. */
1003 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
1004 j = 0;
1005 accum = 0;
1006 accumbits = 0;
1007 carry = do_twos_comp ? 1 : 0;
1008 for (i = 0; i < ndigits; ++i) {
1009 digit thisdigit = v->ob_digit[i];
1010 if (do_twos_comp) {
1011 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
1012 carry = thisdigit >> PyLong_SHIFT;
1013 thisdigit &= PyLong_MASK;
1014 }
1015 /* Because we're going LSB to MSB, thisdigit is more
1016 significant than what's already in accum, so needs to be
1017 prepended to accum. */
1018 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 /* The most-significant digit may be (probably is) at least
1021 partly empty. */
1022 if (i == ndigits - 1) {
1023 /* Count # of sign bits -- they needn't be stored,
1024 * although for signed conversion we need later to
1025 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +00001026 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 while (s != 0) {
1028 s >>= 1;
1029 accumbits++;
1030 }
1031 }
1032 else
1033 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* Store as many bytes as possible. */
1036 while (accumbits >= 8) {
1037 if (j >= n)
1038 goto Overflow;
1039 ++j;
1040 *p = (unsigned char)(accum & 0xff);
1041 p += pincr;
1042 accumbits -= 8;
1043 accum >>= 8;
1044 }
1045 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 /* Store the straggler (if any). */
1048 assert(accumbits < 8);
1049 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1050 if (accumbits > 0) {
1051 if (j >= n)
1052 goto Overflow;
1053 ++j;
1054 if (do_twos_comp) {
1055 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +03001056 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 infinite supply of sign bits). */
1058 accum |= (~(twodigits)0) << accumbits;
1059 }
1060 *p = (unsigned char)(accum & 0xff);
1061 p += pincr;
1062 }
1063 else if (j == n && n > 0 && is_signed) {
1064 /* The main loop filled the byte array exactly, so the code
1065 just above didn't get to ensure there's a sign bit, and the
1066 loop below wouldn't add one either. Make sure a sign bit
1067 exists. */
1068 unsigned char msb = *(p - pincr);
1069 int sign_bit_set = msb >= 0x80;
1070 assert(accumbits == 0);
1071 if (sign_bit_set == do_twos_comp)
1072 return 0;
1073 else
1074 goto Overflow;
1075 }
Tim Peters05607ad2001-06-13 21:01:27 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 /* Fill remaining bytes with copies of the sign bit. */
1078 {
1079 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1080 for ( ; j < n; ++j, p += pincr)
1081 *p = signbyte;
1082 }
Tim Peters05607ad2001-06-13 21:01:27 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001085
Mark Dickinson22b20182010-05-10 21:27:53 +00001086 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1088 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001089
Tim Peters2a9b3672001-06-11 21:23:58 +00001090}
1091
Serhiy Storchaka95949422013-08-27 19:40:23 +03001092/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001093
1094PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001095PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001096{
Mark Dickinson91044792012-10-18 19:21:43 +01001097#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001098 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001099#else
1100
Tim Peters70128a12001-06-16 08:48:40 +00001101#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001102# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001103#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001104 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001105#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001106
Guido van Rossum78694d91998-09-18 14:14:13 +00001107}
1108
Serhiy Storchaka95949422013-08-27 19:40:23 +03001109/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001110
1111void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001112PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001113{
Tim Peters70128a12001-06-16 08:48:40 +00001114#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1118 x = PyLong_AsLong(vv);
1119 else
1120 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001121#else
Tim Peters70128a12001-06-16 08:48:40 +00001122
Tim Peters70128a12001-06-16 08:48:40 +00001123#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001124# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001125#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001126 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1129 x = PyLong_AsLongLong(vv);
1130 else
1131 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001132
1133#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (x == -1 && PyErr_Occurred())
1136 return NULL;
1137 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001138}
1139
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001140/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001141 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001142 */
1143
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001144#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001145
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001146/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001147
1148PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001149PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001152 unsigned long long abs_ival;
1153 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 int ndigits = 0;
1155 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001156
Greg Price5e63ab02019-08-24 10:19:37 -07001157 if (is_small_int(ival)) {
1158 return get_small_int((sdigit)ival);
1159 }
1160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (ival < 0) {
1162 /* avoid signed overflow on negation; see comments
1163 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001164 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 negative = 1;
1166 }
1167 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001168 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 /* Count the number of Python digits.
1172 We used to pick 5 ("big enough for anything"), but that's a
1173 waste of time and space given that 5*15 = 75 bits are rarely
1174 needed. */
1175 t = abs_ival;
1176 while (t) {
1177 ++ndigits;
1178 t >>= PyLong_SHIFT;
1179 }
1180 v = _PyLong_New(ndigits);
1181 if (v != NULL) {
1182 digit *p = v->ob_digit;
1183 Py_SIZE(v) = negative ? -ndigits : ndigits;
1184 t = abs_ival;
1185 while (t) {
1186 *p++ = (digit)(t & PyLong_MASK);
1187 t >>= PyLong_SHIFT;
1188 }
1189 }
1190 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001191}
1192
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001193/* Create a new int object from a C unsigned long long int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001194
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001195PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001196PyLong_FromUnsignedLongLong(unsigned long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001199 unsigned long long t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (ival < PyLong_BASE)
1203 return PyLong_FromLong((long)ival);
1204 /* Count the number of Python digits. */
orenmn86aa2692017-03-06 10:42:47 +02001205 t = ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 while (t) {
1207 ++ndigits;
1208 t >>= PyLong_SHIFT;
1209 }
1210 v = _PyLong_New(ndigits);
1211 if (v != NULL) {
1212 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 while (ival) {
1214 *p++ = (digit)(ival & PyLong_MASK);
1215 ival >>= PyLong_SHIFT;
1216 }
1217 }
1218 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001219}
1220
Serhiy Storchaka95949422013-08-27 19:40:23 +03001221/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001222
1223PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001224PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 PyLongObject *v;
1227 size_t abs_ival;
1228 size_t t; /* unsigned so >> doesn't propagate sign bit */
1229 int ndigits = 0;
1230 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001231
Greg Price5e63ab02019-08-24 10:19:37 -07001232 if (is_small_int(ival)) {
1233 return get_small_int((sdigit)ival);
1234 }
1235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 if (ival < 0) {
1237 /* avoid signed overflow when ival = SIZE_T_MIN */
1238 abs_ival = (size_t)(-1-ival)+1;
1239 negative = 1;
1240 }
1241 else {
1242 abs_ival = (size_t)ival;
1243 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 /* Count the number of Python digits. */
1246 t = abs_ival;
1247 while (t) {
1248 ++ndigits;
1249 t >>= PyLong_SHIFT;
1250 }
1251 v = _PyLong_New(ndigits);
1252 if (v != NULL) {
1253 digit *p = v->ob_digit;
1254 Py_SIZE(v) = negative ? -ndigits : ndigits;
1255 t = abs_ival;
1256 while (t) {
1257 *p++ = (digit)(t & PyLong_MASK);
1258 t >>= PyLong_SHIFT;
1259 }
1260 }
1261 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001262}
1263
Serhiy Storchaka95949422013-08-27 19:40:23 +03001264/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001265
1266PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001267PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 PyLongObject *v;
1270 size_t t;
1271 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (ival < PyLong_BASE)
1274 return PyLong_FromLong((long)ival);
1275 /* Count the number of Python digits. */
1276 t = ival;
1277 while (t) {
1278 ++ndigits;
1279 t >>= PyLong_SHIFT;
1280 }
1281 v = _PyLong_New(ndigits);
1282 if (v != NULL) {
1283 digit *p = v->ob_digit;
1284 Py_SIZE(v) = ndigits;
1285 while (ival) {
1286 *p++ = (digit)(ival & PyLong_MASK);
1287 ival >>= PyLong_SHIFT;
1288 }
1289 }
1290 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001291}
1292
Serhiy Storchaka95949422013-08-27 19:40:23 +03001293/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001294 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001295
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001296long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001297PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001300 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001302 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 if (vv == NULL) {
1305 PyErr_BadInternalCall();
1306 return -1;
1307 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001308
1309 if (PyLong_Check(vv)) {
1310 v = (PyLongObject *)vv;
1311 }
1312 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001313 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001314 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001316 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001318
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001319 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001321 case -1:
1322 bytes = -(sdigit)v->ob_digit[0];
1323 break;
1324 case 0:
1325 bytes = 0;
1326 break;
1327 case 1:
1328 bytes = v->ob_digit[0];
1329 break;
1330 default:
1331 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001332 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001334 if (do_decref) {
1335 Py_DECREF(v);
1336 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001337
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001338 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001340 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 else
1342 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001343}
1344
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001345/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001346 Return -1 and set an error if overflow occurs. */
1347
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001348unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001349PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001352 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001354
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001355 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001357 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001359 if (!PyLong_Check(vv)) {
1360 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001361 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001362 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 v = (PyLongObject*)vv;
1365 switch(Py_SIZE(v)) {
1366 case 0: return 0;
1367 case 1: return v->ob_digit[0];
1368 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001369
Mark Dickinson22b20182010-05-10 21:27:53 +00001370 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001371 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001372
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001373 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001375 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 else
1377 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001378}
Tim Petersd1a7da62001-06-13 00:35:57 +00001379
Serhiy Storchaka95949422013-08-27 19:40:23 +03001380/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001381 Returns -1 and sets an error condition if an error occurs. */
1382
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001383static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001384_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001385{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001386 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001387 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 Py_ssize_t i;
1389 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 if (vv == NULL || !PyLong_Check(vv)) {
1392 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001393 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 }
1395 v = (PyLongObject *)vv;
1396 switch(Py_SIZE(v)) {
1397 case 0: return 0;
1398 case 1: return v->ob_digit[0];
1399 }
1400 i = Py_SIZE(v);
1401 sign = 1;
1402 x = 0;
1403 if (i < 0) {
1404 sign = -1;
1405 i = -i;
1406 }
1407 while (--i >= 0) {
1408 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1409 }
1410 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001411}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001412
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001413unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001414PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001417 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001418
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001419 if (op == NULL) {
1420 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001421 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001423
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001424 if (PyLong_Check(op)) {
1425 return _PyLong_AsUnsignedLongLongMask(op);
1426 }
1427
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001428 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001430 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001431
1432 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1433 Py_DECREF(lo);
1434 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001435}
Tim Petersd1a7da62001-06-13 00:35:57 +00001436
Serhiy Storchaka95949422013-08-27 19:40:23 +03001437/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001438 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001439
Mark Dickinson8d48b432011-10-23 20:47:14 +01001440 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1441 the result. Otherwise *overflow is 0.
1442
1443 For other errors (e.g., TypeError), return -1 and set an error condition.
1444 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001445*/
1446
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001447long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001448PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001451 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001452 unsigned long long x, prev;
1453 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 Py_ssize_t i;
1455 int sign;
1456 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 *overflow = 0;
1459 if (vv == NULL) {
1460 PyErr_BadInternalCall();
1461 return -1;
1462 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001463
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001464 if (PyLong_Check(vv)) {
1465 v = (PyLongObject *)vv;
1466 }
1467 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001468 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001469 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 return -1;
1471 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 switch (i) {
1478 case -1:
1479 res = -(sdigit)v->ob_digit[0];
1480 break;
1481 case 0:
1482 res = 0;
1483 break;
1484 case 1:
1485 res = v->ob_digit[0];
1486 break;
1487 default:
1488 sign = 1;
1489 x = 0;
1490 if (i < 0) {
1491 sign = -1;
1492 i = -(i);
1493 }
1494 while (--i >= 0) {
1495 prev = x;
1496 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1497 if ((x >> PyLong_SHIFT) != prev) {
1498 *overflow = sign;
1499 goto exit;
1500 }
1501 }
1502 /* Haven't lost any bits, but casting to long requires extra
1503 * care (see comment above).
1504 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001505 if (x <= (unsigned long long)PY_LLONG_MAX) {
1506 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 }
1508 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1509 res = PY_LLONG_MIN;
1510 }
1511 else {
1512 *overflow = sign;
1513 /* res is already set to -1 */
1514 }
1515 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001516 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001518 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 }
1520 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001521}
1522
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001523int
1524_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1525{
1526 unsigned long uval;
1527
1528 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1529 PyErr_SetString(PyExc_ValueError, "value must be positive");
1530 return 0;
1531 }
1532 uval = PyLong_AsUnsignedLong(obj);
1533 if (uval == (unsigned long)-1 && PyErr_Occurred())
1534 return 0;
1535 if (uval > USHRT_MAX) {
1536 PyErr_SetString(PyExc_OverflowError,
1537 "Python int too large for C unsigned short");
1538 return 0;
1539 }
1540
1541 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1542 return 1;
1543}
1544
1545int
1546_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1547{
1548 unsigned 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_AsUnsignedLong(obj);
1555 if (uval == (unsigned long)-1 && PyErr_Occurred())
1556 return 0;
1557 if (uval > UINT_MAX) {
1558 PyErr_SetString(PyExc_OverflowError,
1559 "Python int too large for C unsigned int");
1560 return 0;
1561 }
1562
1563 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1564 return 1;
1565}
1566
1567int
1568_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1569{
1570 unsigned long uval;
1571
1572 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1573 PyErr_SetString(PyExc_ValueError, "value must be positive");
1574 return 0;
1575 }
1576 uval = PyLong_AsUnsignedLong(obj);
1577 if (uval == (unsigned long)-1 && PyErr_Occurred())
1578 return 0;
1579
1580 *(unsigned long *)ptr = uval;
1581 return 1;
1582}
1583
1584int
1585_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1586{
1587 unsigned long long uval;
1588
1589 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1590 PyErr_SetString(PyExc_ValueError, "value must be positive");
1591 return 0;
1592 }
1593 uval = PyLong_AsUnsignedLongLong(obj);
1594 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1595 return 0;
1596
1597 *(unsigned long long *)ptr = uval;
1598 return 1;
1599}
1600
1601int
1602_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1603{
1604 size_t uval;
1605
1606 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1607 PyErr_SetString(PyExc_ValueError, "value must be positive");
1608 return 0;
1609 }
1610 uval = PyLong_AsSize_t(obj);
1611 if (uval == (size_t)-1 && PyErr_Occurred())
1612 return 0;
1613
1614 *(size_t *)ptr = uval;
1615 return 1;
1616}
1617
1618
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001619#define CHECK_BINOP(v,w) \
1620 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001621 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1622 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001623 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001624
Tim Peters877a2122002-08-12 05:09:36 +00001625/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1626 * is modified in place, by adding y to it. Carries are propagated as far as
1627 * x[m-1], and the remaining carry (0 or 1) is returned.
1628 */
1629static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001630v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 Py_ssize_t i;
1633 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 assert(m >= n);
1636 for (i = 0; i < n; ++i) {
1637 carry += x[i] + y[i];
1638 x[i] = carry & PyLong_MASK;
1639 carry >>= PyLong_SHIFT;
1640 assert((carry & 1) == carry);
1641 }
1642 for (; carry && i < m; ++i) {
1643 carry += x[i];
1644 x[i] = carry & PyLong_MASK;
1645 carry >>= PyLong_SHIFT;
1646 assert((carry & 1) == carry);
1647 }
1648 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001649}
1650
1651/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1652 * is modified in place, by subtracting y from it. Borrows are propagated as
1653 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1654 */
1655static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001656v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 Py_ssize_t i;
1659 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 assert(m >= n);
1662 for (i = 0; i < n; ++i) {
1663 borrow = x[i] - y[i] - borrow;
1664 x[i] = borrow & PyLong_MASK;
1665 borrow >>= PyLong_SHIFT;
1666 borrow &= 1; /* keep only 1 sign bit */
1667 }
1668 for (; borrow && i < m; ++i) {
1669 borrow = x[i] - borrow;
1670 x[i] = borrow & PyLong_MASK;
1671 borrow >>= PyLong_SHIFT;
1672 borrow &= 1;
1673 }
1674 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001675}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001676
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001677/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1678 * result in z[0:m], and return the d bits shifted out of the top.
1679 */
1680static digit
1681v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 Py_ssize_t i;
1684 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 assert(0 <= d && d < PyLong_SHIFT);
1687 for (i=0; i < m; i++) {
1688 twodigits acc = (twodigits)a[i] << d | carry;
1689 z[i] = (digit)acc & PyLong_MASK;
1690 carry = (digit)(acc >> PyLong_SHIFT);
1691 }
1692 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001693}
1694
1695/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1696 * result in z[0:m], and return the d bits shifted out of the bottom.
1697 */
1698static digit
1699v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 Py_ssize_t i;
1702 digit carry = 0;
1703 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 assert(0 <= d && d < PyLong_SHIFT);
1706 for (i=m; i-- > 0;) {
1707 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1708 carry = (digit)acc & mask;
1709 z[i] = (digit)(acc >> d);
1710 }
1711 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001712}
1713
Tim Peters212e6142001-07-14 12:23:19 +00001714/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1715 in pout, and returning the remainder. pin and pout point at the LSD.
1716 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001717 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001718 immutable. */
1719
1720static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001721inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 assert(n > 0 && n <= PyLong_MASK);
1726 pin += size;
1727 pout += size;
1728 while (--size >= 0) {
1729 digit hi;
1730 rem = (rem << PyLong_SHIFT) | *--pin;
1731 *--pout = hi = (digit)(rem / n);
1732 rem -= (twodigits)hi * n;
1733 }
1734 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001735}
1736
Serhiy Storchaka95949422013-08-27 19:40:23 +03001737/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001738 (as function result) and the remainder (through *prem).
1739 The sign of a is ignored; n should not be zero. */
1740
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001741static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001742divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001743{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001744 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 assert(n > 0 && n <= PyLong_MASK);
1748 z = _PyLong_New(size);
1749 if (z == NULL)
1750 return NULL;
1751 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1752 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001753}
1754
Serhiy Storchaka95949422013-08-27 19:40:23 +03001755/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001756 string. (Return value is non-shared so that callers can modify the
1757 returned value if necessary.) */
1758
Victor Stinnerd3f08822012-05-29 12:57:52 +02001759static int
1760long_to_decimal_string_internal(PyObject *aa,
1761 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001762 _PyUnicodeWriter *writer,
1763 _PyBytesWriter *bytes_writer,
1764 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001767 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 Py_ssize_t size, strlen, size_a, i, j;
1769 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001771 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001772 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 a = (PyLongObject *)aa;
1775 if (a == NULL || !PyLong_Check(a)) {
1776 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001777 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001779 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 /* quick and dirty upper bound for the number of digits
1783 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 But log2(a) < size_a * PyLong_SHIFT, and
1788 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001789 > 3.3 * _PyLong_DECIMAL_SHIFT
1790
1791 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1792 size_a + size_a / d < size_a + size_a / floor(d),
1793 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1794 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001796 d = (33 * _PyLong_DECIMAL_SHIFT) /
1797 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1798 assert(size_a < PY_SSIZE_T_MAX/2);
1799 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 scratch = _PyLong_New(size);
1801 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001802 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* convert array of base _PyLong_BASE digits in pin to an array of
1805 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1806 Volume 2 (3rd edn), section 4.4, Method 1b). */
1807 pin = a->ob_digit;
1808 pout = scratch->ob_digit;
1809 size = 0;
1810 for (i = size_a; --i >= 0; ) {
1811 digit hi = pin[i];
1812 for (j = 0; j < size; j++) {
1813 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1814 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1815 pout[j] = (digit)(z - (twodigits)hi *
1816 _PyLong_DECIMAL_BASE);
1817 }
1818 while (hi) {
1819 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1820 hi /= _PyLong_DECIMAL_BASE;
1821 }
1822 /* check for keyboard interrupt */
1823 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001824 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001825 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001826 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 }
1828 /* pout should have at least one digit, so that the case when a = 0
1829 works correctly */
1830 if (size == 0)
1831 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 /* calculate exact length of output string, and allocate */
1834 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1835 tenpow = 10;
1836 rem = pout[size-1];
1837 while (rem >= tenpow) {
1838 tenpow *= 10;
1839 strlen++;
1840 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001841 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001842 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1843 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001844 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001845 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001846 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001848 else if (bytes_writer) {
1849 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1850 if (*bytes_str == NULL) {
1851 Py_DECREF(scratch);
1852 return -1;
1853 }
1854 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001855 else {
1856 str = PyUnicode_New(strlen, '9');
1857 if (str == NULL) {
1858 Py_DECREF(scratch);
1859 return -1;
1860 }
1861 kind = PyUnicode_KIND(str);
1862 }
1863
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001864#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001865 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001866 /* pout[0] through pout[size-2] contribute exactly \
1867 _PyLong_DECIMAL_SHIFT digits each */ \
1868 for (i=0; i < size - 1; i++) { \
1869 rem = pout[i]; \
1870 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1871 *--p = '0' + rem % 10; \
1872 rem /= 10; \
1873 } \
1874 } \
1875 /* pout[size-1]: always produce at least one decimal digit */ \
1876 rem = pout[i]; \
1877 do { \
1878 *--p = '0' + rem % 10; \
1879 rem /= 10; \
1880 } while (rem != 0); \
1881 \
1882 /* and sign */ \
1883 if (negative) \
1884 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001885 } while (0)
1886
1887#define WRITE_UNICODE_DIGITS(TYPE) \
1888 do { \
1889 if (writer) \
1890 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1891 else \
1892 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1893 \
1894 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001895 \
1896 /* check we've counted correctly */ \
1897 if (writer) \
1898 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1899 else \
1900 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1901 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001904 if (bytes_writer) {
1905 char *p = *bytes_str + strlen;
1906 WRITE_DIGITS(p);
1907 assert(p == *bytes_str);
1908 }
1909 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001910 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001911 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001913 else if (kind == PyUnicode_2BYTE_KIND) {
1914 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001915 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001916 }
1917 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001918 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001919 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001920 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001921 }
1922#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001923#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001926 if (writer) {
1927 writer->pos += strlen;
1928 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001929 else if (bytes_writer) {
1930 (*bytes_str) += strlen;
1931 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001932 else {
1933 assert(_PyUnicode_CheckConsistency(str, 1));
1934 *p_output = (PyObject *)str;
1935 }
1936 return 0;
1937}
1938
1939static PyObject *
1940long_to_decimal_string(PyObject *aa)
1941{
1942 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001943 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001944 return NULL;
1945 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001946}
1947
Serhiy Storchaka95949422013-08-27 19:40:23 +03001948/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001949 which should be one of 2, 8 or 16. Return a string object.
1950 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1951 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001952
Victor Stinnerd3f08822012-05-29 12:57:52 +02001953static int
1954long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001955 PyObject **p_output, _PyUnicodeWriter *writer,
1956 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001957{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001958 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001959 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001960 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001962 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001963 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001965
Victor Stinnerd3f08822012-05-29 12:57:52 +02001966 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 if (a == NULL || !PyLong_Check(a)) {
1968 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001969 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001971 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001972 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* Compute a rough upper bound for the length of the string */
1975 switch (base) {
1976 case 16:
1977 bits = 4;
1978 break;
1979 case 8:
1980 bits = 3;
1981 break;
1982 case 2:
1983 bits = 1;
1984 break;
1985 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001986 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001988
Mark Dickinsone2846542012-04-20 21:21:24 +01001989 /* Compute exact length 'sz' of output string. */
1990 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001991 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001992 }
1993 else {
1994 Py_ssize_t size_a_in_bits;
1995 /* Ensure overflow doesn't occur during computation of sz. */
1996 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1997 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001998 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001999 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01002000 }
2001 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
2002 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002003 /* Allow 1 character for a '-' sign. */
2004 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
2005 }
2006 if (alternate) {
2007 /* 2 characters for prefix */
2008 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01002009 }
2010
Victor Stinnerd3f08822012-05-29 12:57:52 +02002011 if (writer) {
2012 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
2013 return -1;
2014 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 }
Victor Stinner199c9a62015-10-14 09:47:23 +02002016 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002017 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
2018 if (*bytes_str == NULL)
2019 return -1;
2020 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002022 v = PyUnicode_New(sz, 'x');
2023 if (v == NULL)
2024 return -1;
2025 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00002027
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002028#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002029 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002030 if (size_a == 0) { \
2031 *--p = '0'; \
2032 } \
2033 else { \
2034 /* JRH: special case for power-of-2 bases */ \
2035 twodigits accum = 0; \
2036 int accumbits = 0; /* # of bits in accum */ \
2037 Py_ssize_t i; \
2038 for (i = 0; i < size_a; ++i) { \
2039 accum |= (twodigits)a->ob_digit[i] << accumbits; \
2040 accumbits += PyLong_SHIFT; \
2041 assert(accumbits >= bits); \
2042 do { \
2043 char cdigit; \
2044 cdigit = (char)(accum & (base - 1)); \
2045 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
2046 *--p = cdigit; \
2047 accumbits -= bits; \
2048 accum >>= bits; \
2049 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
2050 } \
2051 } \
2052 \
2053 if (alternate) { \
2054 if (base == 16) \
2055 *--p = 'x'; \
2056 else if (base == 8) \
2057 *--p = 'o'; \
2058 else /* (base == 2) */ \
2059 *--p = 'b'; \
2060 *--p = '0'; \
2061 } \
2062 if (negative) \
2063 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002064 } while (0)
2065
2066#define WRITE_UNICODE_DIGITS(TYPE) \
2067 do { \
2068 if (writer) \
2069 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
2070 else \
2071 p = (TYPE*)PyUnicode_DATA(v) + sz; \
2072 \
2073 WRITE_DIGITS(p); \
2074 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002075 if (writer) \
2076 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2077 else \
2078 assert(p == (TYPE*)PyUnicode_DATA(v)); \
2079 } while (0)
2080
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002081 if (bytes_writer) {
2082 char *p = *bytes_str + sz;
2083 WRITE_DIGITS(p);
2084 assert(p == *bytes_str);
2085 }
2086 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002087 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002088 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002089 }
2090 else if (kind == PyUnicode_2BYTE_KIND) {
2091 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002092 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002093 }
2094 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002095 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002096 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002097 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002098 }
2099#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002100#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002101
2102 if (writer) {
2103 writer->pos += sz;
2104 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002105 else if (bytes_writer) {
2106 (*bytes_str) += sz;
2107 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002108 else {
2109 assert(_PyUnicode_CheckConsistency(v, 1));
2110 *p_output = v;
2111 }
2112 return 0;
2113}
2114
2115PyObject *
2116_PyLong_Format(PyObject *obj, int base)
2117{
2118 PyObject *str;
2119 int err;
2120 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002121 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002122 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002123 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002124 if (err == -1)
2125 return NULL;
2126 return str;
2127}
2128
2129int
2130_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2131 PyObject *obj,
2132 int base, int alternate)
2133{
2134 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002135 return long_to_decimal_string_internal(obj, NULL, writer,
2136 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002137 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002138 return long_format_binary(obj, base, alternate, NULL, writer,
2139 NULL, NULL);
2140}
2141
2142char*
2143_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2144 PyObject *obj,
2145 int base, int alternate)
2146{
2147 char *str2;
2148 int res;
2149 str2 = str;
2150 if (base == 10)
2151 res = long_to_decimal_string_internal(obj, NULL, NULL,
2152 writer, &str2);
2153 else
2154 res = long_format_binary(obj, base, alternate, NULL, NULL,
2155 writer, &str2);
2156 if (res < 0)
2157 return NULL;
2158 assert(str2 != NULL);
2159 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002160}
2161
Thomas Wouters477c8d52006-05-27 19:21:47 +00002162/* Table of digit values for 8-bit string -> integer conversion.
2163 * '0' maps to 0, ..., '9' maps to 9.
2164 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2165 * All other indices map to 37.
2166 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002167 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002168 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002169unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2171 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2172 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2173 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2174 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2175 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2176 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2177 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2178 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2179 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2180 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2181 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2182 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2183 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2184 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2185 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002186};
2187
2188/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002189 * 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 +03002190 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002191 * The point to this routine is that it takes time linear in the number of
2192 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002193 *
2194 * Return values:
2195 * -1 on syntax error (exception needs to be set, *res is untouched)
2196 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002197 */
Brett Cannona721aba2016-09-09 14:57:09 -07002198static int
2199long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002200{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002201 const char *p = *str;
2202 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002203 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002204 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 int bits_per_char;
2206 Py_ssize_t n;
2207 PyLongObject *z;
2208 twodigits accum;
2209 int bits_in_accum;
2210 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2213 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002214 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002216 }
2217 /* count digits and set p to end-of-string */
2218 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2219 if (*p == '_') {
2220 if (prev == '_') {
2221 *str = p - 1;
2222 return -1;
2223 }
2224 } else {
2225 ++digits;
2226 }
2227 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002229 }
2230 if (prev == '_') {
2231 /* Trailing underscore not allowed. */
2232 *str = p - 1;
2233 return -1;
2234 }
2235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002237 /* n <- the number of Python digits needed,
2238 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2239 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 PyErr_SetString(PyExc_ValueError,
2241 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002242 *res = NULL;
2243 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002245 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002247 if (z == NULL) {
2248 *res = NULL;
2249 return 0;
2250 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002251 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 * from least to most significant in both.
2253 */
2254 accum = 0;
2255 bits_in_accum = 0;
2256 pdigit = z->ob_digit;
2257 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002258 int k;
2259 if (*p == '_') {
2260 continue;
2261 }
2262 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 assert(k >= 0 && k < base);
2264 accum |= (twodigits)k << bits_in_accum;
2265 bits_in_accum += bits_per_char;
2266 if (bits_in_accum >= PyLong_SHIFT) {
2267 *pdigit++ = (digit)(accum & PyLong_MASK);
2268 assert(pdigit - z->ob_digit <= n);
2269 accum >>= PyLong_SHIFT;
2270 bits_in_accum -= PyLong_SHIFT;
2271 assert(bits_in_accum < PyLong_SHIFT);
2272 }
2273 }
2274 if (bits_in_accum) {
2275 assert(bits_in_accum <= PyLong_SHIFT);
2276 *pdigit++ = (digit)accum;
2277 assert(pdigit - z->ob_digit <= n);
2278 }
2279 while (pdigit - z->ob_digit < n)
2280 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002281 *res = long_normalize(z);
2282 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002283}
2284
Serhiy Storchaka95949422013-08-27 19:40:23 +03002285/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002286 * ignored.
2287 *
2288 * If successful, a PyLong object will be returned and 'pend' will be pointing
2289 * to the first unused byte unless it's NULL.
2290 *
2291 * If unsuccessful, NULL will be returned.
2292 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002293PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002294PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002297 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 PyLongObject *z = NULL;
2299 PyObject *strobj;
2300 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 if ((base != 0 && base < 2) || base > 36) {
2303 PyErr_SetString(PyExc_ValueError,
2304 "int() arg 2 must be >= 2 and <= 36");
2305 return NULL;
2306 }
Brett Cannona721aba2016-09-09 14:57:09 -07002307 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002309 }
2310 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002312 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 else if (*str == '-') {
2314 ++str;
2315 sign = -1;
2316 }
2317 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002318 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002320 }
2321 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002323 }
2324 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002326 }
2327 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002329 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 else {
2331 /* "old" (C-style) octal literal, now invalid.
2332 it might still be zero though */
2333 error_if_nonzero = 1;
2334 base = 10;
2335 }
2336 }
2337 if (str[0] == '0' &&
2338 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2339 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002340 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002342 /* One underscore allowed here. */
2343 if (*str == '_') {
2344 ++str;
2345 }
2346 }
2347 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002348 /* May not start with underscores. */
2349 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002350 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002353 if ((base & (base - 1)) == 0) {
2354 int res = long_from_binary_base(&str, base, &z);
2355 if (res < 0) {
2356 /* Syntax error. */
2357 goto onError;
2358 }
2359 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002361/***
2362Binary bases can be converted in time linear in the number of digits, because
2363Python's representation base is binary. Other bases (including decimal!) use
2364the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002365
Thomas Wouters477c8d52006-05-27 19:21:47 +00002366First some math: the largest integer that can be expressed in N base-B digits
2367is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2368case number of Python digits needed to hold it is the smallest integer n s.t.
2369
2370 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2371 BASE**n >= B**N [taking logs to base BASE]
2372 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2373
2374The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002375this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002376and the result is computed into it.
2377
2378The input string is actually treated as being in base base**i (i.e., i digits
2379are processed at a time), where two more static arrays hold:
2380
2381 convwidth_base[base] = the largest integer i such that base**i <= BASE
2382 convmultmax_base[base] = base ** convwidth_base[base]
2383
2384The first of these is the largest i such that i consecutive input digits
2385must fit in a single Python digit. The second is effectively the input
2386base we're really using.
2387
2388Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2389convmultmax_base[base], the result is "simply"
2390
2391 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2392
2393where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002394
2395Error analysis: as above, the number of Python digits `n` needed is worst-
2396case
2397
2398 n >= N * log(B)/log(BASE)
2399
2400where `N` is the number of input digits in base `B`. This is computed via
2401
2402 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2403
2404below. Two numeric concerns are how much space this can waste, and whether
2405the computed result can be too small. To be concrete, assume BASE = 2**15,
2406which is the default (and it's unlikely anyone changes that).
2407
2408Waste isn't a problem: provided the first input digit isn't 0, the difference
2409between the worst-case input with N digits and the smallest input with N
2410digits is about a factor of B, but B is small compared to BASE so at most
2411one allocated Python digit can remain unused on that count. If
2412N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2413and adding 1 returns a result 1 larger than necessary. However, that can't
2414happen: whenever B is a power of 2, long_from_binary_base() is called
2415instead, and it's impossible for B**i to be an integer power of 2**15 when
2416B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2417an exact integer when B is not a power of 2, since B**i has a prime factor
2418other than 2 in that case, but (2**15)**j's only prime factor is 2).
2419
2420The computed result can be too small if the true value of N*log(B)/log(BASE)
2421is a little bit larger than an exact integer, but due to roundoff errors (in
2422computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2423yields a numeric result a little less than that integer. Unfortunately, "how
2424close can a transcendental function get to an integer over some range?"
2425questions are generally theoretically intractable. Computer analysis via
2426continued fractions is practical: expand log(B)/log(BASE) via continued
2427fractions, giving a sequence i/j of "the best" rational approximations. Then
2428j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2429we can get very close to being in trouble, but very rarely. For example,
243076573 is a denominator in one of the continued-fraction approximations to
2431log(10)/log(2**15), and indeed:
2432
2433 >>> log(10)/log(2**15)*76573
2434 16958.000000654003
2435
2436is very close to an integer. If we were working with IEEE single-precision,
2437rounding errors could kill us. Finding worst cases in IEEE double-precision
2438requires better-than-double-precision log() functions, and Tim didn't bother.
2439Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002440new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002441This should happen extremely rarely, and in fact I don't have a test case
2442that triggers it(!). Instead the code was tested by artificially allocating
2443just 1 digit at the start, so that the copying code was exercised for every
2444digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002445***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002446 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002448 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 int i;
2450 int convwidth;
2451 twodigits convmultmax, convmult;
2452 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002453 const char *scan, *lastdigit;
2454 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 static double log_base_BASE[37] = {0.0e0,};
2457 static int convwidth_base[37] = {0,};
2458 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 if (log_base_BASE[base] == 0.0) {
2461 twodigits convmax = base;
2462 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002463
Mark Dickinson22b20182010-05-10 21:27:53 +00002464 log_base_BASE[base] = (log((double)base) /
2465 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 for (;;) {
2467 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002468 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002470 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 convmax = next;
2472 ++i;
2473 }
2474 convmultmax_base[base] = convmax;
2475 assert(i > 0);
2476 convwidth_base[base] = i;
2477 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 /* Find length of the string of numeric characters. */
2480 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002481 lastdigit = str;
2482
2483 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2484 if (*scan == '_') {
2485 if (prev == '_') {
2486 /* Only one underscore allowed. */
2487 str = lastdigit + 1;
2488 goto onError;
2489 }
2490 }
2491 else {
2492 ++digits;
2493 lastdigit = scan;
2494 }
2495 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002497 }
2498 if (prev == '_') {
2499 /* Trailing underscore not allowed. */
2500 /* Set error pointer to first underscore. */
2501 str = lastdigit + 1;
2502 goto onError;
2503 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002504
Serhiy Storchaka95949422013-08-27 19:40:23 +03002505 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 * integer with this base and length. Note that there's no
2507 * need to initialize z->ob_digit -- no slot is read up before
2508 * being stored into.
2509 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002510 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2511 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002512 /* The same exception as in _PyLong_New(). */
2513 PyErr_SetString(PyExc_OverflowError,
2514 "too many digits in integer");
2515 return NULL;
2516 }
2517 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 /* Uncomment next line to test exceedingly rare copy code */
2519 /* size_z = 1; */
2520 assert(size_z > 0);
2521 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002522 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002524 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 /* `convwidth` consecutive input digits are treated as a single
2528 * digit in base `convmultmax`.
2529 */
2530 convwidth = convwidth_base[base];
2531 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 /* Work ;-) */
2534 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002535 if (*str == '_') {
2536 str++;
2537 continue;
2538 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 /* grab up to convwidth digits from the input string */
2540 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002541 for (i = 1; i < convwidth && str != scan; ++str) {
2542 if (*str == '_') {
2543 continue;
2544 }
2545 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002547 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 assert(c < PyLong_BASE);
2549 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 convmult = convmultmax;
2552 /* Calculate the shift only if we couldn't get
2553 * convwidth digits.
2554 */
2555 if (i != convwidth) {
2556 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002557 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002559 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 /* Multiply z by convmult, and add c. */
2563 pz = z->ob_digit;
2564 pzstop = pz + Py_SIZE(z);
2565 for (; pz < pzstop; ++pz) {
2566 c += (twodigits)*pz * convmult;
2567 *pz = (digit)(c & PyLong_MASK);
2568 c >>= PyLong_SHIFT;
2569 }
2570 /* carry off the current end? */
2571 if (c) {
2572 assert(c < PyLong_BASE);
2573 if (Py_SIZE(z) < size_z) {
2574 *pz = (digit)c;
2575 ++Py_SIZE(z);
2576 }
2577 else {
2578 PyLongObject *tmp;
2579 /* Extremely rare. Get more space. */
2580 assert(Py_SIZE(z) == size_z);
2581 tmp = _PyLong_New(size_z + 1);
2582 if (tmp == NULL) {
2583 Py_DECREF(z);
2584 return NULL;
2585 }
2586 memcpy(tmp->ob_digit,
2587 z->ob_digit,
2588 sizeof(digit) * size_z);
2589 Py_DECREF(z);
2590 z = tmp;
2591 z->ob_digit[size_z] = (digit)c;
2592 ++size_z;
2593 }
2594 }
2595 }
2596 }
Brett Cannona721aba2016-09-09 14:57:09 -07002597 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 if (error_if_nonzero) {
2601 /* reset the base to 0, else the exception message
2602 doesn't make too much sense */
2603 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002604 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002606 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 /* there might still be other problems, therefore base
2608 remains zero here for the same reason */
2609 }
Brett Cannona721aba2016-09-09 14:57:09 -07002610 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002612 }
2613 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002615 }
2616 while (*str && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002618 }
2619 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002621 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002623 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002624 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002625 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002626 }
2627 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002628 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002629 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002630 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002631
Mark Dickinson22b20182010-05-10 21:27:53 +00002632 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002633 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002634 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 Py_XDECREF(z);
2637 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2638 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002639 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002641 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002643 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 base, strobj);
2645 Py_DECREF(strobj);
2646 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002647}
2648
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002649/* Since PyLong_FromString doesn't have a length parameter,
2650 * check here for possible NULs in the string.
2651 *
2652 * Reports an invalid literal as a bytes object.
2653 */
2654PyObject *
2655_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2656{
2657 PyObject *result, *strobj;
2658 char *end = NULL;
2659
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002660 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002661 if (end == NULL || (result != NULL && end == s + len))
2662 return result;
2663 Py_XDECREF(result);
2664 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2665 if (strobj != NULL) {
2666 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002667 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002668 base, strobj);
2669 Py_DECREF(strobj);
2670 }
2671 return NULL;
2672}
2673
Guido van Rossum9e896b32000-04-05 20:11:21 +00002674PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002675PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002676{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002677 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002678 if (unicode == NULL)
2679 return NULL;
2680 v = PyLong_FromUnicodeObject(unicode, base);
2681 Py_DECREF(unicode);
2682 return v;
2683}
2684
2685PyObject *
2686PyLong_FromUnicodeObject(PyObject *u, int base)
2687{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002688 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002689 const char *buffer;
2690 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002691 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002692
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002693 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002694 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002696 assert(PyUnicode_IS_ASCII(asciidig));
2697 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002698 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002699 assert(buffer != NULL);
2700
2701 result = PyLong_FromString(buffer, &end, base);
2702 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002703 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002704 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002706 Py_DECREF(asciidig);
2707 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002708 PyErr_Format(PyExc_ValueError,
2709 "invalid literal for int() with base %d: %.200R",
2710 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002711 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002712}
2713
Tim Peters9f688bf2000-07-07 15:53:28 +00002714/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002715static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002717static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002718
Serhiy Storchaka95949422013-08-27 19:40:23 +03002719/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002720
Guido van Rossume32e0141992-01-19 16:31:05 +00002721static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002722long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002724{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002725 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 if (size_b == 0) {
2729 PyErr_SetString(PyExc_ZeroDivisionError,
2730 "integer division or modulo by zero");
2731 return -1;
2732 }
2733 if (size_a < size_b ||
2734 (size_a == size_b &&
2735 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2736 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002737 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002738 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002739 return -1;
2740 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002741 Py_INCREF(_PyLong_Zero);
2742 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 return 0;
2744 }
2745 if (size_b == 1) {
2746 digit rem = 0;
2747 z = divrem1(a, b->ob_digit[0], &rem);
2748 if (z == NULL)
2749 return -1;
2750 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2751 if (*prem == NULL) {
2752 Py_DECREF(z);
2753 return -1;
2754 }
2755 }
2756 else {
2757 z = x_divrem(a, b, prem);
2758 if (z == NULL)
2759 return -1;
2760 }
2761 /* Set the signs.
2762 The quotient z has the sign of a*b;
2763 the remainder r has the sign of a,
2764 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002765 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2766 _PyLong_Negate(&z);
2767 if (z == NULL) {
2768 Py_CLEAR(*prem);
2769 return -1;
2770 }
2771 }
2772 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2773 _PyLong_Negate(prem);
2774 if (*prem == NULL) {
2775 Py_DECREF(z);
2776 Py_CLEAR(*prem);
2777 return -1;
2778 }
2779 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 *pdiv = maybe_small_long(z);
2781 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002782}
2783
Serhiy Storchaka95949422013-08-27 19:40:23 +03002784/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002785 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002786
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002787static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002788x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 PyLongObject *v, *w, *a;
2791 Py_ssize_t i, k, size_v, size_w;
2792 int d;
2793 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2794 twodigits vv;
2795 sdigit zhi;
2796 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2799 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2800 handle the special case when the initial estimate q for a quotient
2801 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2802 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002805 size_v = Py_ABS(Py_SIZE(v1));
2806 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2808 v = _PyLong_New(size_v+1);
2809 if (v == NULL) {
2810 *prem = NULL;
2811 return NULL;
2812 }
2813 w = _PyLong_New(size_w);
2814 if (w == NULL) {
2815 Py_DECREF(v);
2816 *prem = NULL;
2817 return NULL;
2818 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2821 shift v1 left by the same amount. Results go into w and v. */
2822 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2823 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2824 assert(carry == 0);
2825 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2826 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2827 v->ob_digit[size_v] = carry;
2828 size_v++;
2829 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2832 at most (and usually exactly) k = size_v - size_w digits. */
2833 k = size_v - size_w;
2834 assert(k >= 0);
2835 a = _PyLong_New(k);
2836 if (a == NULL) {
2837 Py_DECREF(w);
2838 Py_DECREF(v);
2839 *prem = NULL;
2840 return NULL;
2841 }
2842 v0 = v->ob_digit;
2843 w0 = w->ob_digit;
2844 wm1 = w0[size_w-1];
2845 wm2 = w0[size_w-2];
2846 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2847 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2848 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002851 Py_DECREF(a);
2852 Py_DECREF(w);
2853 Py_DECREF(v);
2854 *prem = NULL;
2855 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002856 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 /* estimate quotient digit q; may overestimate by 1 (rare) */
2859 vtop = vk[size_w];
2860 assert(vtop <= wm1);
2861 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2862 q = (digit)(vv / wm1);
2863 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2864 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2865 | vk[size_w-2])) {
2866 --q;
2867 r += wm1;
2868 if (r >= PyLong_BASE)
2869 break;
2870 }
2871 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2874 zhi = 0;
2875 for (i = 0; i < size_w; ++i) {
2876 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2877 -PyLong_BASE * q <= z < PyLong_BASE */
2878 z = (sdigit)vk[i] + zhi -
2879 (stwodigits)q * (stwodigits)w0[i];
2880 vk[i] = (digit)z & PyLong_MASK;
2881 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002882 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 /* add w back if q was too large (this branch taken rarely) */
2886 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2887 if ((sdigit)vtop + zhi < 0) {
2888 carry = 0;
2889 for (i = 0; i < size_w; ++i) {
2890 carry += vk[i] + w0[i];
2891 vk[i] = carry & PyLong_MASK;
2892 carry >>= PyLong_SHIFT;
2893 }
2894 --q;
2895 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 /* store quotient digit */
2898 assert(q < PyLong_BASE);
2899 *--ak = q;
2900 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 /* unshift remainder; we reuse w to store the result */
2903 carry = v_rshift(w0, v0, size_w, d);
2904 assert(carry==0);
2905 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 *prem = long_normalize(w);
2908 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002909}
2910
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002911/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2912 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2913 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2914 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2915 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2916 -1.0. */
2917
2918/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2919#if DBL_MANT_DIG == 53
2920#define EXP2_DBL_MANT_DIG 9007199254740992.0
2921#else
2922#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2923#endif
2924
2925double
2926_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2929 /* See below for why x_digits is always large enough. */
2930 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2931 double dx;
2932 /* Correction term for round-half-to-even rounding. For a digit x,
2933 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2934 multiple of 4, rounding ties to a multiple of 8. */
2935 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002936
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002937 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 if (a_size == 0) {
2939 /* Special case for 0: significand 0.0, exponent 0. */
2940 *e = 0;
2941 return 0.0;
2942 }
2943 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2944 /* The following is an overflow-free version of the check
2945 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2946 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2947 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2948 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002949 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2953 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 Number of digits needed for result: write // for floor division.
2956 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2965 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2968 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2969 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 in both cases.
2976 */
2977 if (a_bits <= DBL_MANT_DIG + 2) {
2978 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2979 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2980 x_size = 0;
2981 while (x_size < shift_digits)
2982 x_digits[x_size++] = 0;
2983 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2984 (int)shift_bits);
2985 x_size += a_size;
2986 x_digits[x_size++] = rem;
2987 }
2988 else {
2989 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2990 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2991 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2992 a_size - shift_digits, (int)shift_bits);
2993 x_size = a_size - shift_digits;
2994 /* For correct rounding below, we need the least significant
2995 bit of x to be 'sticky' for this shift: if any of the bits
2996 shifted out was nonzero, we set the least significant bit
2997 of x. */
2998 if (rem)
2999 x_digits[0] |= 1;
3000 else
3001 while (shift_digits > 0)
3002 if (a->ob_digit[--shift_digits]) {
3003 x_digits[0] |= 1;
3004 break;
3005 }
3006 }
Victor Stinner63941882011-09-29 00:42:28 +02003007 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 /* Round, and convert to double. */
3010 x_digits[0] += half_even_correction[x_digits[0] & 7];
3011 dx = x_digits[--x_size];
3012 while (x_size > 0)
3013 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 /* Rescale; make correction if result is 1.0. */
3016 dx /= 4.0 * EXP2_DBL_MANT_DIG;
3017 if (dx == 1.0) {
3018 if (a_bits == PY_SSIZE_T_MAX)
3019 goto overflow;
3020 dx = 0.5;
3021 a_bits += 1;
3022 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 *e = a_bits;
3025 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003026
3027 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 /* exponent > PY_SSIZE_T_MAX */
3029 PyErr_SetString(PyExc_OverflowError,
3030 "huge integer: number of bits overflows a Py_ssize_t");
3031 *e = 0;
3032 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003033}
3034
Serhiy Storchaka95949422013-08-27 19:40:23 +03003035/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003036 using the round-half-to-even rule in the case of a tie. */
3037
3038double
3039PyLong_AsDouble(PyObject *v)
3040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 Py_ssize_t exponent;
3042 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003043
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02003044 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 PyErr_BadInternalCall();
3046 return -1.0;
3047 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02003048 if (!PyLong_Check(v)) {
3049 PyErr_SetString(PyExc_TypeError, "an integer is required");
3050 return -1.0;
3051 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05003052 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05003053 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01003054 to double. This improves performance of FP/long operations
3055 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05003056 */
3057 return (double)MEDIUM_VALUE((PyLongObject *)v);
3058 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
3060 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
3061 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01003062 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 return -1.0;
3064 }
3065 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003066}
3067
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003068/* Methods */
3069
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003070static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003071long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 if (Py_SIZE(a) != Py_SIZE(b)) {
3076 sign = Py_SIZE(a) - Py_SIZE(b);
3077 }
3078 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003079 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3081 ;
3082 if (i < 0)
3083 sign = 0;
3084 else {
3085 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
3086 if (Py_SIZE(a) < 0)
3087 sign = -sign;
3088 }
3089 }
3090 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003091}
3092
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003093static PyObject *
3094long_richcompare(PyObject *self, PyObject *other, int op)
3095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 CHECK_BINOP(self, other);
3098 if (self == other)
3099 result = 0;
3100 else
3101 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003102 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003103}
3104
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003105static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003106long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003107{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003108 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 Py_ssize_t i;
3110 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 i = Py_SIZE(v);
3113 switch(i) {
3114 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3115 case 0: return 0;
3116 case 1: return v->ob_digit[0];
3117 }
3118 sign = 1;
3119 x = 0;
3120 if (i < 0) {
3121 sign = -1;
3122 i = -(i);
3123 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003125 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3126 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3127 _PyHASH_MODULUS.
3128
3129 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3130 amounts to a rotation of the bits of x. To see this, write
3131
3132 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3133
3134 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3135 PyLong_SHIFT bits of x (those that are shifted out of the
3136 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3137 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3138 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3139 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3140 congruent to y modulo _PyHASH_MODULUS. So
3141
3142 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3143
3144 The right-hand side is just the result of rotating the
3145 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3146 not all _PyHASH_BITS bits of x are 1s, the same is true
3147 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3148 the reduction of x*2**PyLong_SHIFT modulo
3149 _PyHASH_MODULUS. */
3150 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3151 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003153 if (x >= _PyHASH_MODULUS)
3154 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 }
3156 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003157 if (x == (Py_uhash_t)-1)
3158 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003159 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003160}
3161
3162
Serhiy Storchaka95949422013-08-27 19:40:23 +03003163/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003164
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003165static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003166x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003167{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003168 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 PyLongObject *z;
3170 Py_ssize_t i;
3171 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 /* Ensure a is the larger of the two: */
3174 if (size_a < size_b) {
3175 { PyLongObject *temp = a; a = b; b = temp; }
3176 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003177 size_a = size_b;
3178 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 }
3180 z = _PyLong_New(size_a+1);
3181 if (z == NULL)
3182 return NULL;
3183 for (i = 0; i < size_b; ++i) {
3184 carry += a->ob_digit[i] + b->ob_digit[i];
3185 z->ob_digit[i] = carry & PyLong_MASK;
3186 carry >>= PyLong_SHIFT;
3187 }
3188 for (; i < size_a; ++i) {
3189 carry += a->ob_digit[i];
3190 z->ob_digit[i] = carry & PyLong_MASK;
3191 carry >>= PyLong_SHIFT;
3192 }
3193 z->ob_digit[i] = carry;
3194 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003195}
3196
3197/* Subtract the absolute values of two integers. */
3198
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003199static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003200x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003201{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003202 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 PyLongObject *z;
3204 Py_ssize_t i;
3205 int sign = 1;
3206 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 /* Ensure a is the larger of the two: */
3209 if (size_a < size_b) {
3210 sign = -1;
3211 { PyLongObject *temp = a; a = b; b = temp; }
3212 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003213 size_a = size_b;
3214 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 }
3216 else if (size_a == size_b) {
3217 /* Find highest digit where a and b differ: */
3218 i = size_a;
3219 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3220 ;
3221 if (i < 0)
3222 return (PyLongObject *)PyLong_FromLong(0);
3223 if (a->ob_digit[i] < b->ob_digit[i]) {
3224 sign = -1;
3225 { PyLongObject *temp = a; a = b; b = temp; }
3226 }
3227 size_a = size_b = i+1;
3228 }
3229 z = _PyLong_New(size_a);
3230 if (z == NULL)
3231 return NULL;
3232 for (i = 0; i < size_b; ++i) {
3233 /* The following assumes unsigned arithmetic
3234 works module 2**N for some N>PyLong_SHIFT. */
3235 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3236 z->ob_digit[i] = borrow & PyLong_MASK;
3237 borrow >>= PyLong_SHIFT;
3238 borrow &= 1; /* Keep only one sign bit */
3239 }
3240 for (; i < size_a; ++i) {
3241 borrow = a->ob_digit[i] - borrow;
3242 z->ob_digit[i] = borrow & PyLong_MASK;
3243 borrow >>= PyLong_SHIFT;
3244 borrow &= 1; /* Keep only one sign bit */
3245 }
3246 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003247 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003248 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003249 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003251}
3252
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003253static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003254long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003259
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003260 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003261 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 }
3263 if (Py_SIZE(a) < 0) {
3264 if (Py_SIZE(b) < 0) {
3265 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003266 if (z != NULL) {
3267 /* x_add received at least one multiple-digit int,
3268 and thus z must be a multiple-digit int.
3269 That also means z is not an element of
3270 small_ints, so negating it in-place is safe. */
3271 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003273 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 }
3275 else
3276 z = x_sub(b, a);
3277 }
3278 else {
3279 if (Py_SIZE(b) < 0)
3280 z = x_sub(a, b);
3281 else
3282 z = x_add(a, b);
3283 }
3284 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003285}
3286
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003287static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003288long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003293
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003294 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003295 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 }
3297 if (Py_SIZE(a) < 0) {
3298 if (Py_SIZE(b) < 0)
3299 z = x_sub(a, b);
3300 else
3301 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003302 if (z != NULL) {
3303 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003305 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 }
3307 else {
3308 if (Py_SIZE(b) < 0)
3309 z = x_add(a, b);
3310 else
3311 z = x_sub(a, b);
3312 }
3313 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003314}
3315
Tim Peters5af4e6c2002-08-12 02:31:19 +00003316/* Grade school multiplication, ignoring the signs.
3317 * Returns the absolute value of the product, or NULL if error.
3318 */
3319static PyLongObject *
3320x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003323 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3324 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 z = _PyLong_New(size_a + size_b);
3328 if (z == NULL)
3329 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3332 if (a == b) {
3333 /* Efficient squaring per HAC, Algorithm 14.16:
3334 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3335 * Gives slightly less than a 2x speedup when a == b,
3336 * via exploiting that each entry in the multiplication
3337 * pyramid appears twice (except for the size_a squares).
3338 */
3339 for (i = 0; i < size_a; ++i) {
3340 twodigits carry;
3341 twodigits f = a->ob_digit[i];
3342 digit *pz = z->ob_digit + (i << 1);
3343 digit *pa = a->ob_digit + i + 1;
3344 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003347 Py_DECREF(z);
3348 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003349 });
Tim Peters0973b992004-08-29 22:16:50 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 carry = *pz + f * f;
3352 *pz++ = (digit)(carry & PyLong_MASK);
3353 carry >>= PyLong_SHIFT;
3354 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 /* Now f is added in twice in each column of the
3357 * pyramid it appears. Same as adding f<<1 once.
3358 */
3359 f <<= 1;
3360 while (pa < paend) {
3361 carry += *pz + *pa++ * f;
3362 *pz++ = (digit)(carry & PyLong_MASK);
3363 carry >>= PyLong_SHIFT;
3364 assert(carry <= (PyLong_MASK << 1));
3365 }
3366 if (carry) {
3367 carry += *pz;
3368 *pz++ = (digit)(carry & PyLong_MASK);
3369 carry >>= PyLong_SHIFT;
3370 }
3371 if (carry)
3372 *pz += (digit)(carry & PyLong_MASK);
3373 assert((carry >> PyLong_SHIFT) == 0);
3374 }
3375 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003376 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 for (i = 0; i < size_a; ++i) {
3378 twodigits carry = 0;
3379 twodigits f = a->ob_digit[i];
3380 digit *pz = z->ob_digit + i;
3381 digit *pb = b->ob_digit;
3382 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003385 Py_DECREF(z);
3386 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003387 });
Tim Peters0973b992004-08-29 22:16:50 +00003388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 while (pb < pbend) {
3390 carry += *pz + *pb++ * f;
3391 *pz++ = (digit)(carry & PyLong_MASK);
3392 carry >>= PyLong_SHIFT;
3393 assert(carry <= PyLong_MASK);
3394 }
3395 if (carry)
3396 *pz += (digit)(carry & PyLong_MASK);
3397 assert((carry >> PyLong_SHIFT) == 0);
3398 }
3399 }
3400 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003401}
3402
3403/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003404 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003405 split, and sets low and high such that abs(n) == (high << size) + low,
3406 viewing the shift as being by digits. The sign bit is ignored, and
3407 the return values are >= 0.
3408 Returns 0 on success, -1 on failure.
3409*/
3410static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003411kmul_split(PyLongObject *n,
3412 Py_ssize_t size,
3413 PyLongObject **high,
3414 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 PyLongObject *hi, *lo;
3417 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003418 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003419
Victor Stinner640c35c2013-06-04 23:14:37 +02003420 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 if ((hi = _PyLong_New(size_hi)) == NULL)
3424 return -1;
3425 if ((lo = _PyLong_New(size_lo)) == NULL) {
3426 Py_DECREF(hi);
3427 return -1;
3428 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3431 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 *high = long_normalize(hi);
3434 *low = long_normalize(lo);
3435 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003436}
3437
Tim Peters60004642002-08-12 22:01:34 +00003438static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3439
Tim Peters5af4e6c2002-08-12 02:31:19 +00003440/* Karatsuba multiplication. Ignores the input signs, and returns the
3441 * absolute value of the product (or NULL if error).
3442 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3443 */
3444static PyLongObject *
3445k_mul(PyLongObject *a, PyLongObject *b)
3446{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003447 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3448 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 PyLongObject *ah = NULL;
3450 PyLongObject *al = NULL;
3451 PyLongObject *bh = NULL;
3452 PyLongObject *bl = NULL;
3453 PyLongObject *ret = NULL;
3454 PyLongObject *t1, *t2, *t3;
3455 Py_ssize_t shift; /* the number of digits we split off */
3456 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3459 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3460 * Then the original product is
3461 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3462 * By picking X to be a power of 2, "*X" is just shifting, and it's
3463 * been reduced to 3 multiplies on numbers half the size.
3464 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 /* We want to split based on the larger number; fiddle so that b
3467 * is largest.
3468 */
3469 if (asize > bsize) {
3470 t1 = a;
3471 a = b;
3472 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 i = asize;
3475 asize = bsize;
3476 bsize = i;
3477 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 /* Use gradeschool math when either number is too small. */
3480 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3481 if (asize <= i) {
3482 if (asize == 0)
3483 return (PyLongObject *)PyLong_FromLong(0);
3484 else
3485 return x_mul(a, b);
3486 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 /* If a is small compared to b, splitting on b gives a degenerate
3489 * case with ah==0, and Karatsuba may be (even much) less efficient
3490 * than "grade school" then. However, we can still win, by viewing
3491 * b as a string of "big digits", each of width a->ob_size. That
3492 * leads to a sequence of balanced calls to k_mul.
3493 */
3494 if (2 * asize <= bsize)
3495 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 /* Split a & b into hi & lo pieces. */
3498 shift = bsize >> 1;
3499 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3500 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 if (a == b) {
3503 bh = ah;
3504 bl = al;
3505 Py_INCREF(bh);
3506 Py_INCREF(bl);
3507 }
3508 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 /* The plan:
3511 * 1. Allocate result space (asize + bsize digits: that's always
3512 * enough).
3513 * 2. Compute ah*bh, and copy into result at 2*shift.
3514 * 3. Compute al*bl, and copy into result at 0. Note that this
3515 * can't overlap with #2.
3516 * 4. Subtract al*bl from the result, starting at shift. This may
3517 * underflow (borrow out of the high digit), but we don't care:
3518 * we're effectively doing unsigned arithmetic mod
3519 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3520 * borrows and carries out of the high digit can be ignored.
3521 * 5. Subtract ah*bh from the result, starting at shift.
3522 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3523 * at shift.
3524 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 /* 1. Allocate result space. */
3527 ret = _PyLong_New(asize + bsize);
3528 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003529#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 /* Fill with trash, to catch reference to uninitialized digits. */
3531 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003532#endif
Tim Peters44121a62002-08-12 06:17:58 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3535 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3536 assert(Py_SIZE(t1) >= 0);
3537 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3538 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3539 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 /* Zero-out the digits higher than the ah*bh copy. */
3542 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3543 if (i)
3544 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3545 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 /* 3. t2 <- al*bl, and copy into the low digits. */
3548 if ((t2 = k_mul(al, bl)) == NULL) {
3549 Py_DECREF(t1);
3550 goto fail;
3551 }
3552 assert(Py_SIZE(t2) >= 0);
3553 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3554 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 /* Zero out remaining digits. */
3557 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3558 if (i)
3559 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3562 * because it's fresher in cache.
3563 */
3564 i = Py_SIZE(ret) - shift; /* # digits after shift */
3565 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3566 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3569 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3572 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3573 Py_DECREF(ah);
3574 Py_DECREF(al);
3575 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 if (a == b) {
3578 t2 = t1;
3579 Py_INCREF(t2);
3580 }
3581 else if ((t2 = x_add(bh, bl)) == NULL) {
3582 Py_DECREF(t1);
3583 goto fail;
3584 }
3585 Py_DECREF(bh);
3586 Py_DECREF(bl);
3587 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 t3 = k_mul(t1, t2);
3590 Py_DECREF(t1);
3591 Py_DECREF(t2);
3592 if (t3 == NULL) goto fail;
3593 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 /* Add t3. It's not obvious why we can't run out of room here.
3596 * See the (*) comment after this function.
3597 */
3598 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3599 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003602
Mark Dickinson22b20182010-05-10 21:27:53 +00003603 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 Py_XDECREF(ret);
3605 Py_XDECREF(ah);
3606 Py_XDECREF(al);
3607 Py_XDECREF(bh);
3608 Py_XDECREF(bl);
3609 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003610}
3611
Tim Petersd6974a52002-08-13 20:37:51 +00003612/* (*) Why adding t3 can't "run out of room" above.
3613
Tim Petersab86c2b2002-08-15 20:06:00 +00003614Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3615to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003616
Tim Petersab86c2b2002-08-15 20:06:00 +000036171. For any integer i, i = c(i/2) + f(i/2). In particular,
3618 bsize = c(bsize/2) + f(bsize/2).
36192. shift = f(bsize/2)
36203. asize <= bsize
36214. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3622 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003623
Tim Petersab86c2b2002-08-15 20:06:00 +00003624We allocated asize + bsize result digits, and add t3 into them at an offset
3625of shift. This leaves asize+bsize-shift allocated digit positions for t3
3626to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3627asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003628
Tim Petersab86c2b2002-08-15 20:06:00 +00003629bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3630at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003631
Tim Petersab86c2b2002-08-15 20:06:00 +00003632If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3633digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3634most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003635
Tim Petersab86c2b2002-08-15 20:06:00 +00003636The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003637
Tim Petersab86c2b2002-08-15 20:06:00 +00003638 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003639
Tim Petersab86c2b2002-08-15 20:06:00 +00003640and we have asize + c(bsize/2) available digit positions. We need to show
3641this is always enough. An instance of c(bsize/2) cancels out in both, so
3642the question reduces to whether asize digits is enough to hold
3643(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3644then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3645asize 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 +00003646digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003647asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003648c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3649is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3650bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003651
Tim Peters48d52c02002-08-14 17:07:32 +00003652Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3653clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3654ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003655*/
3656
Tim Peters60004642002-08-12 22:01:34 +00003657/* b has at least twice the digits of a, and a is big enough that Karatsuba
3658 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3659 * of slices, each with a->ob_size digits, and multiply the slices by a,
3660 * one at a time. This gives k_mul balanced inputs to work with, and is
3661 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003662 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003663 * single-width slice overlap between successive partial sums).
3664 */
3665static PyLongObject *
3666k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3667{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003668 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3669 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 Py_ssize_t nbdone; /* # of b digits already multiplied */
3671 PyLongObject *ret;
3672 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 assert(asize > KARATSUBA_CUTOFF);
3675 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 /* Allocate result space, and zero it out. */
3678 ret = _PyLong_New(asize + bsize);
3679 if (ret == NULL)
3680 return NULL;
3681 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 /* Successive slices of b are copied into bslice. */
3684 bslice = _PyLong_New(asize);
3685 if (bslice == NULL)
3686 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 nbdone = 0;
3689 while (bsize > 0) {
3690 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003691 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 /* Multiply the next slice of b by a. */
3694 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3695 nbtouse * sizeof(digit));
3696 Py_SIZE(bslice) = nbtouse;
3697 product = k_mul(a, bslice);
3698 if (product == NULL)
3699 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 /* Add into result. */
3702 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3703 product->ob_digit, Py_SIZE(product));
3704 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 bsize -= nbtouse;
3707 nbdone += nbtouse;
3708 }
Tim Peters60004642002-08-12 22:01:34 +00003709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 Py_DECREF(bslice);
3711 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003712
Mark Dickinson22b20182010-05-10 21:27:53 +00003713 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 Py_DECREF(ret);
3715 Py_XDECREF(bslice);
3716 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003717}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003718
3719static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003720long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003727 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003729 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 z = k_mul(a, b);
3733 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003734 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3735 _PyLong_Negate(&z);
3736 if (z == NULL)
3737 return NULL;
3738 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003740}
3741
Yury Selivanove0b23092016-02-11 10:26:27 -05003742/* Fast modulo division for single-digit longs. */
3743static PyObject *
3744fast_mod(PyLongObject *a, PyLongObject *b)
3745{
3746 sdigit left = a->ob_digit[0];
3747 sdigit right = b->ob_digit[0];
3748 sdigit mod;
3749
3750 assert(Py_ABS(Py_SIZE(a)) == 1);
3751 assert(Py_ABS(Py_SIZE(b)) == 1);
3752
3753 if (Py_SIZE(a) == Py_SIZE(b)) {
3754 /* 'a' and 'b' have the same sign. */
3755 mod = left % right;
3756 }
3757 else {
3758 /* Either 'a' or 'b' is negative. */
3759 mod = right - 1 - (left - 1) % right;
3760 }
3761
Victor Stinnerf963c132016-03-23 18:36:54 +01003762 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003763}
3764
3765/* Fast floor division for single-digit longs. */
3766static PyObject *
3767fast_floor_div(PyLongObject *a, PyLongObject *b)
3768{
3769 sdigit left = a->ob_digit[0];
3770 sdigit right = b->ob_digit[0];
3771 sdigit div;
3772
3773 assert(Py_ABS(Py_SIZE(a)) == 1);
3774 assert(Py_ABS(Py_SIZE(b)) == 1);
3775
3776 if (Py_SIZE(a) == Py_SIZE(b)) {
3777 /* 'a' and 'b' have the same sign. */
3778 div = left / right;
3779 }
3780 else {
3781 /* Either 'a' or 'b' is negative. */
3782 div = -1 - (left - 1) / right;
3783 }
3784
3785 return PyLong_FromLong(div);
3786}
3787
Guido van Rossume32e0141992-01-19 16:31:05 +00003788/* The / and % operators are now defined in terms of divmod().
3789 The expression a mod b has the value a - b*floor(a/b).
3790 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003791 |a| by |b|, with the sign of a. This is also expressed
3792 as a - b*trunc(a/b), if trunc truncates towards zero.
3793 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 a b a rem b a mod b
3795 13 10 3 3
3796 -13 10 -3 7
3797 13 -10 3 -7
3798 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003799 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003800 have different signs. We then subtract one from the 'div'
3801 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003802
Tim Peters47e52ee2004-08-30 02:44:38 +00003803/* Compute
3804 * *pdiv, *pmod = divmod(v, w)
3805 * NULL can be passed for pdiv or pmod, in which case that part of
3806 * the result is simply thrown away. The caller owns a reference to
3807 * each of these it requests (does not pass NULL for).
3808 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003809static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003810l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003814
Yury Selivanove0b23092016-02-11 10:26:27 -05003815 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3816 /* Fast path for single-digit longs */
3817 div = NULL;
3818 if (pdiv != NULL) {
3819 div = (PyLongObject *)fast_floor_div(v, w);
3820 if (div == NULL) {
3821 return -1;
3822 }
3823 }
3824 if (pmod != NULL) {
3825 mod = (PyLongObject *)fast_mod(v, w);
3826 if (mod == NULL) {
3827 Py_XDECREF(div);
3828 return -1;
3829 }
3830 *pmod = mod;
3831 }
3832 if (pdiv != NULL) {
3833 /* We only want to set `*pdiv` when `*pmod` is
3834 set successfully. */
3835 *pdiv = div;
3836 }
3837 return 0;
3838 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 if (long_divrem(v, w, &div, &mod) < 0)
3840 return -1;
3841 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3842 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3843 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 temp = (PyLongObject *) long_add(mod, w);
3845 Py_DECREF(mod);
3846 mod = temp;
3847 if (mod == NULL) {
3848 Py_DECREF(div);
3849 return -1;
3850 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003851 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3852 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 Py_DECREF(mod);
3854 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 return -1;
3856 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 Py_DECREF(div);
3858 div = temp;
3859 }
3860 if (pdiv != NULL)
3861 *pdiv = div;
3862 else
3863 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 if (pmod != NULL)
3866 *pmod = mod;
3867 else
3868 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003871}
3872
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003873static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003874long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003879
3880 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3881 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3882 }
3883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3885 div = NULL;
3886 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003887}
3888
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003889/* PyLong/PyLong -> float, with correctly rounded result. */
3890
3891#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3892#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3893
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003894static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003895long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 PyLongObject *a, *b, *x;
3898 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3899 digit mask, low;
3900 int inexact, negate, a_is_small, b_is_small;
3901 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 CHECK_BINOP(v, w);
3904 a = (PyLongObject *)v;
3905 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 /*
3908 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3911 1. choose a suitable integer 'shift'
3912 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3913 3. adjust x for correct rounding
3914 4. convert x to a double dx with the same value
3915 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3920 returns either 0.0 or -0.0, depending on the sign of b. For a and
3921 b both nonzero, ignore signs of a and b, and add the sign back in
3922 at the end. Now write a_bits and b_bits for the bit lengths of a
3923 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3924 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3929 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3930 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3931 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 1. The integer 'shift' is chosen so that x has the right number of
3936 bits for a double, plus two or three extra bits that will be used
3937 in the rounding decisions. Writing a_bits and b_bits for the
3938 number of significant bits in a and b respectively, a
3939 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 This is fine in the usual case, but if a/b is smaller than the
3944 smallest normal float then it can lead to double rounding on an
3945 IEEE 754 platform, giving incorrectly rounded results. So we
3946 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 2. The quantity x is computed by first shifting a (left -shift bits
3951 if shift <= 0, right shift bits if shift > 0) and then dividing by
3952 b. For both the shift and the division, we keep track of whether
3953 the result is inexact, in a flag 'inexact'; this information is
3954 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 With the choice of shift above, together with our assumption that
3957 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3958 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3961 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 For float representability, we need x/2**extra_bits <
3966 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3967 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 To round, we just modify the bottom digit of x in-place; this can
3972 end up giving a digit with value > PyLONG_MASK, but that's not a
3973 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 With the original choices for shift above, extra_bits will always
3976 be 2 or 3. Then rounding under the round-half-to-even rule, we
3977 round up iff the most significant of the extra bits is 1, and
3978 either: (a) the computation of x in step 2 had an inexact result,
3979 or (b) at least one other of the extra bits is 1, or (c) the least
3980 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 4. Conversion to a double is straightforward; all floating-point
3983 operations involved in the conversion are exact, so there's no
3984 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3987 The result will always be exactly representable as a double, except
3988 in the case that it overflows. To avoid dependence on the exact
3989 behaviour of ldexp on overflow, we check for overflow before
3990 applying ldexp. The result of ldexp is adjusted for sign before
3991 returning.
3992 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003995 a_size = Py_ABS(Py_SIZE(a));
3996 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3998 if (b_size == 0) {
3999 PyErr_SetString(PyExc_ZeroDivisionError,
4000 "division by zero");
4001 goto error;
4002 }
4003 if (a_size == 0)
4004 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 /* Fast path for a and b small (exactly representable in a double).
4007 Relies on floating-point division being correctly rounded; results
4008 may be subject to double rounding on x86 machines that operate with
4009 the x87 FPU set to 64-bit precision. */
4010 a_is_small = a_size <= MANT_DIG_DIGITS ||
4011 (a_size == MANT_DIG_DIGITS+1 &&
4012 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
4013 b_is_small = b_size <= MANT_DIG_DIGITS ||
4014 (b_size == MANT_DIG_DIGITS+1 &&
4015 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
4016 if (a_is_small && b_is_small) {
4017 double da, db;
4018 da = a->ob_digit[--a_size];
4019 while (a_size > 0)
4020 da = da * PyLong_BASE + a->ob_digit[--a_size];
4021 db = b->ob_digit[--b_size];
4022 while (b_size > 0)
4023 db = db * PyLong_BASE + b->ob_digit[--b_size];
4024 result = da / db;
4025 goto success;
4026 }
Tim Peterse2a60002001-09-04 06:17:36 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 /* Catch obvious cases of underflow and overflow */
4029 diff = a_size - b_size;
4030 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
4031 /* Extreme overflow */
4032 goto overflow;
4033 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
4034 /* Extreme underflow */
4035 goto underflow_or_zero;
4036 /* Next line is now safe from overflowing a Py_ssize_t */
4037 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
4038 bits_in_digit(b->ob_digit[b_size - 1]);
4039 /* Now diff = a_bits - b_bits. */
4040 if (diff > DBL_MAX_EXP)
4041 goto overflow;
4042 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
4043 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004046 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 /* x = abs(a * 2**-shift) */
4051 if (shift <= 0) {
4052 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
4053 digit rem;
4054 /* x = a << -shift */
4055 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
4056 /* In practice, it's probably impossible to end up
4057 here. Both a and b would have to be enormous,
4058 using close to SIZE_T_MAX bytes of memory each. */
4059 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004060 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 goto error;
4062 }
4063 x = _PyLong_New(a_size + shift_digits + 1);
4064 if (x == NULL)
4065 goto error;
4066 for (i = 0; i < shift_digits; i++)
4067 x->ob_digit[i] = 0;
4068 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
4069 a_size, -shift % PyLong_SHIFT);
4070 x->ob_digit[a_size + shift_digits] = rem;
4071 }
4072 else {
4073 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
4074 digit rem;
4075 /* x = a >> shift */
4076 assert(a_size >= shift_digits);
4077 x = _PyLong_New(a_size - shift_digits);
4078 if (x == NULL)
4079 goto error;
4080 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4081 a_size - shift_digits, shift % PyLong_SHIFT);
4082 /* set inexact if any of the bits shifted out is nonzero */
4083 if (rem)
4084 inexact = 1;
4085 while (!inexact && shift_digits > 0)
4086 if (a->ob_digit[--shift_digits])
4087 inexact = 1;
4088 }
4089 long_normalize(x);
4090 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4093 reference to x, so it's safe to modify it in-place. */
4094 if (b_size == 1) {
4095 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4096 b->ob_digit[0]);
4097 long_normalize(x);
4098 if (rem)
4099 inexact = 1;
4100 }
4101 else {
4102 PyLongObject *div, *rem;
4103 div = x_divrem(x, b, &rem);
4104 Py_DECREF(x);
4105 x = div;
4106 if (x == NULL)
4107 goto error;
4108 if (Py_SIZE(rem))
4109 inexact = 1;
4110 Py_DECREF(rem);
4111 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004112 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 assert(x_size > 0); /* result of division is never zero */
4114 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004117 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 /* Round by directly modifying the low digit of x. */
4121 mask = (digit)1 << (extra_bits - 1);
4122 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004123 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004125 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 /* Convert x to a double dx; the conversion is exact. */
4128 dx = x->ob_digit[--x_size];
4129 while (x_size > 0)
4130 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4131 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 /* Check whether ldexp result will overflow a double. */
4134 if (shift + x_bits >= DBL_MAX_EXP &&
4135 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4136 goto overflow;
4137 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004138
4139 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004141
4142 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004144
4145 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 PyErr_SetString(PyExc_OverflowError,
4147 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004148 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004150}
4151
4152static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004153long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 CHECK_BINOP(a, b);
4158
Yury Selivanove0b23092016-02-11 10:26:27 -05004159 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4160 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4161 }
4162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4164 mod = NULL;
4165 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004166}
4167
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004168static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004169long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004171 PyLongObject *div, *mod;
4172 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4177 return NULL;
4178 }
4179 z = PyTuple_New(2);
4180 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004181 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4182 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 }
4184 else {
4185 Py_DECREF(div);
4186 Py_DECREF(mod);
4187 }
4188 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004189}
4190
Mark Dickinsonc5299672019-06-02 10:24:06 +01004191
4192/* Compute an inverse to a modulo n, or raise ValueError if a is not
4193 invertible modulo n. Assumes n is positive. The inverse returned
4194 is whatever falls out of the extended Euclidean algorithm: it may
4195 be either positive or negative, but will be smaller than n in
4196 absolute value.
4197
4198 Pure Python equivalent for long_invmod:
4199
4200 def invmod(a, n):
4201 b, c = 1, 0
4202 while n:
4203 q, r = divmod(a, n)
4204 a, b, c, n = n, c, b - q*c, r
4205
4206 # at this point a is the gcd of the original inputs
4207 if a == 1:
4208 return b
4209 raise ValueError("Not invertible")
4210*/
4211
4212static PyLongObject *
4213long_invmod(PyLongObject *a, PyLongObject *n)
4214{
4215 PyLongObject *b, *c;
4216
4217 /* Should only ever be called for positive n */
4218 assert(Py_SIZE(n) > 0);
4219
4220 b = (PyLongObject *)PyLong_FromLong(1L);
4221 if (b == NULL) {
4222 return NULL;
4223 }
4224 c = (PyLongObject *)PyLong_FromLong(0L);
4225 if (c == NULL) {
4226 Py_DECREF(b);
4227 return NULL;
4228 }
4229 Py_INCREF(a);
4230 Py_INCREF(n);
4231
4232 /* references now owned: a, b, c, n */
4233 while (Py_SIZE(n) != 0) {
4234 PyLongObject *q, *r, *s, *t;
4235
4236 if (l_divmod(a, n, &q, &r) == -1) {
4237 goto Error;
4238 }
4239 Py_DECREF(a);
4240 a = n;
4241 n = r;
4242 t = (PyLongObject *)long_mul(q, c);
4243 Py_DECREF(q);
4244 if (t == NULL) {
4245 goto Error;
4246 }
4247 s = (PyLongObject *)long_sub(b, t);
4248 Py_DECREF(t);
4249 if (s == NULL) {
4250 goto Error;
4251 }
4252 Py_DECREF(b);
4253 b = c;
4254 c = s;
4255 }
4256 /* references now owned: a, b, c, n */
4257
4258 Py_DECREF(c);
4259 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004260 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004261 /* a != 1; we don't have an inverse. */
4262 Py_DECREF(a);
4263 Py_DECREF(b);
4264 PyErr_SetString(PyExc_ValueError,
4265 "base is not invertible for the given modulus");
4266 return NULL;
4267 }
4268 else {
4269 /* a == 1; b gives an inverse modulo n */
4270 Py_DECREF(a);
4271 return b;
4272 }
4273
4274 Error:
4275 Py_DECREF(a);
4276 Py_DECREF(b);
4277 Py_DECREF(c);
4278 Py_DECREF(n);
4279 return NULL;
4280}
4281
4282
Tim Peters47e52ee2004-08-30 02:44:38 +00004283/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004284static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004285long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4288 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 PyLongObject *z = NULL; /* accumulated result */
4291 Py_ssize_t i, j, k; /* counters */
4292 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 /* 5-ary values. If the exponent is large enough, table is
4295 * precomputed so that table[i] == a**i % c for i in range(32).
4296 */
4297 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4298 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 /* a, b, c = v, w, x */
4301 CHECK_BINOP(v, w);
4302 a = (PyLongObject*)v; Py_INCREF(a);
4303 b = (PyLongObject*)w; Py_INCREF(b);
4304 if (PyLong_Check(x)) {
4305 c = (PyLongObject *)x;
4306 Py_INCREF(x);
4307 }
4308 else if (x == Py_None)
4309 c = NULL;
4310 else {
4311 Py_DECREF(a);
4312 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004313 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 }
Tim Peters4c483c42001-09-05 06:24:58 +00004315
Mark Dickinsonc5299672019-06-02 10:24:06 +01004316 if (Py_SIZE(b) < 0 && c == NULL) {
4317 /* if exponent is negative and there's no modulus:
4318 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 that this calls float_pow() which converts its
4320 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004321 Py_DECREF(a);
4322 Py_DECREF(b);
4323 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 if (c) {
4327 /* if modulus == 0:
4328 raise ValueError() */
4329 if (Py_SIZE(c) == 0) {
4330 PyErr_SetString(PyExc_ValueError,
4331 "pow() 3rd argument cannot be 0");
4332 goto Error;
4333 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 /* if modulus < 0:
4336 negativeOutput = True
4337 modulus = -modulus */
4338 if (Py_SIZE(c) < 0) {
4339 negativeOutput = 1;
4340 temp = (PyLongObject *)_PyLong_Copy(c);
4341 if (temp == NULL)
4342 goto Error;
4343 Py_DECREF(c);
4344 c = temp;
4345 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004346 _PyLong_Negate(&c);
4347 if (c == NULL)
4348 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 /* if modulus == 1:
4352 return 0 */
4353 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4354 z = (PyLongObject *)PyLong_FromLong(0L);
4355 goto Done;
4356 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004357
Mark Dickinsonc5299672019-06-02 10:24:06 +01004358 /* if exponent is negative, negate the exponent and
4359 replace the base with a modular inverse */
4360 if (Py_SIZE(b) < 0) {
4361 temp = (PyLongObject *)_PyLong_Copy(b);
4362 if (temp == NULL)
4363 goto Error;
4364 Py_DECREF(b);
4365 b = temp;
4366 temp = NULL;
4367 _PyLong_Negate(&b);
4368 if (b == NULL)
4369 goto Error;
4370
4371 temp = long_invmod(a, c);
4372 if (temp == NULL)
4373 goto Error;
4374 Py_DECREF(a);
4375 a = temp;
4376 }
4377
Tim Peters81a93152013-10-05 16:53:52 -05004378 /* Reduce base by modulus in some cases:
4379 1. If base < 0. Forcing the base non-negative makes things easier.
4380 2. If base is obviously larger than the modulus. The "small
4381 exponent" case later can multiply directly by base repeatedly,
4382 while the "large exponent" case multiplies directly by base 31
4383 times. It can be unboundedly faster to multiply by
4384 base % modulus instead.
4385 We could _always_ do this reduction, but l_divmod() isn't cheap,
4386 so we only do it when it buys something. */
4387 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 if (l_divmod(a, c, NULL, &temp) < 0)
4389 goto Error;
4390 Py_DECREF(a);
4391 a = temp;
4392 temp = NULL;
4393 }
4394 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 /* At this point a, b, and c are guaranteed non-negative UNLESS
4397 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 z = (PyLongObject *)PyLong_FromLong(1L);
4400 if (z == NULL)
4401 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 /* Perform a modular reduction, X = X % c, but leave X alone if c
4404 * is NULL.
4405 */
4406#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004407 do { \
4408 if (c != NULL) { \
4409 if (l_divmod(X, c, NULL, &temp) < 0) \
4410 goto Error; \
4411 Py_XDECREF(X); \
4412 X = temp; \
4413 temp = NULL; \
4414 } \
4415 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 /* Multiply two values, then reduce the result:
4418 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004419#define MULT(X, Y, result) \
4420 do { \
4421 temp = (PyLongObject *)long_mul(X, Y); \
4422 if (temp == NULL) \
4423 goto Error; \
4424 Py_XDECREF(result); \
4425 result = temp; \
4426 temp = NULL; \
4427 REDUCE(result); \
4428 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4431 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4432 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4433 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4434 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004437 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004439 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 }
4441 }
4442 }
4443 else {
4444 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4445 Py_INCREF(z); /* still holds 1L */
4446 table[0] = z;
4447 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004448 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4451 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4454 const int index = (bi >> j) & 0x1f;
4455 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004456 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004458 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 }
4460 }
4461 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 if (negativeOutput && (Py_SIZE(z) != 0)) {
4464 temp = (PyLongObject *)long_sub(z, c);
4465 if (temp == NULL)
4466 goto Error;
4467 Py_DECREF(z);
4468 z = temp;
4469 temp = NULL;
4470 }
4471 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004472
Mark Dickinson22b20182010-05-10 21:27:53 +00004473 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004474 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004476 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4478 for (i = 0; i < 32; ++i)
4479 Py_XDECREF(table[i]);
4480 }
4481 Py_DECREF(a);
4482 Py_DECREF(b);
4483 Py_XDECREF(c);
4484 Py_XDECREF(temp);
4485 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004486}
4487
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004488static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004489long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 /* Implement ~x as -(x+1) */
4492 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004493 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004495 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 if (x == NULL)
4497 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004498 _PyLong_Negate(&x);
4499 /* No need for maybe_small_long here, since any small
4500 longs will have been caught in the Py_SIZE <= 1 fast path. */
4501 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004502}
4503
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004504static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004505long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004508 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 return PyLong_FromLong(-MEDIUM_VALUE(v));
4510 z = (PyLongObject *)_PyLong_Copy(v);
4511 if (z != NULL)
4512 Py_SIZE(z) = -(Py_SIZE(v));
4513 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004514}
4515
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004516static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004517long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 if (Py_SIZE(v) < 0)
4520 return long_neg(v);
4521 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004522 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004523}
4524
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004525static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004526long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004529}
4530
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004531/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4532static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004533divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004534{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004535 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004536 assert(Py_SIZE(shiftby) >= 0);
4537 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4538 if (lshiftby >= 0) {
4539 *wordshift = lshiftby / PyLong_SHIFT;
4540 *remshift = lshiftby % PyLong_SHIFT;
4541 return 0;
4542 }
4543 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4544 be that PyLong_AsSsize_t raised an OverflowError. */
4545 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4546 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004547 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004548 if (wordshift_obj == NULL) {
4549 return -1;
4550 }
4551 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4552 Py_DECREF(wordshift_obj);
4553 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4554 return 0;
4555 }
4556 PyErr_Clear();
4557 /* Clip the value. With such large wordshift the right shift
4558 returns 0 and the left shift raises an error in _PyLong_New(). */
4559 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4560 *remshift = 0;
4561 return 0;
4562}
4563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004564static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004565long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004568 Py_ssize_t newsize, hishift, i, j;
4569 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 if (Py_SIZE(a) < 0) {
4572 /* Right shifting negative numbers is harder */
4573 PyLongObject *a1, *a2;
4574 a1 = (PyLongObject *) long_invert(a);
4575 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004576 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004577 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 Py_DECREF(a1);
4579 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004580 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 z = (PyLongObject *) long_invert(a2);
4582 Py_DECREF(a2);
4583 }
4584 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004585 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 if (newsize <= 0)
4587 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004588 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 lomask = ((digit)1 << hishift) - 1;
4590 himask = PyLong_MASK ^ lomask;
4591 z = _PyLong_New(newsize);
4592 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004593 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004595 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004597 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004599 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004600 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004601 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004602}
4603
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004604static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004605long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004606{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004607 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004608 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004610 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004611
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004612 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004614 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004616 if (Py_SIZE(a) == 0) {
4617 return PyLong_FromLong(0);
4618 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004619 if (divmod_shift(b, &wordshift, &remshift) < 0)
4620 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004621 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4622}
4623
4624/* Return a >> shiftby. */
4625PyObject *
4626_PyLong_Rshift(PyObject *a, size_t shiftby)
4627{
4628 Py_ssize_t wordshift;
4629 digit remshift;
4630
4631 assert(PyLong_Check(a));
4632 if (Py_SIZE(a) == 0) {
4633 return PyLong_FromLong(0);
4634 }
4635 wordshift = shiftby / PyLong_SHIFT;
4636 remshift = shiftby % PyLong_SHIFT;
4637 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4638}
4639
4640static PyObject *
4641long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4642{
4643 /* This version due to Tim Peters */
4644 PyLongObject *z = NULL;
4645 Py_ssize_t oldsize, newsize, i, j;
4646 twodigits accum;
4647
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004648 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 newsize = oldsize + wordshift;
4650 if (remshift)
4651 ++newsize;
4652 z = _PyLong_New(newsize);
4653 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004654 return NULL;
4655 if (Py_SIZE(a) < 0) {
4656 assert(Py_REFCNT(z) == 1);
4657 Py_SIZE(z) = -Py_SIZE(z);
4658 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 for (i = 0; i < wordshift; i++)
4660 z->ob_digit[i] = 0;
4661 accum = 0;
4662 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4663 accum |= (twodigits)a->ob_digit[j] << remshift;
4664 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4665 accum >>= PyLong_SHIFT;
4666 }
4667 if (remshift)
4668 z->ob_digit[newsize-1] = (digit)accum;
4669 else
4670 assert(!accum);
4671 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004673}
4674
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004675static PyObject *
4676long_lshift(PyObject *a, PyObject *b)
4677{
4678 Py_ssize_t wordshift;
4679 digit remshift;
4680
4681 CHECK_BINOP(a, b);
4682
4683 if (Py_SIZE(b) < 0) {
4684 PyErr_SetString(PyExc_ValueError, "negative shift count");
4685 return NULL;
4686 }
4687 if (Py_SIZE(a) == 0) {
4688 return PyLong_FromLong(0);
4689 }
4690 if (divmod_shift(b, &wordshift, &remshift) < 0)
4691 return NULL;
4692 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4693}
4694
4695/* Return a << shiftby. */
4696PyObject *
4697_PyLong_Lshift(PyObject *a, size_t shiftby)
4698{
4699 Py_ssize_t wordshift;
4700 digit remshift;
4701
4702 assert(PyLong_Check(a));
4703 if (Py_SIZE(a) == 0) {
4704 return PyLong_FromLong(0);
4705 }
4706 wordshift = shiftby / PyLong_SHIFT;
4707 remshift = shiftby % PyLong_SHIFT;
4708 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4709}
4710
Mark Dickinson27a87a22009-10-25 20:43:34 +00004711/* Compute two's complement of digit vector a[0:m], writing result to
4712 z[0:m]. The digit vector a need not be normalized, but should not
4713 be entirely zero. a and z may point to the same digit vector. */
4714
4715static void
4716v_complement(digit *z, digit *a, Py_ssize_t m)
4717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 Py_ssize_t i;
4719 digit carry = 1;
4720 for (i = 0; i < m; ++i) {
4721 carry += a[i] ^ PyLong_MASK;
4722 z[i] = carry & PyLong_MASK;
4723 carry >>= PyLong_SHIFT;
4724 }
4725 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004726}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004727
4728/* Bitwise and/xor/or operations */
4729
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004730static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004731long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004732 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004733 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 int nega, negb, negz;
4736 Py_ssize_t size_a, size_b, size_z, i;
4737 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 /* Bitwise operations for negative numbers operate as though
4740 on a two's complement representation. So convert arguments
4741 from sign-magnitude to two's complement, and convert the
4742 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004745 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 nega = Py_SIZE(a) < 0;
4747 if (nega) {
4748 z = _PyLong_New(size_a);
4749 if (z == NULL)
4750 return NULL;
4751 v_complement(z->ob_digit, a->ob_digit, size_a);
4752 a = z;
4753 }
4754 else
4755 /* Keep reference count consistent. */
4756 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004759 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 negb = Py_SIZE(b) < 0;
4761 if (negb) {
4762 z = _PyLong_New(size_b);
4763 if (z == NULL) {
4764 Py_DECREF(a);
4765 return NULL;
4766 }
4767 v_complement(z->ob_digit, b->ob_digit, size_b);
4768 b = z;
4769 }
4770 else
4771 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004773 /* Swap a and b if necessary to ensure size_a >= size_b. */
4774 if (size_a < size_b) {
4775 z = a; a = b; b = z;
4776 size_z = size_a; size_a = size_b; size_b = size_z;
4777 negz = nega; nega = negb; negb = negz;
4778 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 /* JRH: The original logic here was to allocate the result value (z)
4781 as the longer of the two operands. However, there are some cases
4782 where the result is guaranteed to be shorter than that: AND of two
4783 positives, OR of two negatives: use the shorter number. AND with
4784 mixed signs: use the positive number. OR with mixed signs: use the
4785 negative number.
4786 */
4787 switch (op) {
4788 case '^':
4789 negz = nega ^ negb;
4790 size_z = size_a;
4791 break;
4792 case '&':
4793 negz = nega & negb;
4794 size_z = negb ? size_a : size_b;
4795 break;
4796 case '|':
4797 negz = nega | negb;
4798 size_z = negb ? size_b : size_a;
4799 break;
4800 default:
stratakisa10d4262019-03-18 18:59:20 +01004801 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 /* We allow an extra digit if z is negative, to make sure that
4805 the final two's complement of z doesn't overflow. */
4806 z = _PyLong_New(size_z + negz);
4807 if (z == NULL) {
4808 Py_DECREF(a);
4809 Py_DECREF(b);
4810 return NULL;
4811 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 /* Compute digits for overlap of a and b. */
4814 switch(op) {
4815 case '&':
4816 for (i = 0; i < size_b; ++i)
4817 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4818 break;
4819 case '|':
4820 for (i = 0; i < size_b; ++i)
4821 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4822 break;
4823 case '^':
4824 for (i = 0; i < size_b; ++i)
4825 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4826 break;
4827 default:
stratakisa10d4262019-03-18 18:59:20 +01004828 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 /* Copy any remaining digits of a, inverting if necessary. */
4832 if (op == '^' && negb)
4833 for (; i < size_z; ++i)
4834 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4835 else if (i < size_z)
4836 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4837 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 /* Complement result if negative. */
4840 if (negz) {
4841 Py_SIZE(z) = -(Py_SIZE(z));
4842 z->ob_digit[size_z] = PyLong_MASK;
4843 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4844 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004846 Py_DECREF(a);
4847 Py_DECREF(b);
4848 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004849}
4850
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004851static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004852long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 PyObject *c;
4855 CHECK_BINOP(a, b);
4856 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4857 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004858}
4859
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004860static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004861long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 PyObject *c;
4864 CHECK_BINOP(a, b);
4865 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4866 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004867}
4868
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004869static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004870long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004872 PyObject *c;
4873 CHECK_BINOP(a, b);
4874 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4875 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004876}
4877
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004878static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004879long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004881 if (PyLong_CheckExact(v))
4882 Py_INCREF(v);
4883 else
4884 v = _PyLong_Copy((PyLongObject *)v);
4885 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004886}
4887
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004888PyObject *
4889_PyLong_GCD(PyObject *aarg, PyObject *barg)
4890{
4891 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4892 stwodigits x, y, q, s, t, c_carry, d_carry;
4893 stwodigits A, B, C, D, T;
4894 int nbits, k;
4895 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4896 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4897
4898 a = (PyLongObject *)aarg;
4899 b = (PyLongObject *)barg;
4900 size_a = Py_SIZE(a);
4901 size_b = Py_SIZE(b);
4902 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4903 Py_INCREF(a);
4904 Py_INCREF(b);
4905 goto simple;
4906 }
4907
4908 /* Initial reduction: make sure that 0 <= b <= a. */
4909 a = (PyLongObject *)long_abs(a);
4910 if (a == NULL)
4911 return NULL;
4912 b = (PyLongObject *)long_abs(b);
4913 if (b == NULL) {
4914 Py_DECREF(a);
4915 return NULL;
4916 }
4917 if (long_compare(a, b) < 0) {
4918 r = a;
4919 a = b;
4920 b = r;
4921 }
4922 /* We now own references to a and b */
4923
4924 alloc_a = Py_SIZE(a);
4925 alloc_b = Py_SIZE(b);
4926 /* reduce until a fits into 2 digits */
4927 while ((size_a = Py_SIZE(a)) > 2) {
4928 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4929 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4930 corresponding bits of b into y */
4931 size_b = Py_SIZE(b);
4932 assert(size_b <= size_a);
4933 if (size_b == 0) {
4934 if (size_a < alloc_a) {
4935 r = (PyLongObject *)_PyLong_Copy(a);
4936 Py_DECREF(a);
4937 }
4938 else
4939 r = a;
4940 Py_DECREF(b);
4941 Py_XDECREF(c);
4942 Py_XDECREF(d);
4943 return (PyObject *)r;
4944 }
4945 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4946 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4947 (a->ob_digit[size_a-3] >> nbits));
4948
4949 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4950 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4951 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4952
4953 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4954 larger than PyLong_MASK during the algorithm. */
4955 A = 1; B = 0; C = 0; D = 1;
4956 for (k=0;; k++) {
4957 if (y-C == 0)
4958 break;
4959 q = (x+(A-1))/(y-C);
4960 s = B+q*D;
4961 t = x-q*y;
4962 if (s > t)
4963 break;
4964 x = y; y = t;
4965 t = A+q*C; A = D; B = C; C = s; D = t;
4966 }
4967
4968 if (k == 0) {
4969 /* no progress; do a Euclidean step */
4970 if (l_divmod(a, b, NULL, &r) < 0)
4971 goto error;
4972 Py_DECREF(a);
4973 a = b;
4974 b = r;
4975 alloc_a = alloc_b;
4976 alloc_b = Py_SIZE(b);
4977 continue;
4978 }
4979
4980 /*
4981 a, b = A*b-B*a, D*a-C*b if k is odd
4982 a, b = A*a-B*b, D*b-C*a if k is even
4983 */
4984 if (k&1) {
4985 T = -A; A = -B; B = T;
4986 T = -C; C = -D; D = T;
4987 }
4988 if (c != NULL)
4989 Py_SIZE(c) = size_a;
4990 else if (Py_REFCNT(a) == 1) {
4991 Py_INCREF(a);
4992 c = a;
4993 }
4994 else {
4995 alloc_a = size_a;
4996 c = _PyLong_New(size_a);
4997 if (c == NULL)
4998 goto error;
4999 }
5000
5001 if (d != NULL)
5002 Py_SIZE(d) = size_a;
5003 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
5004 Py_INCREF(b);
5005 d = b;
5006 Py_SIZE(d) = size_a;
5007 }
5008 else {
5009 alloc_b = size_a;
5010 d = _PyLong_New(size_a);
5011 if (d == NULL)
5012 goto error;
5013 }
5014 a_end = a->ob_digit + size_a;
5015 b_end = b->ob_digit + size_b;
5016
5017 /* compute new a and new b in parallel */
5018 a_digit = a->ob_digit;
5019 b_digit = b->ob_digit;
5020 c_digit = c->ob_digit;
5021 d_digit = d->ob_digit;
5022 c_carry = 0;
5023 d_carry = 0;
5024 while (b_digit < b_end) {
5025 c_carry += (A * *a_digit) - (B * *b_digit);
5026 d_carry += (D * *b_digit++) - (C * *a_digit++);
5027 *c_digit++ = (digit)(c_carry & PyLong_MASK);
5028 *d_digit++ = (digit)(d_carry & PyLong_MASK);
5029 c_carry >>= PyLong_SHIFT;
5030 d_carry >>= PyLong_SHIFT;
5031 }
5032 while (a_digit < a_end) {
5033 c_carry += A * *a_digit;
5034 d_carry -= C * *a_digit++;
5035 *c_digit++ = (digit)(c_carry & PyLong_MASK);
5036 *d_digit++ = (digit)(d_carry & PyLong_MASK);
5037 c_carry >>= PyLong_SHIFT;
5038 d_carry >>= PyLong_SHIFT;
5039 }
5040 assert(c_carry == 0);
5041 assert(d_carry == 0);
5042
5043 Py_INCREF(c);
5044 Py_INCREF(d);
5045 Py_DECREF(a);
5046 Py_DECREF(b);
5047 a = long_normalize(c);
5048 b = long_normalize(d);
5049 }
5050 Py_XDECREF(c);
5051 Py_XDECREF(d);
5052
5053simple:
5054 assert(Py_REFCNT(a) > 0);
5055 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02005056/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
5057 undefined behaviour when LONG_MAX type is smaller than 60 bits */
5058#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005059 /* a fits into a long, so b must too */
5060 x = PyLong_AsLong((PyObject *)a);
5061 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07005062#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005063 x = PyLong_AsLongLong((PyObject *)a);
5064 y = PyLong_AsLongLong((PyObject *)b);
5065#else
5066# error "_PyLong_GCD"
5067#endif
5068 x = Py_ABS(x);
5069 y = Py_ABS(y);
5070 Py_DECREF(a);
5071 Py_DECREF(b);
5072
5073 /* usual Euclidean algorithm for longs */
5074 while (y != 0) {
5075 t = y;
5076 y = x % y;
5077 x = t;
5078 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005079#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005080 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07005081#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005082 return PyLong_FromLongLong(x);
5083#else
5084# error "_PyLong_GCD"
5085#endif
5086
5087error:
5088 Py_DECREF(a);
5089 Py_DECREF(b);
5090 Py_XDECREF(c);
5091 Py_XDECREF(d);
5092 return NULL;
5093}
5094
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005095static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005096long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 double result;
5099 result = PyLong_AsDouble(v);
5100 if (result == -1.0 && PyErr_Occurred())
5101 return NULL;
5102 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005103}
5104
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005105static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005106long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5107
5108/*[clinic input]
5109@classmethod
5110int.__new__ as long_new
5111 x: object(c_default="NULL") = 0
5112 /
5113 base as obase: object(c_default="NULL") = 10
5114[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005115
Tim Peters6d6c1a32001-08-02 04:15:00 +00005116static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005117long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5118/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005119{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005120 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005123 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005124 if (x == NULL) {
5125 if (obase != NULL) {
5126 PyErr_SetString(PyExc_TypeError,
5127 "int() missing string argument");
5128 return NULL;
5129 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005131 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005132 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005134
Gregory P. Smitha689e522012-12-25 22:38:32 -08005135 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005136 if (base == -1 && PyErr_Occurred())
5137 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005138 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005139 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305140 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005141 return NULL;
5142 }
5143
5144 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005145 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005146 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005147 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 if (PyByteArray_Check(x))
5149 string = PyByteArray_AS_STRING(x);
5150 else
5151 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005152 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 }
5154 else {
5155 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005156 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005157 return NULL;
5158 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005159}
5160
Serhiy Storchaka95949422013-08-27 19:40:23 +03005161/* Wimpy, slow approach to tp_new calls for subtypes of int:
5162 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005163 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005164 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005165*/
5166static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005167long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005169 PyLongObject *tmp, *newobj;
5170 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005172 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005173 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 if (tmp == NULL)
5175 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005176 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 n = Py_SIZE(tmp);
5178 if (n < 0)
5179 n = -n;
5180 newobj = (PyLongObject *)type->tp_alloc(type, n);
5181 if (newobj == NULL) {
5182 Py_DECREF(tmp);
5183 return NULL;
5184 }
5185 assert(PyLong_Check(newobj));
5186 Py_SIZE(newobj) = Py_SIZE(tmp);
5187 for (i = 0; i < n; i++)
5188 newobj->ob_digit[i] = tmp->ob_digit[i];
5189 Py_DECREF(tmp);
5190 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005191}
5192
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005193/*[clinic input]
5194int.__getnewargs__
5195[clinic start generated code]*/
5196
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005197static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005198int___getnewargs___impl(PyObject *self)
5199/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005200{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005201 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005202}
5203
Guido van Rossumb43daf72007-08-01 18:08:08 +00005204static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005205long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005208}
5209
5210static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005211long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005214}
5215
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005216/*[clinic input]
5217int.__format__
5218
5219 format_spec: unicode
5220 /
5221[clinic start generated code]*/
5222
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005223static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005224int___format___impl(PyObject *self, PyObject *format_spec)
5225/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005226{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005227 _PyUnicodeWriter writer;
5228 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005229
Victor Stinner8f674cc2013-04-17 23:02:17 +02005230 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005231 ret = _PyLong_FormatAdvancedWriter(
5232 &writer,
5233 self,
5234 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5235 if (ret == -1) {
5236 _PyUnicodeWriter_Dealloc(&writer);
5237 return NULL;
5238 }
5239 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005240}
5241
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005242/* Return a pair (q, r) such that a = b * q + r, and
5243 abs(r) <= abs(b)/2, with equality possible only if q is even.
5244 In other words, q == a / b, rounded to the nearest integer using
5245 round-half-to-even. */
5246
5247PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005248_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005249{
5250 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005251 PyObject *twice_rem, *result, *temp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005252 int cmp, quo_is_odd, quo_is_neg;
5253
5254 /* Equivalent Python code:
5255
5256 def divmod_near(a, b):
5257 q, r = divmod(a, b)
5258 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5259 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5260 # positive, 2 * r < b if b negative.
5261 greater_than_half = 2*r > b if b > 0 else 2*r < b
5262 exactly_half = 2*r == b
5263 if greater_than_half or exactly_half and q % 2 == 1:
5264 q += 1
5265 r -= b
5266 return q, r
5267
5268 */
5269 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5270 PyErr_SetString(PyExc_TypeError,
5271 "non-integer arguments in division");
5272 return NULL;
5273 }
5274
5275 /* Do a and b have different signs? If so, quotient is negative. */
5276 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5277
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005278 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5279 goto error;
5280
5281 /* compare twice the remainder with the divisor, to see
5282 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005283 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005284 if (twice_rem == NULL)
5285 goto error;
5286 if (quo_is_neg) {
5287 temp = long_neg((PyLongObject*)twice_rem);
5288 Py_DECREF(twice_rem);
5289 twice_rem = temp;
5290 if (twice_rem == NULL)
5291 goto error;
5292 }
5293 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5294 Py_DECREF(twice_rem);
5295
5296 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5297 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5298 /* fix up quotient */
5299 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005300 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005301 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005302 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005303 Py_DECREF(quo);
5304 quo = (PyLongObject *)temp;
5305 if (quo == NULL)
5306 goto error;
5307 /* and remainder */
5308 if (quo_is_neg)
5309 temp = long_add(rem, (PyLongObject *)b);
5310 else
5311 temp = long_sub(rem, (PyLongObject *)b);
5312 Py_DECREF(rem);
5313 rem = (PyLongObject *)temp;
5314 if (rem == NULL)
5315 goto error;
5316 }
5317
5318 result = PyTuple_New(2);
5319 if (result == NULL)
5320 goto error;
5321
5322 /* PyTuple_SET_ITEM steals references */
5323 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5324 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005325 return result;
5326
5327 error:
5328 Py_XDECREF(quo);
5329 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005330 return NULL;
5331}
5332
Eric Smith8c663262007-08-25 02:26:07 +00005333static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005334long_round(PyObject *self, PyObject *args)
5335{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005336 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005337
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005338 /* To round an integer m to the nearest 10**n (n positive), we make use of
5339 * the divmod_near operation, defined by:
5340 *
5341 * divmod_near(a, b) = (q, r)
5342 *
5343 * where q is the nearest integer to the quotient a / b (the
5344 * nearest even integer in the case of a tie) and r == a - q * b.
5345 * Hence q * b = a - r is the nearest multiple of b to a,
5346 * preferring even multiples in the case of a tie.
5347 *
5348 * So the nearest multiple of 10**n to m is:
5349 *
5350 * m - divmod_near(m, 10**n)[1].
5351 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005352 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5353 return NULL;
5354 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005355 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005356
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005357 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 if (ndigits == NULL)
5359 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005360
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005361 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 if (Py_SIZE(ndigits) >= 0) {
5363 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005364 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005366
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005367 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5368 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005370 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005372 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005373
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005374 result = PyLong_FromLong(10L);
5375 if (result == NULL) {
5376 Py_DECREF(ndigits);
5377 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005379
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005380 temp = long_pow(result, ndigits, Py_None);
5381 Py_DECREF(ndigits);
5382 Py_DECREF(result);
5383 result = temp;
5384 if (result == NULL)
5385 return NULL;
5386
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005387 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005388 Py_DECREF(result);
5389 result = temp;
5390 if (result == NULL)
5391 return NULL;
5392
5393 temp = long_sub((PyLongObject *)self,
5394 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5395 Py_DECREF(result);
5396 result = temp;
5397
5398 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005399}
5400
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005401/*[clinic input]
5402int.__sizeof__ -> Py_ssize_t
5403
5404Returns size in memory, in bytes.
5405[clinic start generated code]*/
5406
5407static Py_ssize_t
5408int___sizeof___impl(PyObject *self)
5409/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005412
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005413 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5414 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005415}
5416
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005417/*[clinic input]
5418int.bit_length
5419
5420Number of bits necessary to represent self in binary.
5421
5422>>> bin(37)
5423'0b100101'
5424>>> (37).bit_length()
54256
5426[clinic start generated code]*/
5427
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005428static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005429int_bit_length_impl(PyObject *self)
5430/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005433 Py_ssize_t ndigits;
5434 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005436
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005437 assert(self != NULL);
5438 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005439
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005440 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 if (ndigits == 0)
5442 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005443
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005444 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005445 msd_bits = bits_in_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5448 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 /* expression above may overflow; use Python integers instead */
5451 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5452 if (result == NULL)
5453 return NULL;
5454 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5455 if (x == NULL)
5456 goto error;
5457 y = (PyLongObject *)long_mul(result, x);
5458 Py_DECREF(x);
5459 if (y == NULL)
5460 goto error;
5461 Py_DECREF(result);
5462 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5465 if (x == NULL)
5466 goto error;
5467 y = (PyLongObject *)long_add(result, x);
5468 Py_DECREF(x);
5469 if (y == NULL)
5470 goto error;
5471 Py_DECREF(result);
5472 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005474 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005475
Mark Dickinson22b20182010-05-10 21:27:53 +00005476 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 Py_DECREF(result);
5478 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005479}
5480
Christian Heimes53876d92008-04-19 00:31:39 +00005481#if 0
5482static PyObject *
5483long_is_finite(PyObject *v)
5484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005485 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005486}
5487#endif
5488
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005489/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005490int.as_integer_ratio
5491
5492Return integer ratio.
5493
5494Return a pair of integers, whose ratio is exactly equal to the original int
5495and with a positive denominator.
5496
5497>>> (10).as_integer_ratio()
5498(10, 1)
5499>>> (-10).as_integer_ratio()
5500(-10, 1)
5501>>> (0).as_integer_ratio()
5502(0, 1)
5503[clinic start generated code]*/
5504
5505static PyObject *
5506int_as_integer_ratio_impl(PyObject *self)
5507/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5508{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005509 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005510 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005511 if (numerator == NULL) {
5512 return NULL;
5513 }
5514 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5515 Py_DECREF(numerator);
5516 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005517}
5518
5519/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005520int.to_bytes
5521
5522 length: Py_ssize_t
5523 Length of bytes object to use. An OverflowError is raised if the
5524 integer is not representable with the given number of bytes.
5525 byteorder: unicode
5526 The byte order used to represent the integer. If byteorder is 'big',
5527 the most significant byte is at the beginning of the byte array. If
5528 byteorder is 'little', the most significant byte is at the end of the
5529 byte array. To request the native byte order of the host system, use
5530 `sys.byteorder' as the byte order value.
5531 *
5532 signed as is_signed: bool = False
5533 Determines whether two's complement is used to represent the integer.
5534 If signed is False and a negative integer is given, an OverflowError
5535 is raised.
5536
5537Return an array of bytes representing an integer.
5538[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005539
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005540static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005541int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5542 int is_signed)
5543/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005547
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005548 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005550 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 little_endian = 0;
5552 else {
5553 PyErr_SetString(PyExc_ValueError,
5554 "byteorder must be either 'little' or 'big'");
5555 return NULL;
5556 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 if (length < 0) {
5559 PyErr_SetString(PyExc_ValueError,
5560 "length argument must be non-negative");
5561 return NULL;
5562 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 bytes = PyBytes_FromStringAndSize(NULL, length);
5565 if (bytes == NULL)
5566 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005567
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005568 if (_PyLong_AsByteArray((PyLongObject *)self,
5569 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 length, little_endian, is_signed) < 0) {
5571 Py_DECREF(bytes);
5572 return NULL;
5573 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005576}
5577
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005578/*[clinic input]
5579@classmethod
5580int.from_bytes
5581
5582 bytes as bytes_obj: object
5583 Holds the array of bytes to convert. The argument must either
5584 support the buffer protocol or be an iterable object producing bytes.
5585 Bytes and bytearray are examples of built-in objects that support the
5586 buffer protocol.
5587 byteorder: unicode
5588 The byte order used to represent the integer. If byteorder is 'big',
5589 the most significant byte is at the beginning of the byte array. If
5590 byteorder is 'little', the most significant byte is at the end of the
5591 byte array. To request the native byte order of the host system, use
5592 `sys.byteorder' as the byte order value.
5593 *
5594 signed as is_signed: bool = False
5595 Indicates whether two's complement is used to represent the integer.
5596
5597Return the integer represented by the given array of bytes.
5598[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005599
5600static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005601int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5602 PyObject *byteorder, int is_signed)
5603/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005605 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005606 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005607
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005608 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005609 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005610 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005611 little_endian = 0;
5612 else {
5613 PyErr_SetString(PyExc_ValueError,
5614 "byteorder must be either 'little' or 'big'");
5615 return NULL;
5616 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005617
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005618 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 if (bytes == NULL)
5620 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 long_obj = _PyLong_FromByteArray(
5623 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5624 little_endian, is_signed);
5625 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005626
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005627 if (long_obj != NULL && type != &PyLong_Type) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02005628 Py_SETREF(long_obj, _PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005629 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005632}
5633
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005634static PyObject *
5635long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5636{
5637 return long_long(self);
5638}
5639
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005640static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005641 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005642 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005643 INT_BIT_LENGTH_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00005644#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005645 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5646 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005647#endif
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005648 INT_TO_BYTES_METHODDEF
5649 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005650 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005651 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005653 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005655 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005656 "Ceiling of an Integral returns itself."},
5657 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5658 "Rounding an Integral returns itself.\n"
5659 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005660 INT___GETNEWARGS___METHODDEF
5661 INT___FORMAT___METHODDEF
5662 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005664};
5665
Guido van Rossumb43daf72007-08-01 18:08:08 +00005666static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005667 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005668 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005669 "the real part of a complex number",
5670 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005671 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005672 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005673 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005674 NULL},
5675 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005676 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005677 "the numerator of a rational number in lowest terms",
5678 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005679 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005680 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005681 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005682 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005683 {NULL} /* Sentinel */
5684};
5685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005686PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005687"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005688int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005689\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005690Convert a number or string to an integer, or return 0 if no arguments\n\
5691are given. If x is a number, return x.__int__(). For floating point\n\
5692numbers, this truncates towards zero.\n\
5693\n\
5694If x is not a number or if base is given, then x must be a string,\n\
5695bytes, or bytearray instance representing an integer literal in the\n\
5696given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5697by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5698Base 0 means to interpret the base from the string as an integer literal.\n\
5699>>> int('0b100', base=0)\n\
57004");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005701
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005702static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005703 (binaryfunc)long_add, /*nb_add*/
5704 (binaryfunc)long_sub, /*nb_subtract*/
5705 (binaryfunc)long_mul, /*nb_multiply*/
5706 long_mod, /*nb_remainder*/
5707 long_divmod, /*nb_divmod*/
5708 long_pow, /*nb_power*/
5709 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005710 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005711 (unaryfunc)long_abs, /*tp_absolute*/
5712 (inquiry)long_bool, /*tp_bool*/
5713 (unaryfunc)long_invert, /*nb_invert*/
5714 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005715 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005716 long_and, /*nb_and*/
5717 long_xor, /*nb_xor*/
5718 long_or, /*nb_or*/
5719 long_long, /*nb_int*/
5720 0, /*nb_reserved*/
5721 long_float, /*nb_float*/
5722 0, /* nb_inplace_add */
5723 0, /* nb_inplace_subtract */
5724 0, /* nb_inplace_multiply */
5725 0, /* nb_inplace_remainder */
5726 0, /* nb_inplace_power */
5727 0, /* nb_inplace_lshift */
5728 0, /* nb_inplace_rshift */
5729 0, /* nb_inplace_and */
5730 0, /* nb_inplace_xor */
5731 0, /* nb_inplace_or */
5732 long_div, /* nb_floor_divide */
5733 long_true_divide, /* nb_true_divide */
5734 0, /* nb_inplace_floor_divide */
5735 0, /* nb_inplace_true_divide */
5736 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005737};
5738
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005739PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005740 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5741 "int", /* tp_name */
5742 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5743 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005744 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005745 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 0, /* tp_getattr */
5747 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005748 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 long_to_decimal_string, /* tp_repr */
5750 &long_as_number, /* tp_as_number */
5751 0, /* tp_as_sequence */
5752 0, /* tp_as_mapping */
5753 (hashfunc)long_hash, /* tp_hash */
5754 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005755 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005756 PyObject_GenericGetAttr, /* tp_getattro */
5757 0, /* tp_setattro */
5758 0, /* tp_as_buffer */
5759 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5760 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5761 long_doc, /* tp_doc */
5762 0, /* tp_traverse */
5763 0, /* tp_clear */
5764 long_richcompare, /* tp_richcompare */
5765 0, /* tp_weaklistoffset */
5766 0, /* tp_iter */
5767 0, /* tp_iternext */
5768 long_methods, /* tp_methods */
5769 0, /* tp_members */
5770 long_getset, /* tp_getset */
5771 0, /* tp_base */
5772 0, /* tp_dict */
5773 0, /* tp_descr_get */
5774 0, /* tp_descr_set */
5775 0, /* tp_dictoffset */
5776 0, /* tp_init */
5777 0, /* tp_alloc */
5778 long_new, /* tp_new */
5779 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005780};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005781
Mark Dickinsonbd792642009-03-18 20:06:12 +00005782static PyTypeObject Int_InfoType;
5783
5784PyDoc_STRVAR(int_info__doc__,
5785"sys.int_info\n\
5786\n\
5787A struct sequence that holds information about Python's\n\
5788internal representation of integers. The attributes are read only.");
5789
5790static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005791 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005792 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005794};
5795
5796static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005797 "sys.int_info", /* name */
5798 int_info__doc__, /* doc */
5799 int_info_fields, /* fields */
5800 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005801};
5802
5803PyObject *
5804PyLong_GetInfo(void)
5805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005806 PyObject* int_info;
5807 int field = 0;
5808 int_info = PyStructSequence_New(&Int_InfoType);
5809 if (int_info == NULL)
5810 return NULL;
5811 PyStructSequence_SET_ITEM(int_info, field++,
5812 PyLong_FromLong(PyLong_SHIFT));
5813 PyStructSequence_SET_ITEM(int_info, field++,
5814 PyLong_FromLong(sizeof(digit)));
5815 if (PyErr_Occurred()) {
5816 Py_CLEAR(int_info);
5817 return NULL;
5818 }
5819 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005820}
5821
Guido van Rossumddefaf32007-01-14 03:31:43 +00005822int
5823_PyLong_Init(void)
5824{
5825#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 int ival, size;
5827 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005829 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5830 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5831 if (Py_TYPE(v) == &PyLong_Type) {
5832 /* The element is already initialized, most likely
5833 * the Python interpreter was initialized before.
5834 */
5835 Py_ssize_t refcnt;
5836 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005838 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5839 _Py_NewReference(op);
5840 /* _Py_NewReference sets the ref count to 1 but
5841 * the ref count might be larger. Set the refcnt
5842 * to the original refcnt + 1 */
5843 Py_REFCNT(op) = refcnt + 1;
5844 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005845 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005846 }
5847 else {
Victor Stinnerb509d522018-11-23 14:27:38 +01005848 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005849 }
5850 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005851 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005853#endif
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005854 _PyLong_Zero = PyLong_FromLong(0);
5855 if (_PyLong_Zero == NULL)
5856 return 0;
5857 _PyLong_One = PyLong_FromLong(1);
5858 if (_PyLong_One == NULL)
5859 return 0;
5860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005862 if (Int_InfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005863 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005864 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005865 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005866 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005869}
5870
5871void
5872PyLong_Fini(void)
5873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874 /* Integers are currently statically allocated. Py_DECREF is not
5875 needed, but Python must forget about the reference or multiple
5876 reinitializations will fail. */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005877 Py_CLEAR(_PyLong_One);
5878 Py_CLEAR(_PyLong_Zero);
Guido van Rossumddefaf32007-01-14 03:31:43 +00005879#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005880 int i;
5881 PyLongObject *v = small_ints;
5882 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5883 _Py_DEC_REFTOTAL;
5884 _Py_ForgetReference((PyObject*)v);
5885 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005886#endif
5887}