blob: 4cf2b0726e81e05d6f20972d990af223d3cbd2d6 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Serhiy Storchaka495e8802017-02-01 23:12:20 +020012#include "clinic/longobject.c.h"
13/*[clinic input]
14class int "PyObject *" "&PyLong_Type"
15[clinic start generated code]*/
16/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
17
Guido van Rossumddefaf32007-01-14 03:31:43 +000018#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000020#endif
21#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000023#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020025_Py_IDENTIFIER(little);
26_Py_IDENTIFIER(big);
27
Mark Dickinsone4416742009-02-15 15:14:57 +000028/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020029#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
30 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 (Py_SIZE(x) == 0 ? (sdigit)0 : \
32 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000033
Serhiy Storchakaba85d692017-03-30 09:09:41 +030034PyObject *_PyLong_Zero = NULL;
35PyObject *_PyLong_One = NULL;
36
Guido van Rossumddefaf32007-01-14 03:31:43 +000037#if NSMALLNEGINTS + NSMALLPOSINTS > 0
38/* Small integers are preallocated in this array so that they
39 can be shared.
40 The integers that are preallocated are those in the range
41 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
42*/
43static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
Greg Price5e63ab02019-08-24 10:19:37 -070044
animalize6b519982019-09-06 14:00:56 +080045#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
Greg Price5e63ab02019-08-24 10:19:37 -070046
Guido van Rossumddefaf32007-01-14 03:31:43 +000047#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +000048Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000049#endif
50
Guido van Rossum7eaf8222007-06-18 17:58:50 +000051static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000052get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053{
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050054 PyObject *v;
animalize6b519982019-09-06 14:00:56 +080055 assert(IS_SMALL_INT(ival));
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050056 v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000058#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 if (ival >= 0)
Pablo Galindo49c75a82018-10-28 15:02:17 +000060 _Py_quick_int_allocs++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 else
Pablo Galindo49c75a82018-10-28 15:02:17 +000062 _Py_quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000063#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068maybe_small_long(PyLongObject *v)
69{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020070 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 sdigit ival = MEDIUM_VALUE(v);
animalize6b519982019-09-06 14:00:56 +080072 if (IS_SMALL_INT(ival)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 Py_DECREF(v);
74 return (PyLongObject *)get_small_int(ival);
75 }
76 }
77 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000078}
Guido van Rossumddefaf32007-01-14 03:31:43 +000079#else
animalize6b519982019-09-06 14:00:56 +080080#define IS_SMALL_INT(ival) 0
81#define get_small_int(ival) (Py_UNREACHABLE(), NULL)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000082#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000083#endif
84
Serhiy Storchaka95949422013-08-27 19:40:23 +030085/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000086 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020087Py_LOCAL_INLINE(void)
88_PyLong_Negate(PyLongObject **x_p)
89{
90 PyLongObject *x;
91
92 x = (PyLongObject *)*x_p;
93 if (Py_REFCNT(x) == 1) {
94 Py_SIZE(x) = -Py_SIZE(x);
95 return;
96 }
97
98 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
99 Py_DECREF(x);
100}
101
Serhiy Storchaka95949422013-08-27 19:40:23 +0300102/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +0000103 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +0300104 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +0000105 */
Tim Peters0973b992004-08-29 22:16:50 +0000106#define KARATSUBA_CUTOFF 70
107#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +0000108
Tim Peters47e52ee2004-08-30 02:44:38 +0000109/* For exponentiation, use the binary left-to-right algorithm
110 * unless the exponent contains more than FIVEARY_CUTOFF digits.
111 * In that case, do 5 bits at a time. The potential drawback is that
112 * a table of 2**5 intermediate results is computed.
113 */
114#define FIVEARY_CUTOFF 8
115
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000116#define SIGCHECK(PyTryBlock) \
117 do { \
118 if (PyErr_CheckSignals()) PyTryBlock \
119 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000120
Serhiy Storchaka95949422013-08-27 19:40:23 +0300121/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000122 Doesn't attempt to free the storage--in most cases, due to the nature
123 of the algorithms used, this could save at most be one word anyway. */
124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200126long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200128 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 while (i > 0 && v->ob_digit[i-1] == 0)
132 --i;
133 if (i != j)
134 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
135 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000136}
137
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200138/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
139 using the nb_int slot, if available. Raise TypeError if either the
140 nb_int slot is not available or the result of the call to nb_int
141 returns something not of type int.
142*/
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200143PyObject *
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200144_PyLong_FromNbInt(PyObject *integral)
145{
146 PyNumberMethods *nb;
147 PyObject *result;
148
149 /* Fast path for the case that we already have an int. */
150 if (PyLong_CheckExact(integral)) {
151 Py_INCREF(integral);
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200152 return integral;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200153 }
154
155 nb = Py_TYPE(integral)->tp_as_number;
156 if (nb == NULL || nb->nb_int == NULL) {
157 PyErr_Format(PyExc_TypeError,
158 "an integer is required (got type %.200s)",
159 Py_TYPE(integral)->tp_name);
160 return NULL;
161 }
162
163 /* Convert using the nb_int slot, which should return something
164 of exact type int. */
165 result = nb->nb_int(integral);
166 if (!result || PyLong_CheckExact(result))
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200167 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200168 if (!PyLong_Check(result)) {
169 PyErr_Format(PyExc_TypeError,
170 "__int__ returned non-int (type %.200s)",
171 result->ob_type->tp_name);
172 Py_DECREF(result);
173 return NULL;
174 }
175 /* Issue #17576: warn if 'result' not of exact type int. */
176 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
177 "__int__ returned non-int (type %.200s). "
178 "The ability to return an instance of a strict subclass of int "
179 "is deprecated, and may be removed in a future version of Python.",
180 result->ob_type->tp_name)) {
181 Py_DECREF(result);
182 return NULL;
183 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200184 return result;
185}
186
187/* Convert the given object to a PyLongObject using the nb_index or
188 nb_int slots, if available (the latter is deprecated).
189 Raise TypeError if either nb_index and nb_int slots are not
190 available or the result of the call to nb_index or nb_int
191 returns something not of type int.
192 Should be replaced with PyNumber_Index after the end of the
193 deprecation period.
194*/
195PyObject *
196_PyLong_FromNbIndexOrNbInt(PyObject *integral)
197{
198 PyNumberMethods *nb;
199 PyObject *result;
200
201 /* Fast path for the case that we already have an int. */
202 if (PyLong_CheckExact(integral)) {
203 Py_INCREF(integral);
204 return integral;
205 }
206
207 nb = Py_TYPE(integral)->tp_as_number;
208 if (nb == NULL || (nb->nb_index == NULL && nb->nb_int == NULL)) {
209 PyErr_Format(PyExc_TypeError,
210 "an integer is required (got type %.200s)",
211 Py_TYPE(integral)->tp_name);
212 return NULL;
213 }
214
215 if (nb->nb_index) {
216 /* Convert using the nb_index slot, which should return something
217 of exact type int. */
218 result = nb->nb_index(integral);
219 if (!result || PyLong_CheckExact(result))
220 return result;
221 if (!PyLong_Check(result)) {
222 PyErr_Format(PyExc_TypeError,
223 "__index__ returned non-int (type %.200s)",
224 result->ob_type->tp_name);
225 Py_DECREF(result);
226 return NULL;
227 }
228 /* Issue #17576: warn if 'result' not of exact type int. */
229 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
230 "__index__ returned non-int (type %.200s). "
231 "The ability to return an instance of a strict subclass of int "
232 "is deprecated, and may be removed in a future version of Python.",
233 result->ob_type->tp_name))
234 {
235 Py_DECREF(result);
236 return NULL;
237 }
238 return result;
239 }
240
241 result = _PyLong_FromNbInt(integral);
242 if (result && PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
243 "an integer is required (got type %.200s). "
244 "Implicit conversion to integers using __int__ is deprecated, "
245 "and may be removed in a future version of Python.",
246 Py_TYPE(integral)->tp_name))
247 {
248 Py_DECREF(result);
249 return NULL;
250 }
251 return result;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200252}
253
254
Serhiy Storchaka95949422013-08-27 19:40:23 +0300255/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000256 Return NULL and set exception if we run out of memory. */
257
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000258#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000260
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000261PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000262_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 PyLongObject *result;
265 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
266 sizeof(digit)*size. Previous incarnations of this code used
267 sizeof(PyVarObject) instead of the offsetof, but this risks being
268 incorrect in the presence of padding between the PyVarObject header
269 and the digits. */
270 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
271 PyErr_SetString(PyExc_OverflowError,
272 "too many digits in integer");
273 return NULL;
274 }
275 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
276 size*sizeof(digit));
277 if (!result) {
278 PyErr_NoMemory();
279 return NULL;
280 }
Victor Stinnerb509d522018-11-23 14:27:38 +0100281 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000282}
283
Tim Peters64b5ce32001-09-10 20:52:51 +0000284PyObject *
285_PyLong_Copy(PyLongObject *src)
286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 PyLongObject *result;
288 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 assert(src != NULL);
291 i = Py_SIZE(src);
292 if (i < 0)
293 i = -(i);
294 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100295 sdigit ival = MEDIUM_VALUE(src);
animalize6b519982019-09-06 14:00:56 +0800296 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700297 return get_small_int(ival);
298 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 }
300 result = _PyLong_New(i);
301 if (result != NULL) {
302 Py_SIZE(result) = Py_SIZE(src);
303 while (--i >= 0)
304 result->ob_digit[i] = src->ob_digit[i];
305 }
306 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000307}
308
Serhiy Storchaka95949422013-08-27 19:40:23 +0300309/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000310
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000312PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 PyLongObject *v;
315 unsigned long abs_ival;
316 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
317 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100318 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000319
animalize6b519982019-09-06 14:00:56 +0800320 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -0700321 return get_small_int((sdigit)ival);
322 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (ival < 0) {
325 /* negate: can't write this as abs_ival = -ival since that
326 invokes undefined behaviour when ival is LONG_MIN */
327 abs_ival = 0U-(unsigned long)ival;
328 sign = -1;
329 }
330 else {
331 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100332 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* Fast path for single-digit ints */
336 if (!(abs_ival >> PyLong_SHIFT)) {
337 v = _PyLong_New(1);
338 if (v) {
339 Py_SIZE(v) = sign;
340 v->ob_digit[0] = Py_SAFE_DOWNCAST(
341 abs_ival, unsigned long, digit);
342 }
343 return (PyObject*)v;
344 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000345
Mark Dickinson249b8982009-04-27 19:41:00 +0000346#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 /* 2 digits */
348 if (!(abs_ival >> 2*PyLong_SHIFT)) {
349 v = _PyLong_New(2);
350 if (v) {
351 Py_SIZE(v) = 2*sign;
352 v->ob_digit[0] = Py_SAFE_DOWNCAST(
353 abs_ival & PyLong_MASK, unsigned long, digit);
354 v->ob_digit[1] = Py_SAFE_DOWNCAST(
355 abs_ival >> PyLong_SHIFT, unsigned long, digit);
356 }
357 return (PyObject*)v;
358 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000359#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 /* Larger numbers: loop to determine number of digits */
362 t = abs_ival;
363 while (t) {
364 ++ndigits;
365 t >>= PyLong_SHIFT;
366 }
367 v = _PyLong_New(ndigits);
368 if (v != NULL) {
369 digit *p = v->ob_digit;
370 Py_SIZE(v) = ndigits*sign;
371 t = abs_ival;
372 while (t) {
373 *p++ = Py_SAFE_DOWNCAST(
374 t & PyLong_MASK, unsigned long, digit);
375 t >>= PyLong_SHIFT;
376 }
377 }
378 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000379}
380
Serhiy Storchaka95949422013-08-27 19:40:23 +0300381/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000382
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000383PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000384PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 PyLongObject *v;
387 unsigned long t;
388 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (ival < PyLong_BASE)
391 return PyLong_FromLong(ival);
392 /* Count the number of Python digits. */
orenmn86aa2692017-03-06 10:42:47 +0200393 t = ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 while (t) {
395 ++ndigits;
396 t >>= PyLong_SHIFT;
397 }
398 v = _PyLong_New(ndigits);
399 if (v != NULL) {
400 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 while (ival) {
402 *p++ = (digit)(ival & PyLong_MASK);
403 ival >>= PyLong_SHIFT;
404 }
405 }
406 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000407}
408
Serhiy Storchaka95949422013-08-27 19:40:23 +0300409/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000410
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000411PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 PyLongObject *v;
415 double frac;
416 int i, ndig, expo, neg;
417 neg = 0;
418 if (Py_IS_INFINITY(dval)) {
419 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000420 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 return NULL;
422 }
423 if (Py_IS_NAN(dval)) {
424 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000425 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 return NULL;
427 }
428 if (dval < 0.0) {
429 neg = 1;
430 dval = -dval;
431 }
432 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
433 if (expo <= 0)
434 return PyLong_FromLong(0L);
435 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
436 v = _PyLong_New(ndig);
437 if (v == NULL)
438 return NULL;
439 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
440 for (i = ndig; --i >= 0; ) {
441 digit bits = (digit)frac;
442 v->ob_digit[i] = bits;
443 frac = frac - (double)bits;
444 frac = ldexp(frac, PyLong_SHIFT);
445 }
446 if (neg)
447 Py_SIZE(v) = -(Py_SIZE(v));
448 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000449}
450
Thomas Wouters89f507f2006-12-13 04:49:30 +0000451/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
452 * anything about what happens when a signed integer operation overflows,
453 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700454 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000455 * (unsigned long)LONG_MAX, and for the smallest negative signed long
456 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
457 * However, some other compilers warn about applying unary minus to an
458 * unsigned operand. Hence the weird "0-".
459 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
461#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000462
Serhiy Storchaka95949422013-08-27 19:40:23 +0300463/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100464 method.
465
466 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
467 the result. Otherwise *overflow is 0.
468
469 For other errors (e.g., TypeError), return -1 and set an error condition.
470 In this case *overflow will be 0.
471*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000472
473long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000474PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200477 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 unsigned long x, prev;
479 long res;
480 Py_ssize_t i;
481 int sign;
482 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 *overflow = 0;
485 if (vv == NULL) {
486 PyErr_BadInternalCall();
487 return -1;
488 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000489
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200490 if (PyLong_Check(vv)) {
491 v = (PyLongObject *)vv;
492 }
493 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200494 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200495 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 return -1;
497 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 switch (i) {
504 case -1:
505 res = -(sdigit)v->ob_digit[0];
506 break;
507 case 0:
508 res = 0;
509 break;
510 case 1:
511 res = v->ob_digit[0];
512 break;
513 default:
514 sign = 1;
515 x = 0;
516 if (i < 0) {
517 sign = -1;
518 i = -(i);
519 }
520 while (--i >= 0) {
521 prev = x;
522 x = (x << PyLong_SHIFT) | v->ob_digit[i];
523 if ((x >> PyLong_SHIFT) != prev) {
524 *overflow = sign;
525 goto exit;
526 }
527 }
528 /* Haven't lost any bits, but casting to long requires extra
529 * care (see comment above).
530 */
531 if (x <= (unsigned long)LONG_MAX) {
532 res = (long)x * sign;
533 }
534 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
535 res = LONG_MIN;
536 }
537 else {
538 *overflow = sign;
539 /* res is already set to -1 */
540 }
541 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000542 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200544 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 }
546 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000547}
548
Serhiy Storchaka95949422013-08-27 19:40:23 +0300549/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100550 method. Return -1 and set an error if overflow occurs. */
551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000553PyLong_AsLong(PyObject *obj)
554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 int overflow;
556 long result = PyLong_AsLongAndOverflow(obj, &overflow);
557 if (overflow) {
558 /* XXX: could be cute and give a different
559 message for overflow == -1 */
560 PyErr_SetString(PyExc_OverflowError,
561 "Python int too large to convert to C long");
562 }
563 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000564}
565
Serhiy Storchaka95949422013-08-27 19:40:23 +0300566/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200567 method. Return -1 and set an error if overflow occurs. */
568
569int
570_PyLong_AsInt(PyObject *obj)
571{
572 int overflow;
573 long result = PyLong_AsLongAndOverflow(obj, &overflow);
574 if (overflow || result > INT_MAX || result < INT_MIN) {
575 /* XXX: could be cute and give a different
576 message for overflow == -1 */
577 PyErr_SetString(PyExc_OverflowError,
578 "Python int too large to convert to C int");
579 return -1;
580 }
581 return (int)result;
582}
583
Serhiy Storchaka95949422013-08-27 19:40:23 +0300584/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000585 Returns -1 and sets an error condition if overflow occurs. */
586
587Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000588PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200589 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 size_t x, prev;
591 Py_ssize_t i;
592 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (vv == NULL) {
595 PyErr_BadInternalCall();
596 return -1;
597 }
598 if (!PyLong_Check(vv)) {
599 PyErr_SetString(PyExc_TypeError, "an integer is required");
600 return -1;
601 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 v = (PyLongObject *)vv;
604 i = Py_SIZE(v);
605 switch (i) {
606 case -1: return -(sdigit)v->ob_digit[0];
607 case 0: return 0;
608 case 1: return v->ob_digit[0];
609 }
610 sign = 1;
611 x = 0;
612 if (i < 0) {
613 sign = -1;
614 i = -(i);
615 }
616 while (--i >= 0) {
617 prev = x;
618 x = (x << PyLong_SHIFT) | v->ob_digit[i];
619 if ((x >> PyLong_SHIFT) != prev)
620 goto overflow;
621 }
622 /* Haven't lost any bits, but casting to a signed type requires
623 * extra care (see comment above).
624 */
625 if (x <= (size_t)PY_SSIZE_T_MAX) {
626 return (Py_ssize_t)x * sign;
627 }
628 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
629 return PY_SSIZE_T_MIN;
630 }
631 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000632
Mark Dickinson22b20182010-05-10 21:27:53 +0000633 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 PyErr_SetString(PyExc_OverflowError,
635 "Python int too large to convert to C ssize_t");
636 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000637}
638
Serhiy Storchaka95949422013-08-27 19:40:23 +0300639/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000640 Returns -1 and sets an error condition if overflow occurs. */
641
642unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000643PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000644{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200645 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 unsigned long x, prev;
647 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 if (vv == NULL) {
650 PyErr_BadInternalCall();
651 return (unsigned long)-1;
652 }
653 if (!PyLong_Check(vv)) {
654 PyErr_SetString(PyExc_TypeError, "an integer is required");
655 return (unsigned long)-1;
656 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 v = (PyLongObject *)vv;
659 i = Py_SIZE(v);
660 x = 0;
661 if (i < 0) {
662 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000663 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 return (unsigned long) -1;
665 }
666 switch (i) {
667 case 0: return 0;
668 case 1: return v->ob_digit[0];
669 }
670 while (--i >= 0) {
671 prev = x;
672 x = (x << PyLong_SHIFT) | v->ob_digit[i];
673 if ((x >> PyLong_SHIFT) != prev) {
674 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100675 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000676 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 return (unsigned long) -1;
678 }
679 }
680 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000681}
682
Serhiy Storchaka95949422013-08-27 19:40:23 +0300683/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200684 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000685
686size_t
687PyLong_AsSize_t(PyObject *vv)
688{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200689 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 size_t x, prev;
691 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (vv == NULL) {
694 PyErr_BadInternalCall();
695 return (size_t) -1;
696 }
697 if (!PyLong_Check(vv)) {
698 PyErr_SetString(PyExc_TypeError, "an integer is required");
699 return (size_t)-1;
700 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 v = (PyLongObject *)vv;
703 i = Py_SIZE(v);
704 x = 0;
705 if (i < 0) {
706 PyErr_SetString(PyExc_OverflowError,
707 "can't convert negative value to size_t");
708 return (size_t) -1;
709 }
710 switch (i) {
711 case 0: return 0;
712 case 1: return v->ob_digit[0];
713 }
714 while (--i >= 0) {
715 prev = x;
716 x = (x << PyLong_SHIFT) | v->ob_digit[i];
717 if ((x >> PyLong_SHIFT) != prev) {
718 PyErr_SetString(PyExc_OverflowError,
719 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200720 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 }
722 }
723 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000724}
725
Serhiy Storchaka95949422013-08-27 19:40:23 +0300726/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000727 Returns -1 and sets an error condition if an error occurs. */
728
Guido van Rossumddefaf32007-01-14 03:31:43 +0000729static unsigned long
730_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000731{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200732 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 unsigned long x;
734 Py_ssize_t i;
735 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 if (vv == NULL || !PyLong_Check(vv)) {
738 PyErr_BadInternalCall();
739 return (unsigned long) -1;
740 }
741 v = (PyLongObject *)vv;
742 i = Py_SIZE(v);
743 switch (i) {
744 case 0: return 0;
745 case 1: return v->ob_digit[0];
746 }
747 sign = 1;
748 x = 0;
749 if (i < 0) {
750 sign = -1;
751 i = -i;
752 }
753 while (--i >= 0) {
754 x = (x << PyLong_SHIFT) | v->ob_digit[i];
755 }
756 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000757}
758
Guido van Rossumddefaf32007-01-14 03:31:43 +0000759unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200760PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyLongObject *lo;
763 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000764
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200765 if (op == NULL) {
766 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 return (unsigned long)-1;
768 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000769
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200770 if (PyLong_Check(op)) {
771 return _PyLong_AsUnsignedLongMask(op);
772 }
773
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200774 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 if (lo == NULL)
776 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200777
778 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
779 Py_DECREF(lo);
780 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000781}
782
Tim Peters5b8132f2003-01-31 15:52:05 +0000783int
784_PyLong_Sign(PyObject *vv)
785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 assert(v != NULL);
789 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000792}
793
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200794/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
795 2**k if d is nonzero, else 0. */
796
797static const unsigned char BitLengthTable[32] = {
798 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
799 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
800};
801
802static int
803bits_in_digit(digit d)
804{
805 int d_bits = 0;
806 while (d >= 32) {
807 d_bits += 6;
808 d >>= 6;
809 }
810 d_bits += (int)BitLengthTable[d];
811 return d_bits;
812}
813
Tim Petersbaefd9e2003-01-28 20:37:45 +0000814size_t
815_PyLong_NumBits(PyObject *vv)
816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyLongObject *v = (PyLongObject *)vv;
818 size_t result = 0;
819 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200820 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 assert(v != NULL);
823 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200824 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
826 if (ndigits > 0) {
827 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700828 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100830 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200831 msd_bits = bits_in_digit(msd);
832 if (SIZE_MAX - msd_bits < result)
833 goto Overflow;
834 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 }
836 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000837
Mark Dickinson22b20182010-05-10 21:27:53 +0000838 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
840 "to express in a platform size_t");
841 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000842}
843
Tim Peters2a9b3672001-06-11 21:23:58 +0000844PyObject *
845_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000847{
Mark Dickinson22b20182010-05-10 21:27:53 +0000848 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 int incr; /* direction to move pstartbyte */
850 const unsigned char* pendbyte; /* MSB of bytes */
851 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300852 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyLongObject* v; /* result */
854 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (n == 0)
857 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 if (little_endian) {
860 pstartbyte = bytes;
861 pendbyte = bytes + n - 1;
862 incr = 1;
863 }
864 else {
865 pstartbyte = bytes + n - 1;
866 pendbyte = bytes;
867 incr = -1;
868 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (is_signed)
871 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200874 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 is positive, and leading 0xff bytes if negative. */
876 {
877 size_t i;
878 const unsigned char* p = pendbyte;
879 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000880 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000883 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 break;
885 }
886 numsignificantbytes = n - i;
887 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
888 actually has 2 significant bytes. OTOH, 0xff0001 ==
889 -0x00ffff, so we wouldn't *need* to bump it there; but we
890 do for 0xffff = -0x0001. To be safe without bothering to
891 check every case, bump it regardless. */
892 if (is_signed && numsignificantbytes < n)
893 ++numsignificantbytes;
894 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000895
Serhiy Storchaka95949422013-08-27 19:40:23 +0300896 /* How many Python int digits do we need? We have
897 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
899 /* catch overflow before it happens */
900 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
901 PyErr_SetString(PyExc_OverflowError,
902 "byte array too long to convert to int");
903 return NULL;
904 }
905 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
906 v = _PyLong_New(ndigits);
907 if (v == NULL)
908 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* Copy the bits over. The tricky parts are computing 2's-comp on
911 the fly for signed numbers, and dealing with the mismatch between
912 8-bit bytes and (probably) 15-bit Python digits.*/
913 {
914 size_t i;
915 twodigits carry = 1; /* for 2's-comp calculation */
916 twodigits accum = 0; /* sliding register */
917 unsigned int accumbits = 0; /* number of bits in accum */
918 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
921 twodigits thisbyte = *p;
922 /* Compute correction for 2's comp, if needed. */
923 if (is_signed) {
924 thisbyte = (0xff ^ thisbyte) + carry;
925 carry = thisbyte >> 8;
926 thisbyte &= 0xff;
927 }
928 /* Because we're going LSB to MSB, thisbyte is
929 more significant than what's already in accum,
930 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200931 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 accumbits += 8;
933 if (accumbits >= PyLong_SHIFT) {
934 /* There's enough to fill a Python digit. */
935 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000936 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 ++idigit;
938 accum >>= PyLong_SHIFT;
939 accumbits -= PyLong_SHIFT;
940 assert(accumbits < PyLong_SHIFT);
941 }
942 }
943 assert(accumbits < PyLong_SHIFT);
944 if (accumbits) {
945 assert(idigit < ndigits);
946 v->ob_digit[idigit] = (digit)accum;
947 ++idigit;
948 }
949 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 Py_SIZE(v) = is_signed ? -idigit : idigit;
952 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000953}
954
955int
956_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 unsigned char* bytes, size_t n,
958 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000961 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000963 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
965 digit carry; /* for computing 2's-comp */
966 size_t j; /* # bytes filled */
967 unsigned char* p; /* pointer to next byte in bytes */
968 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 if (Py_SIZE(v) < 0) {
973 ndigits = -(Py_SIZE(v));
974 if (!is_signed) {
975 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000976 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 return -1;
978 }
979 do_twos_comp = 1;
980 }
981 else {
982 ndigits = Py_SIZE(v);
983 do_twos_comp = 0;
984 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (little_endian) {
987 p = bytes;
988 pincr = 1;
989 }
990 else {
991 p = bytes + n - 1;
992 pincr = -1;
993 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 /* Copy over all the Python digits.
996 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300997 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 normalized. */
999 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
1000 j = 0;
1001 accum = 0;
1002 accumbits = 0;
1003 carry = do_twos_comp ? 1 : 0;
1004 for (i = 0; i < ndigits; ++i) {
1005 digit thisdigit = v->ob_digit[i];
1006 if (do_twos_comp) {
1007 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
1008 carry = thisdigit >> PyLong_SHIFT;
1009 thisdigit &= PyLong_MASK;
1010 }
1011 /* Because we're going LSB to MSB, thisdigit is more
1012 significant than what's already in accum, so needs to be
1013 prepended to accum. */
1014 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 /* The most-significant digit may be (probably is) at least
1017 partly empty. */
1018 if (i == ndigits - 1) {
1019 /* Count # of sign bits -- they needn't be stored,
1020 * although for signed conversion we need later to
1021 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +00001022 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 while (s != 0) {
1024 s >>= 1;
1025 accumbits++;
1026 }
1027 }
1028 else
1029 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 /* Store as many bytes as possible. */
1032 while (accumbits >= 8) {
1033 if (j >= n)
1034 goto Overflow;
1035 ++j;
1036 *p = (unsigned char)(accum & 0xff);
1037 p += pincr;
1038 accumbits -= 8;
1039 accum >>= 8;
1040 }
1041 }
Tim Peters2a9b3672001-06-11 21:23:58 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 /* Store the straggler (if any). */
1044 assert(accumbits < 8);
1045 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1046 if (accumbits > 0) {
1047 if (j >= n)
1048 goto Overflow;
1049 ++j;
1050 if (do_twos_comp) {
1051 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +03001052 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 infinite supply of sign bits). */
1054 accum |= (~(twodigits)0) << accumbits;
1055 }
1056 *p = (unsigned char)(accum & 0xff);
1057 p += pincr;
1058 }
1059 else if (j == n && n > 0 && is_signed) {
1060 /* The main loop filled the byte array exactly, so the code
1061 just above didn't get to ensure there's a sign bit, and the
1062 loop below wouldn't add one either. Make sure a sign bit
1063 exists. */
1064 unsigned char msb = *(p - pincr);
1065 int sign_bit_set = msb >= 0x80;
1066 assert(accumbits == 0);
1067 if (sign_bit_set == do_twos_comp)
1068 return 0;
1069 else
1070 goto Overflow;
1071 }
Tim Peters05607ad2001-06-13 21:01:27 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 /* Fill remaining bytes with copies of the sign bit. */
1074 {
1075 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1076 for ( ; j < n; ++j, p += pincr)
1077 *p = signbyte;
1078 }
Tim Peters05607ad2001-06-13 21:01:27 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001081
Mark Dickinson22b20182010-05-10 21:27:53 +00001082 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1084 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001085
Tim Peters2a9b3672001-06-11 21:23:58 +00001086}
1087
Serhiy Storchaka95949422013-08-27 19:40:23 +03001088/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001089
1090PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001091PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001092{
Mark Dickinson91044792012-10-18 19:21:43 +01001093#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001094 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001095#else
1096
Tim Peters70128a12001-06-16 08:48:40 +00001097#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001098# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001099#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001100 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001101#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001102
Guido van Rossum78694d91998-09-18 14:14:13 +00001103}
1104
Serhiy Storchaka95949422013-08-27 19:40:23 +03001105/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001106
1107void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001108PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001109{
Tim Peters70128a12001-06-16 08:48:40 +00001110#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1114 x = PyLong_AsLong(vv);
1115 else
1116 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001117#else
Tim Peters70128a12001-06-16 08:48:40 +00001118
Tim Peters70128a12001-06-16 08:48:40 +00001119#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001120# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001121#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001122 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1125 x = PyLong_AsLongLong(vv);
1126 else
1127 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001128
1129#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (x == -1 && PyErr_Occurred())
1132 return NULL;
1133 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001134}
1135
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001136/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001137 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001138 */
1139
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001140#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001141
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001142/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001143
1144PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001145PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001148 unsigned long long abs_ival;
1149 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 int ndigits = 0;
1151 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001152
animalize6b519982019-09-06 14:00:56 +08001153 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001154 return get_small_int((sdigit)ival);
1155 }
1156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (ival < 0) {
1158 /* avoid signed overflow on negation; see comments
1159 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001160 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 negative = 1;
1162 }
1163 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001164 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 /* Count the number of Python digits.
1168 We used to pick 5 ("big enough for anything"), but that's a
1169 waste of time and space given that 5*15 = 75 bits are rarely
1170 needed. */
1171 t = abs_ival;
1172 while (t) {
1173 ++ndigits;
1174 t >>= PyLong_SHIFT;
1175 }
1176 v = _PyLong_New(ndigits);
1177 if (v != NULL) {
1178 digit *p = v->ob_digit;
1179 Py_SIZE(v) = negative ? -ndigits : ndigits;
1180 t = abs_ival;
1181 while (t) {
1182 *p++ = (digit)(t & PyLong_MASK);
1183 t >>= PyLong_SHIFT;
1184 }
1185 }
1186 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001187}
1188
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001189/* Create a new int object from a C unsigned long long int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001190
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001191PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001192PyLong_FromUnsignedLongLong(unsigned long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001195 unsigned long long t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 if (ival < PyLong_BASE)
1199 return PyLong_FromLong((long)ival);
1200 /* Count the number of Python digits. */
orenmn86aa2692017-03-06 10:42:47 +02001201 t = ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 while (t) {
1203 ++ndigits;
1204 t >>= PyLong_SHIFT;
1205 }
1206 v = _PyLong_New(ndigits);
1207 if (v != NULL) {
1208 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 while (ival) {
1210 *p++ = (digit)(ival & PyLong_MASK);
1211 ival >>= PyLong_SHIFT;
1212 }
1213 }
1214 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001215}
1216
Serhiy Storchaka95949422013-08-27 19:40:23 +03001217/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001218
1219PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001220PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 PyLongObject *v;
1223 size_t abs_ival;
1224 size_t t; /* unsigned so >> doesn't propagate sign bit */
1225 int ndigits = 0;
1226 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001227
animalize6b519982019-09-06 14:00:56 +08001228 if (IS_SMALL_INT(ival)) {
Greg Price5e63ab02019-08-24 10:19:37 -07001229 return get_small_int((sdigit)ival);
1230 }
1231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (ival < 0) {
1233 /* avoid signed overflow when ival = SIZE_T_MIN */
1234 abs_ival = (size_t)(-1-ival)+1;
1235 negative = 1;
1236 }
1237 else {
1238 abs_ival = (size_t)ival;
1239 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 /* Count the number of Python digits. */
1242 t = abs_ival;
1243 while (t) {
1244 ++ndigits;
1245 t >>= PyLong_SHIFT;
1246 }
1247 v = _PyLong_New(ndigits);
1248 if (v != NULL) {
1249 digit *p = v->ob_digit;
1250 Py_SIZE(v) = negative ? -ndigits : ndigits;
1251 t = abs_ival;
1252 while (t) {
1253 *p++ = (digit)(t & PyLong_MASK);
1254 t >>= PyLong_SHIFT;
1255 }
1256 }
1257 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001258}
1259
Serhiy Storchaka95949422013-08-27 19:40:23 +03001260/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001261
1262PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001263PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 PyLongObject *v;
1266 size_t t;
1267 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (ival < PyLong_BASE)
1270 return PyLong_FromLong((long)ival);
1271 /* Count the number of Python digits. */
1272 t = ival;
1273 while (t) {
1274 ++ndigits;
1275 t >>= PyLong_SHIFT;
1276 }
1277 v = _PyLong_New(ndigits);
1278 if (v != NULL) {
1279 digit *p = v->ob_digit;
1280 Py_SIZE(v) = ndigits;
1281 while (ival) {
1282 *p++ = (digit)(ival & PyLong_MASK);
1283 ival >>= PyLong_SHIFT;
1284 }
1285 }
1286 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001287}
1288
Serhiy Storchaka95949422013-08-27 19:40:23 +03001289/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001290 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001291
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001292long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001293PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001296 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001298 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 if (vv == NULL) {
1301 PyErr_BadInternalCall();
1302 return -1;
1303 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001304
1305 if (PyLong_Check(vv)) {
1306 v = (PyLongObject *)vv;
1307 }
1308 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001309 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001310 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001312 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001314
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001315 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001317 case -1:
1318 bytes = -(sdigit)v->ob_digit[0];
1319 break;
1320 case 0:
1321 bytes = 0;
1322 break;
1323 case 1:
1324 bytes = v->ob_digit[0];
1325 break;
1326 default:
1327 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001328 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001330 if (do_decref) {
1331 Py_DECREF(v);
1332 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001333
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001334 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001336 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 else
1338 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001339}
1340
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001341/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001342 Return -1 and set an error if overflow occurs. */
1343
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001344unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001345PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001348 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001350
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001351 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001353 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001355 if (!PyLong_Check(vv)) {
1356 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001357 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001358 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 v = (PyLongObject*)vv;
1361 switch(Py_SIZE(v)) {
1362 case 0: return 0;
1363 case 1: return v->ob_digit[0];
1364 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001365
Mark Dickinson22b20182010-05-10 21:27:53 +00001366 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001367 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001368
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001369 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001371 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 else
1373 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001374}
Tim Petersd1a7da62001-06-13 00:35:57 +00001375
Serhiy Storchaka95949422013-08-27 19:40:23 +03001376/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001377 Returns -1 and sets an error condition if an error occurs. */
1378
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001379static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001380_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001381{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001382 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001383 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 Py_ssize_t i;
1385 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (vv == NULL || !PyLong_Check(vv)) {
1388 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001389 return (unsigned long long) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 }
1391 v = (PyLongObject *)vv;
1392 switch(Py_SIZE(v)) {
1393 case 0: return 0;
1394 case 1: return v->ob_digit[0];
1395 }
1396 i = Py_SIZE(v);
1397 sign = 1;
1398 x = 0;
1399 if (i < 0) {
1400 sign = -1;
1401 i = -i;
1402 }
1403 while (--i >= 0) {
1404 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1405 }
1406 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001407}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001408
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001409unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001410PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001413 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001414
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001415 if (op == NULL) {
1416 PyErr_BadInternalCall();
Zackery Spytzdc247652019-06-06 14:39:23 -06001417 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001419
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001420 if (PyLong_Check(op)) {
1421 return _PyLong_AsUnsignedLongLongMask(op);
1422 }
1423
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001424 lo = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001426 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001427
1428 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1429 Py_DECREF(lo);
1430 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001431}
Tim Petersd1a7da62001-06-13 00:35:57 +00001432
Serhiy Storchaka95949422013-08-27 19:40:23 +03001433/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001434 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001435
Mark Dickinson8d48b432011-10-23 20:47:14 +01001436 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1437 the result. Otherwise *overflow is 0.
1438
1439 For other errors (e.g., TypeError), return -1 and set an error condition.
1440 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001441*/
1442
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001443long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001444PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001447 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001448 unsigned long long x, prev;
1449 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 Py_ssize_t i;
1451 int sign;
1452 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 *overflow = 0;
1455 if (vv == NULL) {
1456 PyErr_BadInternalCall();
1457 return -1;
1458 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001459
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001460 if (PyLong_Check(vv)) {
1461 v = (PyLongObject *)vv;
1462 }
1463 else {
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001464 v = (PyLongObject *)_PyLong_FromNbIndexOrNbInt(vv);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001465 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 return -1;
1467 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 switch (i) {
1474 case -1:
1475 res = -(sdigit)v->ob_digit[0];
1476 break;
1477 case 0:
1478 res = 0;
1479 break;
1480 case 1:
1481 res = v->ob_digit[0];
1482 break;
1483 default:
1484 sign = 1;
1485 x = 0;
1486 if (i < 0) {
1487 sign = -1;
1488 i = -(i);
1489 }
1490 while (--i >= 0) {
1491 prev = x;
1492 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1493 if ((x >> PyLong_SHIFT) != prev) {
1494 *overflow = sign;
1495 goto exit;
1496 }
1497 }
1498 /* Haven't lost any bits, but casting to long requires extra
1499 * care (see comment above).
1500 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001501 if (x <= (unsigned long long)PY_LLONG_MAX) {
1502 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 }
1504 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1505 res = PY_LLONG_MIN;
1506 }
1507 else {
1508 *overflow = sign;
1509 /* res is already set to -1 */
1510 }
1511 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001512 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001514 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 }
1516 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001517}
1518
Serhiy Storchaka7cb7bcf2018-07-26 13:22:16 +03001519int
1520_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1521{
1522 unsigned long uval;
1523
1524 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1525 PyErr_SetString(PyExc_ValueError, "value must be positive");
1526 return 0;
1527 }
1528 uval = PyLong_AsUnsignedLong(obj);
1529 if (uval == (unsigned long)-1 && PyErr_Occurred())
1530 return 0;
1531 if (uval > USHRT_MAX) {
1532 PyErr_SetString(PyExc_OverflowError,
1533 "Python int too large for C unsigned short");
1534 return 0;
1535 }
1536
1537 *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1538 return 1;
1539}
1540
1541int
1542_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1543{
1544 unsigned long uval;
1545
1546 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1547 PyErr_SetString(PyExc_ValueError, "value must be positive");
1548 return 0;
1549 }
1550 uval = PyLong_AsUnsignedLong(obj);
1551 if (uval == (unsigned long)-1 && PyErr_Occurred())
1552 return 0;
1553 if (uval > UINT_MAX) {
1554 PyErr_SetString(PyExc_OverflowError,
1555 "Python int too large for C unsigned int");
1556 return 0;
1557 }
1558
1559 *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1560 return 1;
1561}
1562
1563int
1564_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1565{
1566 unsigned long uval;
1567
1568 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1569 PyErr_SetString(PyExc_ValueError, "value must be positive");
1570 return 0;
1571 }
1572 uval = PyLong_AsUnsignedLong(obj);
1573 if (uval == (unsigned long)-1 && PyErr_Occurred())
1574 return 0;
1575
1576 *(unsigned long *)ptr = uval;
1577 return 1;
1578}
1579
1580int
1581_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1582{
1583 unsigned long long uval;
1584
1585 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1586 PyErr_SetString(PyExc_ValueError, "value must be positive");
1587 return 0;
1588 }
1589 uval = PyLong_AsUnsignedLongLong(obj);
1590 if (uval == (unsigned long long)-1 && PyErr_Occurred())
1591 return 0;
1592
1593 *(unsigned long long *)ptr = uval;
1594 return 1;
1595}
1596
1597int
1598_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1599{
1600 size_t uval;
1601
1602 if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1603 PyErr_SetString(PyExc_ValueError, "value must be positive");
1604 return 0;
1605 }
1606 uval = PyLong_AsSize_t(obj);
1607 if (uval == (size_t)-1 && PyErr_Occurred())
1608 return 0;
1609
1610 *(size_t *)ptr = uval;
1611 return 1;
1612}
1613
1614
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001615#define CHECK_BINOP(v,w) \
1616 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001617 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1618 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001619 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001620
Tim Peters877a2122002-08-12 05:09:36 +00001621/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1622 * is modified in place, by adding y to it. Carries are propagated as far as
1623 * x[m-1], and the remaining carry (0 or 1) is returned.
1624 */
1625static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001626v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 Py_ssize_t i;
1629 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 assert(m >= n);
1632 for (i = 0; i < n; ++i) {
1633 carry += x[i] + y[i];
1634 x[i] = carry & PyLong_MASK;
1635 carry >>= PyLong_SHIFT;
1636 assert((carry & 1) == carry);
1637 }
1638 for (; carry && i < m; ++i) {
1639 carry += x[i];
1640 x[i] = carry & PyLong_MASK;
1641 carry >>= PyLong_SHIFT;
1642 assert((carry & 1) == carry);
1643 }
1644 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001645}
1646
1647/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1648 * is modified in place, by subtracting y from it. Borrows are propagated as
1649 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1650 */
1651static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001652v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 Py_ssize_t i;
1655 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 assert(m >= n);
1658 for (i = 0; i < n; ++i) {
1659 borrow = x[i] - y[i] - borrow;
1660 x[i] = borrow & PyLong_MASK;
1661 borrow >>= PyLong_SHIFT;
1662 borrow &= 1; /* keep only 1 sign bit */
1663 }
1664 for (; borrow && i < m; ++i) {
1665 borrow = x[i] - borrow;
1666 x[i] = borrow & PyLong_MASK;
1667 borrow >>= PyLong_SHIFT;
1668 borrow &= 1;
1669 }
1670 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001671}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001672
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001673/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1674 * result in z[0:m], and return the d bits shifted out of the top.
1675 */
1676static digit
1677v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 Py_ssize_t i;
1680 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 assert(0 <= d && d < PyLong_SHIFT);
1683 for (i=0; i < m; i++) {
1684 twodigits acc = (twodigits)a[i] << d | carry;
1685 z[i] = (digit)acc & PyLong_MASK;
1686 carry = (digit)(acc >> PyLong_SHIFT);
1687 }
1688 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001689}
1690
1691/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1692 * result in z[0:m], and return the d bits shifted out of the bottom.
1693 */
1694static digit
1695v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 Py_ssize_t i;
1698 digit carry = 0;
1699 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 assert(0 <= d && d < PyLong_SHIFT);
1702 for (i=m; i-- > 0;) {
1703 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1704 carry = (digit)acc & mask;
1705 z[i] = (digit)(acc >> d);
1706 }
1707 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001708}
1709
Tim Peters212e6142001-07-14 12:23:19 +00001710/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1711 in pout, and returning the remainder. pin and pout point at the LSD.
1712 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001713 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001714 immutable. */
1715
1716static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001717inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 assert(n > 0 && n <= PyLong_MASK);
1722 pin += size;
1723 pout += size;
1724 while (--size >= 0) {
1725 digit hi;
1726 rem = (rem << PyLong_SHIFT) | *--pin;
1727 *--pout = hi = (digit)(rem / n);
1728 rem -= (twodigits)hi * n;
1729 }
1730 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001731}
1732
Serhiy Storchaka95949422013-08-27 19:40:23 +03001733/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001734 (as function result) and the remainder (through *prem).
1735 The sign of a is ignored; n should not be zero. */
1736
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001737static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001738divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001739{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001740 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 assert(n > 0 && n <= PyLong_MASK);
1744 z = _PyLong_New(size);
1745 if (z == NULL)
1746 return NULL;
1747 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1748 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001749}
1750
Serhiy Storchaka95949422013-08-27 19:40:23 +03001751/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001752 string. (Return value is non-shared so that callers can modify the
1753 returned value if necessary.) */
1754
Victor Stinnerd3f08822012-05-29 12:57:52 +02001755static int
1756long_to_decimal_string_internal(PyObject *aa,
1757 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001758 _PyUnicodeWriter *writer,
1759 _PyBytesWriter *bytes_writer,
1760 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001763 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 Py_ssize_t size, strlen, size_a, i, j;
1765 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001767 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001768 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 a = (PyLongObject *)aa;
1771 if (a == NULL || !PyLong_Check(a)) {
1772 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001773 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001775 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 /* quick and dirty upper bound for the number of digits
1779 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 But log2(a) < size_a * PyLong_SHIFT, and
1784 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001785 > 3.3 * _PyLong_DECIMAL_SHIFT
1786
1787 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1788 size_a + size_a / d < size_a + size_a / floor(d),
1789 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1790 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001792 d = (33 * _PyLong_DECIMAL_SHIFT) /
1793 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1794 assert(size_a < PY_SSIZE_T_MAX/2);
1795 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 scratch = _PyLong_New(size);
1797 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001798 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 /* convert array of base _PyLong_BASE digits in pin to an array of
1801 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1802 Volume 2 (3rd edn), section 4.4, Method 1b). */
1803 pin = a->ob_digit;
1804 pout = scratch->ob_digit;
1805 size = 0;
1806 for (i = size_a; --i >= 0; ) {
1807 digit hi = pin[i];
1808 for (j = 0; j < size; j++) {
1809 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1810 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1811 pout[j] = (digit)(z - (twodigits)hi *
1812 _PyLong_DECIMAL_BASE);
1813 }
1814 while (hi) {
1815 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1816 hi /= _PyLong_DECIMAL_BASE;
1817 }
1818 /* check for keyboard interrupt */
1819 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001820 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001821 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001822 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 }
1824 /* pout should have at least one digit, so that the case when a = 0
1825 works correctly */
1826 if (size == 0)
1827 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 /* calculate exact length of output string, and allocate */
1830 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1831 tenpow = 10;
1832 rem = pout[size-1];
1833 while (rem >= tenpow) {
1834 tenpow *= 10;
1835 strlen++;
1836 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001837 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001838 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1839 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001840 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001841 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001842 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001844 else if (bytes_writer) {
1845 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1846 if (*bytes_str == NULL) {
1847 Py_DECREF(scratch);
1848 return -1;
1849 }
1850 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001851 else {
1852 str = PyUnicode_New(strlen, '9');
1853 if (str == NULL) {
1854 Py_DECREF(scratch);
1855 return -1;
1856 }
1857 kind = PyUnicode_KIND(str);
1858 }
1859
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001860#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001861 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001862 /* pout[0] through pout[size-2] contribute exactly \
1863 _PyLong_DECIMAL_SHIFT digits each */ \
1864 for (i=0; i < size - 1; i++) { \
1865 rem = pout[i]; \
1866 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1867 *--p = '0' + rem % 10; \
1868 rem /= 10; \
1869 } \
1870 } \
1871 /* pout[size-1]: always produce at least one decimal digit */ \
1872 rem = pout[i]; \
1873 do { \
1874 *--p = '0' + rem % 10; \
1875 rem /= 10; \
1876 } while (rem != 0); \
1877 \
1878 /* and sign */ \
1879 if (negative) \
1880 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001881 } while (0)
1882
1883#define WRITE_UNICODE_DIGITS(TYPE) \
1884 do { \
1885 if (writer) \
1886 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1887 else \
1888 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1889 \
1890 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001891 \
1892 /* check we've counted correctly */ \
1893 if (writer) \
1894 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1895 else \
1896 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1897 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001900 if (bytes_writer) {
1901 char *p = *bytes_str + strlen;
1902 WRITE_DIGITS(p);
1903 assert(p == *bytes_str);
1904 }
1905 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001906 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001907 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001909 else if (kind == PyUnicode_2BYTE_KIND) {
1910 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001911 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001912 }
1913 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001914 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001915 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001916 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917 }
1918#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001919#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001922 if (writer) {
1923 writer->pos += strlen;
1924 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001925 else if (bytes_writer) {
1926 (*bytes_str) += strlen;
1927 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001928 else {
1929 assert(_PyUnicode_CheckConsistency(str, 1));
1930 *p_output = (PyObject *)str;
1931 }
1932 return 0;
1933}
1934
1935static PyObject *
1936long_to_decimal_string(PyObject *aa)
1937{
1938 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001939 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001940 return NULL;
1941 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001942}
1943
Serhiy Storchaka95949422013-08-27 19:40:23 +03001944/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001945 which should be one of 2, 8 or 16. Return a string object.
1946 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1947 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001948
Victor Stinnerd3f08822012-05-29 12:57:52 +02001949static int
1950long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001951 PyObject **p_output, _PyUnicodeWriter *writer,
1952 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001953{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001954 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001955 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001956 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001958 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001959 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001961
Victor Stinnerd3f08822012-05-29 12:57:52 +02001962 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (a == NULL || !PyLong_Check(a)) {
1964 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001965 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001967 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001968 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 /* Compute a rough upper bound for the length of the string */
1971 switch (base) {
1972 case 16:
1973 bits = 4;
1974 break;
1975 case 8:
1976 bits = 3;
1977 break;
1978 case 2:
1979 bits = 1;
1980 break;
1981 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001982 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001984
Mark Dickinsone2846542012-04-20 21:21:24 +01001985 /* Compute exact length 'sz' of output string. */
1986 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001987 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001988 }
1989 else {
1990 Py_ssize_t size_a_in_bits;
1991 /* Ensure overflow doesn't occur during computation of sz. */
1992 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1993 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001994 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001995 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001996 }
1997 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1998 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001999 /* Allow 1 character for a '-' sign. */
2000 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
2001 }
2002 if (alternate) {
2003 /* 2 characters for prefix */
2004 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01002005 }
2006
Victor Stinnerd3f08822012-05-29 12:57:52 +02002007 if (writer) {
2008 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
2009 return -1;
2010 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 }
Victor Stinner199c9a62015-10-14 09:47:23 +02002012 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002013 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
2014 if (*bytes_str == NULL)
2015 return -1;
2016 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002018 v = PyUnicode_New(sz, 'x');
2019 if (v == NULL)
2020 return -1;
2021 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00002023
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002024#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002025 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002026 if (size_a == 0) { \
2027 *--p = '0'; \
2028 } \
2029 else { \
2030 /* JRH: special case for power-of-2 bases */ \
2031 twodigits accum = 0; \
2032 int accumbits = 0; /* # of bits in accum */ \
2033 Py_ssize_t i; \
2034 for (i = 0; i < size_a; ++i) { \
2035 accum |= (twodigits)a->ob_digit[i] << accumbits; \
2036 accumbits += PyLong_SHIFT; \
2037 assert(accumbits >= bits); \
2038 do { \
2039 char cdigit; \
2040 cdigit = (char)(accum & (base - 1)); \
2041 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
2042 *--p = cdigit; \
2043 accumbits -= bits; \
2044 accum >>= bits; \
2045 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
2046 } \
2047 } \
2048 \
2049 if (alternate) { \
2050 if (base == 16) \
2051 *--p = 'x'; \
2052 else if (base == 8) \
2053 *--p = 'o'; \
2054 else /* (base == 2) */ \
2055 *--p = 'b'; \
2056 *--p = '0'; \
2057 } \
2058 if (negative) \
2059 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002060 } while (0)
2061
2062#define WRITE_UNICODE_DIGITS(TYPE) \
2063 do { \
2064 if (writer) \
2065 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
2066 else \
2067 p = (TYPE*)PyUnicode_DATA(v) + sz; \
2068 \
2069 WRITE_DIGITS(p); \
2070 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02002071 if (writer) \
2072 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2073 else \
2074 assert(p == (TYPE*)PyUnicode_DATA(v)); \
2075 } while (0)
2076
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002077 if (bytes_writer) {
2078 char *p = *bytes_str + sz;
2079 WRITE_DIGITS(p);
2080 assert(p == *bytes_str);
2081 }
2082 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002083 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002084 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002085 }
2086 else if (kind == PyUnicode_2BYTE_KIND) {
2087 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002088 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002089 }
2090 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02002091 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02002092 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002093 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002094 }
2095#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002096#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02002097
2098 if (writer) {
2099 writer->pos += sz;
2100 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002101 else if (bytes_writer) {
2102 (*bytes_str) += sz;
2103 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02002104 else {
2105 assert(_PyUnicode_CheckConsistency(v, 1));
2106 *p_output = v;
2107 }
2108 return 0;
2109}
2110
2111PyObject *
2112_PyLong_Format(PyObject *obj, int base)
2113{
2114 PyObject *str;
2115 int err;
2116 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002117 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002118 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002119 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002120 if (err == -1)
2121 return NULL;
2122 return str;
2123}
2124
2125int
2126_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2127 PyObject *obj,
2128 int base, int alternate)
2129{
2130 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002131 return long_to_decimal_string_internal(obj, NULL, writer,
2132 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002133 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02002134 return long_format_binary(obj, base, alternate, NULL, writer,
2135 NULL, NULL);
2136}
2137
2138char*
2139_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2140 PyObject *obj,
2141 int base, int alternate)
2142{
2143 char *str2;
2144 int res;
2145 str2 = str;
2146 if (base == 10)
2147 res = long_to_decimal_string_internal(obj, NULL, NULL,
2148 writer, &str2);
2149 else
2150 res = long_format_binary(obj, base, alternate, NULL, NULL,
2151 writer, &str2);
2152 if (res < 0)
2153 return NULL;
2154 assert(str2 != NULL);
2155 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002156}
2157
Thomas Wouters477c8d52006-05-27 19:21:47 +00002158/* Table of digit values for 8-bit string -> integer conversion.
2159 * '0' maps to 0, ..., '9' maps to 9.
2160 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2161 * All other indices map to 37.
2162 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002163 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002164 */
Raymond Hettinger35631532009-01-09 03:58:09 +00002165unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2167 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2168 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2169 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2170 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2171 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2172 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2173 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2174 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2175 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2176 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2177 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 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,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002182};
2183
2184/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002185 * 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 +03002186 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002187 * The point to this routine is that it takes time linear in the number of
2188 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002189 *
2190 * Return values:
2191 * -1 on syntax error (exception needs to be set, *res is untouched)
2192 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002193 */
Brett Cannona721aba2016-09-09 14:57:09 -07002194static int
2195long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002196{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002197 const char *p = *str;
2198 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002199 char prev = 0;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002200 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 int bits_per_char;
2202 Py_ssize_t n;
2203 PyLongObject *z;
2204 twodigits accum;
2205 int bits_in_accum;
2206 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2209 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002210 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002212 }
2213 /* count digits and set p to end-of-string */
2214 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2215 if (*p == '_') {
2216 if (prev == '_') {
2217 *str = p - 1;
2218 return -1;
2219 }
2220 } else {
2221 ++digits;
2222 }
2223 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002225 }
2226 if (prev == '_') {
2227 /* Trailing underscore not allowed. */
2228 *str = p - 1;
2229 return -1;
2230 }
2231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002233 /* n <- the number of Python digits needed,
2234 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2235 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 PyErr_SetString(PyExc_ValueError,
2237 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002238 *res = NULL;
2239 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002241 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002243 if (z == NULL) {
2244 *res = NULL;
2245 return 0;
2246 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002247 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 * from least to most significant in both.
2249 */
2250 accum = 0;
2251 bits_in_accum = 0;
2252 pdigit = z->ob_digit;
2253 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002254 int k;
2255 if (*p == '_') {
2256 continue;
2257 }
2258 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 assert(k >= 0 && k < base);
2260 accum |= (twodigits)k << bits_in_accum;
2261 bits_in_accum += bits_per_char;
2262 if (bits_in_accum >= PyLong_SHIFT) {
2263 *pdigit++ = (digit)(accum & PyLong_MASK);
2264 assert(pdigit - z->ob_digit <= n);
2265 accum >>= PyLong_SHIFT;
2266 bits_in_accum -= PyLong_SHIFT;
2267 assert(bits_in_accum < PyLong_SHIFT);
2268 }
2269 }
2270 if (bits_in_accum) {
2271 assert(bits_in_accum <= PyLong_SHIFT);
2272 *pdigit++ = (digit)accum;
2273 assert(pdigit - z->ob_digit <= n);
2274 }
2275 while (pdigit - z->ob_digit < n)
2276 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002277 *res = long_normalize(z);
2278 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002279}
2280
Serhiy Storchaka95949422013-08-27 19:40:23 +03002281/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002282 * ignored.
2283 *
2284 * If successful, a PyLong object will be returned and 'pend' will be pointing
2285 * to the first unused byte unless it's NULL.
2286 *
2287 * If unsuccessful, NULL will be returned.
2288 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002289PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002290PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002293 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 PyLongObject *z = NULL;
2295 PyObject *strobj;
2296 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 if ((base != 0 && base < 2) || base > 36) {
2299 PyErr_SetString(PyExc_ValueError,
2300 "int() arg 2 must be >= 2 and <= 36");
2301 return NULL;
2302 }
Brett Cannona721aba2016-09-09 14:57:09 -07002303 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002305 }
2306 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002308 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 else if (*str == '-') {
2310 ++str;
2311 sign = -1;
2312 }
2313 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002314 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002316 }
2317 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002319 }
2320 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002322 }
2323 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002325 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 else {
2327 /* "old" (C-style) octal literal, now invalid.
2328 it might still be zero though */
2329 error_if_nonzero = 1;
2330 base = 10;
2331 }
2332 }
2333 if (str[0] == '0' &&
2334 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2335 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002336 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002338 /* One underscore allowed here. */
2339 if (*str == '_') {
2340 ++str;
2341 }
2342 }
2343 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002344 /* May not start with underscores. */
2345 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002346 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002349 if ((base & (base - 1)) == 0) {
2350 int res = long_from_binary_base(&str, base, &z);
2351 if (res < 0) {
2352 /* Syntax error. */
2353 goto onError;
2354 }
2355 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002357/***
2358Binary bases can be converted in time linear in the number of digits, because
2359Python's representation base is binary. Other bases (including decimal!) use
2360the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002361
Thomas Wouters477c8d52006-05-27 19:21:47 +00002362First some math: the largest integer that can be expressed in N base-B digits
2363is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2364case number of Python digits needed to hold it is the smallest integer n s.t.
2365
2366 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2367 BASE**n >= B**N [taking logs to base BASE]
2368 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2369
2370The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002371this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002372and the result is computed into it.
2373
2374The input string is actually treated as being in base base**i (i.e., i digits
2375are processed at a time), where two more static arrays hold:
2376
2377 convwidth_base[base] = the largest integer i such that base**i <= BASE
2378 convmultmax_base[base] = base ** convwidth_base[base]
2379
2380The first of these is the largest i such that i consecutive input digits
2381must fit in a single Python digit. The second is effectively the input
2382base we're really using.
2383
2384Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2385convmultmax_base[base], the result is "simply"
2386
2387 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2388
2389where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002390
2391Error analysis: as above, the number of Python digits `n` needed is worst-
2392case
2393
2394 n >= N * log(B)/log(BASE)
2395
2396where `N` is the number of input digits in base `B`. This is computed via
2397
2398 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2399
2400below. Two numeric concerns are how much space this can waste, and whether
2401the computed result can be too small. To be concrete, assume BASE = 2**15,
2402which is the default (and it's unlikely anyone changes that).
2403
2404Waste isn't a problem: provided the first input digit isn't 0, the difference
2405between the worst-case input with N digits and the smallest input with N
2406digits is about a factor of B, but B is small compared to BASE so at most
2407one allocated Python digit can remain unused on that count. If
2408N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2409and adding 1 returns a result 1 larger than necessary. However, that can't
2410happen: whenever B is a power of 2, long_from_binary_base() is called
2411instead, and it's impossible for B**i to be an integer power of 2**15 when
2412B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2413an exact integer when B is not a power of 2, since B**i has a prime factor
2414other than 2 in that case, but (2**15)**j's only prime factor is 2).
2415
2416The computed result can be too small if the true value of N*log(B)/log(BASE)
2417is a little bit larger than an exact integer, but due to roundoff errors (in
2418computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2419yields a numeric result a little less than that integer. Unfortunately, "how
2420close can a transcendental function get to an integer over some range?"
2421questions are generally theoretically intractable. Computer analysis via
2422continued fractions is practical: expand log(B)/log(BASE) via continued
2423fractions, giving a sequence i/j of "the best" rational approximations. Then
2424j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2425we can get very close to being in trouble, but very rarely. For example,
242676573 is a denominator in one of the continued-fraction approximations to
2427log(10)/log(2**15), and indeed:
2428
2429 >>> log(10)/log(2**15)*76573
2430 16958.000000654003
2431
2432is very close to an integer. If we were working with IEEE single-precision,
2433rounding errors could kill us. Finding worst cases in IEEE double-precision
2434requires better-than-double-precision log() functions, and Tim didn't bother.
2435Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002436new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002437This should happen extremely rarely, and in fact I don't have a test case
2438that triggers it(!). Instead the code was tested by artificially allocating
2439just 1 digit at the start, so that the copying code was exercised for every
2440digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002441***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002442 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 Py_ssize_t size_z;
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002444 Py_ssize_t digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 int i;
2446 int convwidth;
2447 twodigits convmultmax, convmult;
2448 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002449 const char *scan, *lastdigit;
2450 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 static double log_base_BASE[37] = {0.0e0,};
2453 static int convwidth_base[37] = {0,};
2454 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 if (log_base_BASE[base] == 0.0) {
2457 twodigits convmax = base;
2458 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002459
Mark Dickinson22b20182010-05-10 21:27:53 +00002460 log_base_BASE[base] = (log((double)base) /
2461 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 for (;;) {
2463 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002464 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002466 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 convmax = next;
2468 ++i;
2469 }
2470 convmultmax_base[base] = convmax;
2471 assert(i > 0);
2472 convwidth_base[base] = i;
2473 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 /* Find length of the string of numeric characters. */
2476 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002477 lastdigit = str;
2478
2479 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2480 if (*scan == '_') {
2481 if (prev == '_') {
2482 /* Only one underscore allowed. */
2483 str = lastdigit + 1;
2484 goto onError;
2485 }
2486 }
2487 else {
2488 ++digits;
2489 lastdigit = scan;
2490 }
2491 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002493 }
2494 if (prev == '_') {
2495 /* Trailing underscore not allowed. */
2496 /* Set error pointer to first underscore. */
2497 str = lastdigit + 1;
2498 goto onError;
2499 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002500
Serhiy Storchaka95949422013-08-27 19:40:23 +03002501 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 * integer with this base and length. Note that there's no
2503 * need to initialize z->ob_digit -- no slot is read up before
2504 * being stored into.
2505 */
Victor Stinnerdd431b32017-12-08 00:06:55 +01002506 double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2507 if (fsize_z > (double)MAX_LONG_DIGITS) {
Serhiy Storchaka29ba6882017-12-03 22:16:21 +02002508 /* The same exception as in _PyLong_New(). */
2509 PyErr_SetString(PyExc_OverflowError,
2510 "too many digits in integer");
2511 return NULL;
2512 }
2513 size_z = (Py_ssize_t)fsize_z;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 /* Uncomment next line to test exceedingly rare copy code */
2515 /* size_z = 1; */
2516 assert(size_z > 0);
2517 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002518 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002520 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 /* `convwidth` consecutive input digits are treated as a single
2524 * digit in base `convmultmax`.
2525 */
2526 convwidth = convwidth_base[base];
2527 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 /* Work ;-) */
2530 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002531 if (*str == '_') {
2532 str++;
2533 continue;
2534 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 /* grab up to convwidth digits from the input string */
2536 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002537 for (i = 1; i < convwidth && str != scan; ++str) {
2538 if (*str == '_') {
2539 continue;
2540 }
2541 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002543 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 assert(c < PyLong_BASE);
2545 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 convmult = convmultmax;
2548 /* Calculate the shift only if we couldn't get
2549 * convwidth digits.
2550 */
2551 if (i != convwidth) {
2552 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002553 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 /* Multiply z by convmult, and add c. */
2559 pz = z->ob_digit;
2560 pzstop = pz + Py_SIZE(z);
2561 for (; pz < pzstop; ++pz) {
2562 c += (twodigits)*pz * convmult;
2563 *pz = (digit)(c & PyLong_MASK);
2564 c >>= PyLong_SHIFT;
2565 }
2566 /* carry off the current end? */
2567 if (c) {
2568 assert(c < PyLong_BASE);
2569 if (Py_SIZE(z) < size_z) {
2570 *pz = (digit)c;
2571 ++Py_SIZE(z);
2572 }
2573 else {
2574 PyLongObject *tmp;
2575 /* Extremely rare. Get more space. */
2576 assert(Py_SIZE(z) == size_z);
2577 tmp = _PyLong_New(size_z + 1);
2578 if (tmp == NULL) {
2579 Py_DECREF(z);
2580 return NULL;
2581 }
2582 memcpy(tmp->ob_digit,
2583 z->ob_digit,
2584 sizeof(digit) * size_z);
2585 Py_DECREF(z);
2586 z = tmp;
2587 z->ob_digit[size_z] = (digit)c;
2588 ++size_z;
2589 }
2590 }
2591 }
2592 }
Brett Cannona721aba2016-09-09 14:57:09 -07002593 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002595 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 if (error_if_nonzero) {
2597 /* reset the base to 0, else the exception message
2598 doesn't make too much sense */
2599 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002600 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002602 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 /* there might still be other problems, therefore base
2604 remains zero here for the same reason */
2605 }
Brett Cannona721aba2016-09-09 14:57:09 -07002606 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002608 }
2609 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002611 }
2612 while (*str && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002614 }
2615 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002617 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002619 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002620 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002621 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002622 }
2623 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002624 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002625 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002626 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002627
Mark Dickinson22b20182010-05-10 21:27:53 +00002628 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002629 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002630 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002631 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 Py_XDECREF(z);
2633 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2634 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002635 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002637 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002639 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 base, strobj);
2641 Py_DECREF(strobj);
2642 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002643}
2644
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002645/* Since PyLong_FromString doesn't have a length parameter,
2646 * check here for possible NULs in the string.
2647 *
2648 * Reports an invalid literal as a bytes object.
2649 */
2650PyObject *
2651_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2652{
2653 PyObject *result, *strobj;
2654 char *end = NULL;
2655
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002656 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002657 if (end == NULL || (result != NULL && end == s + len))
2658 return result;
2659 Py_XDECREF(result);
2660 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2661 if (strobj != NULL) {
2662 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002663 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002664 base, strobj);
2665 Py_DECREF(strobj);
2666 }
2667 return NULL;
2668}
2669
Guido van Rossum9e896b32000-04-05 20:11:21 +00002670PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002671PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002672{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002673 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002674 if (unicode == NULL)
2675 return NULL;
2676 v = PyLong_FromUnicodeObject(unicode, base);
2677 Py_DECREF(unicode);
2678 return v;
2679}
2680
2681PyObject *
2682PyLong_FromUnicodeObject(PyObject *u, int base)
2683{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002684 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002685 const char *buffer;
2686 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002687 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002690 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002692 assert(PyUnicode_IS_ASCII(asciidig));
2693 /* Simply get a pointer to existing ASCII characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002694 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002695 assert(buffer != NULL);
2696
2697 result = PyLong_FromString(buffer, &end, base);
2698 if (end == NULL || (result != NULL && end == buffer + buflen)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002699 Py_DECREF(asciidig);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002700 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002702 Py_DECREF(asciidig);
2703 Py_XDECREF(result);
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002704 PyErr_Format(PyExc_ValueError,
2705 "invalid literal for int() with base %d: %.200R",
2706 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002707 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002708}
2709
Tim Peters9f688bf2000-07-07 15:53:28 +00002710/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002711static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 (PyLongObject *, PyLongObject *, PyLongObject **);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002713static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002714
Serhiy Storchaka95949422013-08-27 19:40:23 +03002715/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002716
Guido van Rossume32e0141992-01-19 16:31:05 +00002717static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002718long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002720{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002721 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 if (size_b == 0) {
2725 PyErr_SetString(PyExc_ZeroDivisionError,
2726 "integer division or modulo by zero");
2727 return -1;
2728 }
2729 if (size_a < size_b ||
2730 (size_a == size_b &&
2731 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2732 /* |a| < |b|. */
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03002733 *prem = (PyLongObject *)long_long((PyObject *)a);
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002734 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002735 return -1;
2736 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002737 Py_INCREF(_PyLong_Zero);
2738 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 return 0;
2740 }
2741 if (size_b == 1) {
2742 digit rem = 0;
2743 z = divrem1(a, b->ob_digit[0], &rem);
2744 if (z == NULL)
2745 return -1;
2746 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2747 if (*prem == NULL) {
2748 Py_DECREF(z);
2749 return -1;
2750 }
2751 }
2752 else {
2753 z = x_divrem(a, b, prem);
2754 if (z == NULL)
2755 return -1;
2756 }
2757 /* Set the signs.
2758 The quotient z has the sign of a*b;
2759 the remainder r has the sign of a,
2760 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002761 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2762 _PyLong_Negate(&z);
2763 if (z == NULL) {
2764 Py_CLEAR(*prem);
2765 return -1;
2766 }
2767 }
2768 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2769 _PyLong_Negate(prem);
2770 if (*prem == NULL) {
2771 Py_DECREF(z);
2772 Py_CLEAR(*prem);
2773 return -1;
2774 }
2775 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 *pdiv = maybe_small_long(z);
2777 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002778}
2779
Serhiy Storchaka95949422013-08-27 19:40:23 +03002780/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002781 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002782
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002783static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002784x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 PyLongObject *v, *w, *a;
2787 Py_ssize_t i, k, size_v, size_w;
2788 int d;
2789 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2790 twodigits vv;
2791 sdigit zhi;
2792 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2795 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2796 handle the special case when the initial estimate q for a quotient
2797 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2798 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002801 size_v = Py_ABS(Py_SIZE(v1));
2802 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2804 v = _PyLong_New(size_v+1);
2805 if (v == NULL) {
2806 *prem = NULL;
2807 return NULL;
2808 }
2809 w = _PyLong_New(size_w);
2810 if (w == NULL) {
2811 Py_DECREF(v);
2812 *prem = NULL;
2813 return NULL;
2814 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2817 shift v1 left by the same amount. Results go into w and v. */
2818 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2819 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2820 assert(carry == 0);
2821 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2822 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2823 v->ob_digit[size_v] = carry;
2824 size_v++;
2825 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2828 at most (and usually exactly) k = size_v - size_w digits. */
2829 k = size_v - size_w;
2830 assert(k >= 0);
2831 a = _PyLong_New(k);
2832 if (a == NULL) {
2833 Py_DECREF(w);
2834 Py_DECREF(v);
2835 *prem = NULL;
2836 return NULL;
2837 }
2838 v0 = v->ob_digit;
2839 w0 = w->ob_digit;
2840 wm1 = w0[size_w-1];
2841 wm2 = w0[size_w-2];
2842 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2843 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2844 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002847 Py_DECREF(a);
2848 Py_DECREF(w);
2849 Py_DECREF(v);
2850 *prem = NULL;
2851 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002852 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 /* estimate quotient digit q; may overestimate by 1 (rare) */
2855 vtop = vk[size_w];
2856 assert(vtop <= wm1);
2857 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2858 q = (digit)(vv / wm1);
2859 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2860 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2861 | vk[size_w-2])) {
2862 --q;
2863 r += wm1;
2864 if (r >= PyLong_BASE)
2865 break;
2866 }
2867 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2870 zhi = 0;
2871 for (i = 0; i < size_w; ++i) {
2872 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2873 -PyLong_BASE * q <= z < PyLong_BASE */
2874 z = (sdigit)vk[i] + zhi -
2875 (stwodigits)q * (stwodigits)w0[i];
2876 vk[i] = (digit)z & PyLong_MASK;
2877 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002878 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 /* add w back if q was too large (this branch taken rarely) */
2882 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2883 if ((sdigit)vtop + zhi < 0) {
2884 carry = 0;
2885 for (i = 0; i < size_w; ++i) {
2886 carry += vk[i] + w0[i];
2887 vk[i] = carry & PyLong_MASK;
2888 carry >>= PyLong_SHIFT;
2889 }
2890 --q;
2891 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 /* store quotient digit */
2894 assert(q < PyLong_BASE);
2895 *--ak = q;
2896 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 /* unshift remainder; we reuse w to store the result */
2899 carry = v_rshift(w0, v0, size_w, d);
2900 assert(carry==0);
2901 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 *prem = long_normalize(w);
2904 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002905}
2906
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002907/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2908 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2909 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2910 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2911 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2912 -1.0. */
2913
2914/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2915#if DBL_MANT_DIG == 53
2916#define EXP2_DBL_MANT_DIG 9007199254740992.0
2917#else
2918#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2919#endif
2920
2921double
2922_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2925 /* See below for why x_digits is always large enough. */
2926 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2927 double dx;
2928 /* Correction term for round-half-to-even rounding. For a digit x,
2929 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2930 multiple of 4, rounding ties to a multiple of 8. */
2931 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002932
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002933 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 if (a_size == 0) {
2935 /* Special case for 0: significand 0.0, exponent 0. */
2936 *e = 0;
2937 return 0.0;
2938 }
2939 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2940 /* The following is an overflow-free version of the check
2941 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2942 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2943 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2944 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002945 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2949 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 Number of digits needed for result: write // for floor division.
2952 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2961 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2964 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2965 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 in both cases.
2972 */
2973 if (a_bits <= DBL_MANT_DIG + 2) {
2974 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2975 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2976 x_size = 0;
2977 while (x_size < shift_digits)
2978 x_digits[x_size++] = 0;
2979 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2980 (int)shift_bits);
2981 x_size += a_size;
2982 x_digits[x_size++] = rem;
2983 }
2984 else {
2985 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2986 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2987 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2988 a_size - shift_digits, (int)shift_bits);
2989 x_size = a_size - shift_digits;
2990 /* For correct rounding below, we need the least significant
2991 bit of x to be 'sticky' for this shift: if any of the bits
2992 shifted out was nonzero, we set the least significant bit
2993 of x. */
2994 if (rem)
2995 x_digits[0] |= 1;
2996 else
2997 while (shift_digits > 0)
2998 if (a->ob_digit[--shift_digits]) {
2999 x_digits[0] |= 1;
3000 break;
3001 }
3002 }
Victor Stinner63941882011-09-29 00:42:28 +02003003 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 /* Round, and convert to double. */
3006 x_digits[0] += half_even_correction[x_digits[0] & 7];
3007 dx = x_digits[--x_size];
3008 while (x_size > 0)
3009 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 /* Rescale; make correction if result is 1.0. */
3012 dx /= 4.0 * EXP2_DBL_MANT_DIG;
3013 if (dx == 1.0) {
3014 if (a_bits == PY_SSIZE_T_MAX)
3015 goto overflow;
3016 dx = 0.5;
3017 a_bits += 1;
3018 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 *e = a_bits;
3021 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003022
3023 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 /* exponent > PY_SSIZE_T_MAX */
3025 PyErr_SetString(PyExc_OverflowError,
3026 "huge integer: number of bits overflows a Py_ssize_t");
3027 *e = 0;
3028 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003029}
3030
Serhiy Storchaka95949422013-08-27 19:40:23 +03003031/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003032 using the round-half-to-even rule in the case of a tie. */
3033
3034double
3035PyLong_AsDouble(PyObject *v)
3036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 Py_ssize_t exponent;
3038 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003039
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02003040 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 PyErr_BadInternalCall();
3042 return -1.0;
3043 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02003044 if (!PyLong_Check(v)) {
3045 PyErr_SetString(PyExc_TypeError, "an integer is required");
3046 return -1.0;
3047 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05003048 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05003049 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01003050 to double. This improves performance of FP/long operations
3051 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05003052 */
3053 return (double)MEDIUM_VALUE((PyLongObject *)v);
3054 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
3056 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
3057 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01003058 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 return -1.0;
3060 }
3061 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00003062}
3063
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003064/* Methods */
3065
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003066static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003067long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 if (Py_SIZE(a) != Py_SIZE(b)) {
3072 sign = Py_SIZE(a) - Py_SIZE(b);
3073 }
3074 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003075 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3077 ;
3078 if (i < 0)
3079 sign = 0;
3080 else {
3081 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
3082 if (Py_SIZE(a) < 0)
3083 sign = -sign;
3084 }
3085 }
3086 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003087}
3088
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003089static PyObject *
3090long_richcompare(PyObject *self, PyObject *other, int op)
3091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 CHECK_BINOP(self, other);
3094 if (self == other)
3095 result = 0;
3096 else
3097 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
stratakise8b19652017-11-02 11:32:54 +01003098 Py_RETURN_RICHCOMPARE(result, 0, op);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003099}
3100
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003101static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00003102long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00003103{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003104 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 Py_ssize_t i;
3106 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 i = Py_SIZE(v);
3109 switch(i) {
3110 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
3111 case 0: return 0;
3112 case 1: return v->ob_digit[0];
3113 }
3114 sign = 1;
3115 x = 0;
3116 if (i < 0) {
3117 sign = -1;
3118 i = -(i);
3119 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00003121 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3122 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3123 _PyHASH_MODULUS.
3124
3125 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3126 amounts to a rotation of the bits of x. To see this, write
3127
3128 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3129
3130 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3131 PyLong_SHIFT bits of x (those that are shifted out of the
3132 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3133 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3134 bits of x, shifted up. Then since 2**_PyHASH_BITS is
3135 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3136 congruent to y modulo _PyHASH_MODULUS. So
3137
3138 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3139
3140 The right-hand side is just the result of rotating the
3141 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3142 not all _PyHASH_BITS bits of x are 1s, the same is true
3143 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3144 the reduction of x*2**PyLong_SHIFT modulo
3145 _PyHASH_MODULUS. */
3146 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3147 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003149 if (x >= _PyHASH_MODULUS)
3150 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 }
3152 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003153 if (x == (Py_uhash_t)-1)
3154 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003155 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003156}
3157
3158
Serhiy Storchaka95949422013-08-27 19:40:23 +03003159/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003160
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003161static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003162x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003163{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003164 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 PyLongObject *z;
3166 Py_ssize_t i;
3167 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 /* Ensure a is the larger of the two: */
3170 if (size_a < size_b) {
3171 { PyLongObject *temp = a; a = b; b = temp; }
3172 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003173 size_a = size_b;
3174 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 }
3176 z = _PyLong_New(size_a+1);
3177 if (z == NULL)
3178 return NULL;
3179 for (i = 0; i < size_b; ++i) {
3180 carry += a->ob_digit[i] + b->ob_digit[i];
3181 z->ob_digit[i] = carry & PyLong_MASK;
3182 carry >>= PyLong_SHIFT;
3183 }
3184 for (; i < size_a; ++i) {
3185 carry += a->ob_digit[i];
3186 z->ob_digit[i] = carry & PyLong_MASK;
3187 carry >>= PyLong_SHIFT;
3188 }
3189 z->ob_digit[i] = carry;
3190 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003191}
3192
3193/* Subtract the absolute values of two integers. */
3194
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003195static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003196x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003197{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003198 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 PyLongObject *z;
3200 Py_ssize_t i;
3201 int sign = 1;
3202 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 /* Ensure a is the larger of the two: */
3205 if (size_a < size_b) {
3206 sign = -1;
3207 { PyLongObject *temp = a; a = b; b = temp; }
3208 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003209 size_a = size_b;
3210 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 }
3212 else if (size_a == size_b) {
3213 /* Find highest digit where a and b differ: */
3214 i = size_a;
3215 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3216 ;
3217 if (i < 0)
3218 return (PyLongObject *)PyLong_FromLong(0);
3219 if (a->ob_digit[i] < b->ob_digit[i]) {
3220 sign = -1;
3221 { PyLongObject *temp = a; a = b; b = temp; }
3222 }
3223 size_a = size_b = i+1;
3224 }
3225 z = _PyLong_New(size_a);
3226 if (z == NULL)
3227 return NULL;
3228 for (i = 0; i < size_b; ++i) {
3229 /* The following assumes unsigned arithmetic
3230 works module 2**N for some N>PyLong_SHIFT. */
3231 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3232 z->ob_digit[i] = borrow & PyLong_MASK;
3233 borrow >>= PyLong_SHIFT;
3234 borrow &= 1; /* Keep only one sign bit */
3235 }
3236 for (; i < size_a; ++i) {
3237 borrow = a->ob_digit[i] - borrow;
3238 z->ob_digit[i] = borrow & PyLong_MASK;
3239 borrow >>= PyLong_SHIFT;
3240 borrow &= 1; /* Keep only one sign bit */
3241 }
3242 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003243 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003244 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003245 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003247}
3248
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003249static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003250long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003255
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003256 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003257 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 }
3259 if (Py_SIZE(a) < 0) {
3260 if (Py_SIZE(b) < 0) {
3261 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003262 if (z != NULL) {
3263 /* x_add received at least one multiple-digit int,
3264 and thus z must be a multiple-digit int.
3265 That also means z is not an element of
3266 small_ints, so negating it in-place is safe. */
3267 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003269 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 }
3271 else
3272 z = x_sub(b, a);
3273 }
3274 else {
3275 if (Py_SIZE(b) < 0)
3276 z = x_sub(a, b);
3277 else
3278 z = x_add(a, b);
3279 }
3280 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003281}
3282
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003283static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003284long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003289
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003290 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003291 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 }
3293 if (Py_SIZE(a) < 0) {
3294 if (Py_SIZE(b) < 0)
3295 z = x_sub(a, b);
3296 else
3297 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003298 if (z != NULL) {
3299 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003301 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 }
3303 else {
3304 if (Py_SIZE(b) < 0)
3305 z = x_add(a, b);
3306 else
3307 z = x_sub(a, b);
3308 }
3309 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003310}
3311
Tim Peters5af4e6c2002-08-12 02:31:19 +00003312/* Grade school multiplication, ignoring the signs.
3313 * Returns the absolute value of the product, or NULL if error.
3314 */
3315static PyLongObject *
3316x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003319 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3320 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 z = _PyLong_New(size_a + size_b);
3324 if (z == NULL)
3325 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3328 if (a == b) {
3329 /* Efficient squaring per HAC, Algorithm 14.16:
3330 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3331 * Gives slightly less than a 2x speedup when a == b,
3332 * via exploiting that each entry in the multiplication
3333 * pyramid appears twice (except for the size_a squares).
3334 */
3335 for (i = 0; i < size_a; ++i) {
3336 twodigits carry;
3337 twodigits f = a->ob_digit[i];
3338 digit *pz = z->ob_digit + (i << 1);
3339 digit *pa = a->ob_digit + i + 1;
3340 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003343 Py_DECREF(z);
3344 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003345 });
Tim Peters0973b992004-08-29 22:16:50 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 carry = *pz + f * f;
3348 *pz++ = (digit)(carry & PyLong_MASK);
3349 carry >>= PyLong_SHIFT;
3350 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 /* Now f is added in twice in each column of the
3353 * pyramid it appears. Same as adding f<<1 once.
3354 */
3355 f <<= 1;
3356 while (pa < paend) {
3357 carry += *pz + *pa++ * f;
3358 *pz++ = (digit)(carry & PyLong_MASK);
3359 carry >>= PyLong_SHIFT;
3360 assert(carry <= (PyLong_MASK << 1));
3361 }
3362 if (carry) {
3363 carry += *pz;
3364 *pz++ = (digit)(carry & PyLong_MASK);
3365 carry >>= PyLong_SHIFT;
3366 }
3367 if (carry)
3368 *pz += (digit)(carry & PyLong_MASK);
3369 assert((carry >> PyLong_SHIFT) == 0);
3370 }
3371 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003372 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 for (i = 0; i < size_a; ++i) {
3374 twodigits carry = 0;
3375 twodigits f = a->ob_digit[i];
3376 digit *pz = z->ob_digit + i;
3377 digit *pb = b->ob_digit;
3378 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003381 Py_DECREF(z);
3382 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003383 });
Tim Peters0973b992004-08-29 22:16:50 +00003384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 while (pb < pbend) {
3386 carry += *pz + *pb++ * f;
3387 *pz++ = (digit)(carry & PyLong_MASK);
3388 carry >>= PyLong_SHIFT;
3389 assert(carry <= PyLong_MASK);
3390 }
3391 if (carry)
3392 *pz += (digit)(carry & PyLong_MASK);
3393 assert((carry >> PyLong_SHIFT) == 0);
3394 }
3395 }
3396 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003397}
3398
3399/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003400 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003401 split, and sets low and high such that abs(n) == (high << size) + low,
3402 viewing the shift as being by digits. The sign bit is ignored, and
3403 the return values are >= 0.
3404 Returns 0 on success, -1 on failure.
3405*/
3406static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003407kmul_split(PyLongObject *n,
3408 Py_ssize_t size,
3409 PyLongObject **high,
3410 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 PyLongObject *hi, *lo;
3413 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003414 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003415
Victor Stinner640c35c2013-06-04 23:14:37 +02003416 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 if ((hi = _PyLong_New(size_hi)) == NULL)
3420 return -1;
3421 if ((lo = _PyLong_New(size_lo)) == NULL) {
3422 Py_DECREF(hi);
3423 return -1;
3424 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3427 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 *high = long_normalize(hi);
3430 *low = long_normalize(lo);
3431 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003432}
3433
Tim Peters60004642002-08-12 22:01:34 +00003434static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3435
Tim Peters5af4e6c2002-08-12 02:31:19 +00003436/* Karatsuba multiplication. Ignores the input signs, and returns the
3437 * absolute value of the product (or NULL if error).
3438 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3439 */
3440static PyLongObject *
3441k_mul(PyLongObject *a, PyLongObject *b)
3442{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003443 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3444 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 PyLongObject *ah = NULL;
3446 PyLongObject *al = NULL;
3447 PyLongObject *bh = NULL;
3448 PyLongObject *bl = NULL;
3449 PyLongObject *ret = NULL;
3450 PyLongObject *t1, *t2, *t3;
3451 Py_ssize_t shift; /* the number of digits we split off */
3452 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3455 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3456 * Then the original product is
3457 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3458 * By picking X to be a power of 2, "*X" is just shifting, and it's
3459 * been reduced to 3 multiplies on numbers half the size.
3460 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 /* We want to split based on the larger number; fiddle so that b
3463 * is largest.
3464 */
3465 if (asize > bsize) {
3466 t1 = a;
3467 a = b;
3468 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 i = asize;
3471 asize = bsize;
3472 bsize = i;
3473 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 /* Use gradeschool math when either number is too small. */
3476 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3477 if (asize <= i) {
3478 if (asize == 0)
3479 return (PyLongObject *)PyLong_FromLong(0);
3480 else
3481 return x_mul(a, b);
3482 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 /* If a is small compared to b, splitting on b gives a degenerate
3485 * case with ah==0, and Karatsuba may be (even much) less efficient
3486 * than "grade school" then. However, we can still win, by viewing
3487 * b as a string of "big digits", each of width a->ob_size. That
3488 * leads to a sequence of balanced calls to k_mul.
3489 */
3490 if (2 * asize <= bsize)
3491 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 /* Split a & b into hi & lo pieces. */
3494 shift = bsize >> 1;
3495 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3496 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 if (a == b) {
3499 bh = ah;
3500 bl = al;
3501 Py_INCREF(bh);
3502 Py_INCREF(bl);
3503 }
3504 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 /* The plan:
3507 * 1. Allocate result space (asize + bsize digits: that's always
3508 * enough).
3509 * 2. Compute ah*bh, and copy into result at 2*shift.
3510 * 3. Compute al*bl, and copy into result at 0. Note that this
3511 * can't overlap with #2.
3512 * 4. Subtract al*bl from the result, starting at shift. This may
3513 * underflow (borrow out of the high digit), but we don't care:
3514 * we're effectively doing unsigned arithmetic mod
3515 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3516 * borrows and carries out of the high digit can be ignored.
3517 * 5. Subtract ah*bh from the result, starting at shift.
3518 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3519 * at shift.
3520 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 /* 1. Allocate result space. */
3523 ret = _PyLong_New(asize + bsize);
3524 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003525#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 /* Fill with trash, to catch reference to uninitialized digits. */
3527 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003528#endif
Tim Peters44121a62002-08-12 06:17:58 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3531 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3532 assert(Py_SIZE(t1) >= 0);
3533 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3534 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3535 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 /* Zero-out the digits higher than the ah*bh copy. */
3538 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3539 if (i)
3540 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3541 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 /* 3. t2 <- al*bl, and copy into the low digits. */
3544 if ((t2 = k_mul(al, bl)) == NULL) {
3545 Py_DECREF(t1);
3546 goto fail;
3547 }
3548 assert(Py_SIZE(t2) >= 0);
3549 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3550 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 /* Zero out remaining digits. */
3553 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3554 if (i)
3555 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3558 * because it's fresher in cache.
3559 */
3560 i = Py_SIZE(ret) - shift; /* # digits after shift */
3561 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3562 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3565 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3568 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3569 Py_DECREF(ah);
3570 Py_DECREF(al);
3571 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 if (a == b) {
3574 t2 = t1;
3575 Py_INCREF(t2);
3576 }
3577 else if ((t2 = x_add(bh, bl)) == NULL) {
3578 Py_DECREF(t1);
3579 goto fail;
3580 }
3581 Py_DECREF(bh);
3582 Py_DECREF(bl);
3583 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 t3 = k_mul(t1, t2);
3586 Py_DECREF(t1);
3587 Py_DECREF(t2);
3588 if (t3 == NULL) goto fail;
3589 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 /* Add t3. It's not obvious why we can't run out of room here.
3592 * See the (*) comment after this function.
3593 */
3594 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3595 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003598
Mark Dickinson22b20182010-05-10 21:27:53 +00003599 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 Py_XDECREF(ret);
3601 Py_XDECREF(ah);
3602 Py_XDECREF(al);
3603 Py_XDECREF(bh);
3604 Py_XDECREF(bl);
3605 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003606}
3607
Tim Petersd6974a52002-08-13 20:37:51 +00003608/* (*) Why adding t3 can't "run out of room" above.
3609
Tim Petersab86c2b2002-08-15 20:06:00 +00003610Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3611to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003612
Tim Petersab86c2b2002-08-15 20:06:00 +000036131. For any integer i, i = c(i/2) + f(i/2). In particular,
3614 bsize = c(bsize/2) + f(bsize/2).
36152. shift = f(bsize/2)
36163. asize <= bsize
36174. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3618 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003619
Tim Petersab86c2b2002-08-15 20:06:00 +00003620We allocated asize + bsize result digits, and add t3 into them at an offset
3621of shift. This leaves asize+bsize-shift allocated digit positions for t3
3622to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3623asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003624
Tim Petersab86c2b2002-08-15 20:06:00 +00003625bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3626at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003627
Tim Petersab86c2b2002-08-15 20:06:00 +00003628If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3629digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3630most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003631
Tim Petersab86c2b2002-08-15 20:06:00 +00003632The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003633
Tim Petersab86c2b2002-08-15 20:06:00 +00003634 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003635
Tim Petersab86c2b2002-08-15 20:06:00 +00003636and we have asize + c(bsize/2) available digit positions. We need to show
3637this is always enough. An instance of c(bsize/2) cancels out in both, so
3638the question reduces to whether asize digits is enough to hold
3639(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3640then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3641asize 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 +00003642digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003643asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003644c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3645is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3646bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003647
Tim Peters48d52c02002-08-14 17:07:32 +00003648Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3649clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3650ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003651*/
3652
Tim Peters60004642002-08-12 22:01:34 +00003653/* b has at least twice the digits of a, and a is big enough that Karatsuba
3654 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3655 * of slices, each with a->ob_size digits, and multiply the slices by a,
3656 * one at a time. This gives k_mul balanced inputs to work with, and is
3657 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003658 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003659 * single-width slice overlap between successive partial sums).
3660 */
3661static PyLongObject *
3662k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3663{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003664 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3665 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 Py_ssize_t nbdone; /* # of b digits already multiplied */
3667 PyLongObject *ret;
3668 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 assert(asize > KARATSUBA_CUTOFF);
3671 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 /* Allocate result space, and zero it out. */
3674 ret = _PyLong_New(asize + bsize);
3675 if (ret == NULL)
3676 return NULL;
3677 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 /* Successive slices of b are copied into bslice. */
3680 bslice = _PyLong_New(asize);
3681 if (bslice == NULL)
3682 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 nbdone = 0;
3685 while (bsize > 0) {
3686 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003687 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 /* Multiply the next slice of b by a. */
3690 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3691 nbtouse * sizeof(digit));
3692 Py_SIZE(bslice) = nbtouse;
3693 product = k_mul(a, bslice);
3694 if (product == NULL)
3695 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 /* Add into result. */
3698 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3699 product->ob_digit, Py_SIZE(product));
3700 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 bsize -= nbtouse;
3703 nbdone += nbtouse;
3704 }
Tim Peters60004642002-08-12 22:01:34 +00003705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 Py_DECREF(bslice);
3707 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003708
Mark Dickinson22b20182010-05-10 21:27:53 +00003709 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 Py_DECREF(ret);
3711 Py_XDECREF(bslice);
3712 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003713}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003714
3715static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003716long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003723 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003725 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 z = k_mul(a, b);
3729 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003730 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3731 _PyLong_Negate(&z);
3732 if (z == NULL)
3733 return NULL;
3734 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003736}
3737
Yury Selivanove0b23092016-02-11 10:26:27 -05003738/* Fast modulo division for single-digit longs. */
3739static PyObject *
3740fast_mod(PyLongObject *a, PyLongObject *b)
3741{
3742 sdigit left = a->ob_digit[0];
3743 sdigit right = b->ob_digit[0];
3744 sdigit mod;
3745
3746 assert(Py_ABS(Py_SIZE(a)) == 1);
3747 assert(Py_ABS(Py_SIZE(b)) == 1);
3748
3749 if (Py_SIZE(a) == Py_SIZE(b)) {
3750 /* 'a' and 'b' have the same sign. */
3751 mod = left % right;
3752 }
3753 else {
3754 /* Either 'a' or 'b' is negative. */
3755 mod = right - 1 - (left - 1) % right;
3756 }
3757
Victor Stinnerf963c132016-03-23 18:36:54 +01003758 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003759}
3760
3761/* Fast floor division for single-digit longs. */
3762static PyObject *
3763fast_floor_div(PyLongObject *a, PyLongObject *b)
3764{
3765 sdigit left = a->ob_digit[0];
3766 sdigit right = b->ob_digit[0];
3767 sdigit div;
3768
3769 assert(Py_ABS(Py_SIZE(a)) == 1);
3770 assert(Py_ABS(Py_SIZE(b)) == 1);
3771
3772 if (Py_SIZE(a) == Py_SIZE(b)) {
3773 /* 'a' and 'b' have the same sign. */
3774 div = left / right;
3775 }
3776 else {
3777 /* Either 'a' or 'b' is negative. */
3778 div = -1 - (left - 1) / right;
3779 }
3780
3781 return PyLong_FromLong(div);
3782}
3783
Guido van Rossume32e0141992-01-19 16:31:05 +00003784/* The / and % operators are now defined in terms of divmod().
3785 The expression a mod b has the value a - b*floor(a/b).
3786 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003787 |a| by |b|, with the sign of a. This is also expressed
3788 as a - b*trunc(a/b), if trunc truncates towards zero.
3789 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 a b a rem b a mod b
3791 13 10 3 3
3792 -13 10 -3 7
3793 13 -10 3 -7
3794 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003795 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003796 have different signs. We then subtract one from the 'div'
3797 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003798
Tim Peters47e52ee2004-08-30 02:44:38 +00003799/* Compute
3800 * *pdiv, *pmod = divmod(v, w)
3801 * NULL can be passed for pdiv or pmod, in which case that part of
3802 * the result is simply thrown away. The caller owns a reference to
3803 * each of these it requests (does not pass NULL for).
3804 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003805static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003806l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003810
Yury Selivanove0b23092016-02-11 10:26:27 -05003811 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3812 /* Fast path for single-digit longs */
3813 div = NULL;
3814 if (pdiv != NULL) {
3815 div = (PyLongObject *)fast_floor_div(v, w);
3816 if (div == NULL) {
3817 return -1;
3818 }
3819 }
3820 if (pmod != NULL) {
3821 mod = (PyLongObject *)fast_mod(v, w);
3822 if (mod == NULL) {
3823 Py_XDECREF(div);
3824 return -1;
3825 }
3826 *pmod = mod;
3827 }
3828 if (pdiv != NULL) {
3829 /* We only want to set `*pdiv` when `*pmod` is
3830 set successfully. */
3831 *pdiv = div;
3832 }
3833 return 0;
3834 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 if (long_divrem(v, w, &div, &mod) < 0)
3836 return -1;
3837 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3838 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3839 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 temp = (PyLongObject *) long_add(mod, w);
3841 Py_DECREF(mod);
3842 mod = temp;
3843 if (mod == NULL) {
3844 Py_DECREF(div);
3845 return -1;
3846 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003847 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3848 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 Py_DECREF(mod);
3850 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 return -1;
3852 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 Py_DECREF(div);
3854 div = temp;
3855 }
3856 if (pdiv != NULL)
3857 *pdiv = div;
3858 else
3859 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 if (pmod != NULL)
3862 *pmod = mod;
3863 else
3864 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003867}
3868
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003869static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003870long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003875
3876 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3877 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3878 }
3879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3881 div = NULL;
3882 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003883}
3884
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003885/* PyLong/PyLong -> float, with correctly rounded result. */
3886
3887#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3888#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3889
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003890static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003891long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 PyLongObject *a, *b, *x;
3894 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3895 digit mask, low;
3896 int inexact, negate, a_is_small, b_is_small;
3897 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 CHECK_BINOP(v, w);
3900 a = (PyLongObject *)v;
3901 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 /*
3904 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3907 1. choose a suitable integer 'shift'
3908 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3909 3. adjust x for correct rounding
3910 4. convert x to a double dx with the same value
3911 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3916 returns either 0.0 or -0.0, depending on the sign of b. For a and
3917 b both nonzero, ignore signs of a and b, and add the sign back in
3918 at the end. Now write a_bits and b_bits for the bit lengths of a
3919 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3920 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3925 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3926 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3927 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 1. The integer 'shift' is chosen so that x has the right number of
3932 bits for a double, plus two or three extra bits that will be used
3933 in the rounding decisions. Writing a_bits and b_bits for the
3934 number of significant bits in a and b respectively, a
3935 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 This is fine in the usual case, but if a/b is smaller than the
3940 smallest normal float then it can lead to double rounding on an
3941 IEEE 754 platform, giving incorrectly rounded results. So we
3942 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 2. The quantity x is computed by first shifting a (left -shift bits
3947 if shift <= 0, right shift bits if shift > 0) and then dividing by
3948 b. For both the shift and the division, we keep track of whether
3949 the result is inexact, in a flag 'inexact'; this information is
3950 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 With the choice of shift above, together with our assumption that
3953 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3954 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3957 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 For float representability, we need x/2**extra_bits <
3962 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3963 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 To round, we just modify the bottom digit of x in-place; this can
3968 end up giving a digit with value > PyLONG_MASK, but that's not a
3969 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 With the original choices for shift above, extra_bits will always
3972 be 2 or 3. Then rounding under the round-half-to-even rule, we
3973 round up iff the most significant of the extra bits is 1, and
3974 either: (a) the computation of x in step 2 had an inexact result,
3975 or (b) at least one other of the extra bits is 1, or (c) the least
3976 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 4. Conversion to a double is straightforward; all floating-point
3979 operations involved in the conversion are exact, so there's no
3980 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3983 The result will always be exactly representable as a double, except
3984 in the case that it overflows. To avoid dependence on the exact
3985 behaviour of ldexp on overflow, we check for overflow before
3986 applying ldexp. The result of ldexp is adjusted for sign before
3987 returning.
3988 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003991 a_size = Py_ABS(Py_SIZE(a));
3992 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3994 if (b_size == 0) {
3995 PyErr_SetString(PyExc_ZeroDivisionError,
3996 "division by zero");
3997 goto error;
3998 }
3999 if (a_size == 0)
4000 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 /* Fast path for a and b small (exactly representable in a double).
4003 Relies on floating-point division being correctly rounded; results
4004 may be subject to double rounding on x86 machines that operate with
4005 the x87 FPU set to 64-bit precision. */
4006 a_is_small = a_size <= MANT_DIG_DIGITS ||
4007 (a_size == MANT_DIG_DIGITS+1 &&
4008 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
4009 b_is_small = b_size <= MANT_DIG_DIGITS ||
4010 (b_size == MANT_DIG_DIGITS+1 &&
4011 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
4012 if (a_is_small && b_is_small) {
4013 double da, db;
4014 da = a->ob_digit[--a_size];
4015 while (a_size > 0)
4016 da = da * PyLong_BASE + a->ob_digit[--a_size];
4017 db = b->ob_digit[--b_size];
4018 while (b_size > 0)
4019 db = db * PyLong_BASE + b->ob_digit[--b_size];
4020 result = da / db;
4021 goto success;
4022 }
Tim Peterse2a60002001-09-04 06:17:36 +00004023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 /* Catch obvious cases of underflow and overflow */
4025 diff = a_size - b_size;
4026 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
4027 /* Extreme overflow */
4028 goto overflow;
4029 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
4030 /* Extreme underflow */
4031 goto underflow_or_zero;
4032 /* Next line is now safe from overflowing a Py_ssize_t */
4033 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
4034 bits_in_digit(b->ob_digit[b_size - 1]);
4035 /* Now diff = a_bits - b_bits. */
4036 if (diff > DBL_MAX_EXP)
4037 goto overflow;
4038 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
4039 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00004040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004042 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 /* x = abs(a * 2**-shift) */
4047 if (shift <= 0) {
4048 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
4049 digit rem;
4050 /* x = a << -shift */
4051 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
4052 /* In practice, it's probably impossible to end up
4053 here. Both a and b would have to be enormous,
4054 using close to SIZE_T_MAX bytes of memory each. */
4055 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004056 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 goto error;
4058 }
4059 x = _PyLong_New(a_size + shift_digits + 1);
4060 if (x == NULL)
4061 goto error;
4062 for (i = 0; i < shift_digits; i++)
4063 x->ob_digit[i] = 0;
4064 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
4065 a_size, -shift % PyLong_SHIFT);
4066 x->ob_digit[a_size + shift_digits] = rem;
4067 }
4068 else {
4069 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
4070 digit rem;
4071 /* x = a >> shift */
4072 assert(a_size >= shift_digits);
4073 x = _PyLong_New(a_size - shift_digits);
4074 if (x == NULL)
4075 goto error;
4076 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4077 a_size - shift_digits, shift % PyLong_SHIFT);
4078 /* set inexact if any of the bits shifted out is nonzero */
4079 if (rem)
4080 inexact = 1;
4081 while (!inexact && shift_digits > 0)
4082 if (a->ob_digit[--shift_digits])
4083 inexact = 1;
4084 }
4085 long_normalize(x);
4086 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 /* x //= b. If the remainder is nonzero, set inexact. We own the only
4089 reference to x, so it's safe to modify it in-place. */
4090 if (b_size == 1) {
4091 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4092 b->ob_digit[0]);
4093 long_normalize(x);
4094 if (rem)
4095 inexact = 1;
4096 }
4097 else {
4098 PyLongObject *div, *rem;
4099 div = x_divrem(x, b, &rem);
4100 Py_DECREF(x);
4101 x = div;
4102 if (x == NULL)
4103 goto error;
4104 if (Py_SIZE(rem))
4105 inexact = 1;
4106 Py_DECREF(rem);
4107 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004108 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 assert(x_size > 0); /* result of division is never zero */
4110 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02004113 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 /* Round by directly modifying the low digit of x. */
4117 mask = (digit)1 << (extra_bits - 1);
4118 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004119 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01004121 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 /* Convert x to a double dx; the conversion is exact. */
4124 dx = x->ob_digit[--x_size];
4125 while (x_size > 0)
4126 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4127 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 /* Check whether ldexp result will overflow a double. */
4130 if (shift + x_bits >= DBL_MAX_EXP &&
4131 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4132 goto overflow;
4133 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004134
4135 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004137
4138 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004140
4141 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 PyErr_SetString(PyExc_OverflowError,
4143 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004144 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004146}
4147
4148static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004149long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 CHECK_BINOP(a, b);
4154
Yury Selivanove0b23092016-02-11 10:26:27 -05004155 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4156 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4157 }
4158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4160 mod = NULL;
4161 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004162}
4163
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004164static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004165long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 PyLongObject *div, *mod;
4168 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4173 return NULL;
4174 }
4175 z = PyTuple_New(2);
4176 if (z != NULL) {
Sergey Fedoseevea6207d2019-02-21 15:01:11 +05004177 PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4178 PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 }
4180 else {
4181 Py_DECREF(div);
4182 Py_DECREF(mod);
4183 }
4184 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004185}
4186
Mark Dickinsonc5299672019-06-02 10:24:06 +01004187
4188/* Compute an inverse to a modulo n, or raise ValueError if a is not
4189 invertible modulo n. Assumes n is positive. The inverse returned
4190 is whatever falls out of the extended Euclidean algorithm: it may
4191 be either positive or negative, but will be smaller than n in
4192 absolute value.
4193
4194 Pure Python equivalent for long_invmod:
4195
4196 def invmod(a, n):
4197 b, c = 1, 0
4198 while n:
4199 q, r = divmod(a, n)
4200 a, b, c, n = n, c, b - q*c, r
4201
4202 # at this point a is the gcd of the original inputs
4203 if a == 1:
4204 return b
4205 raise ValueError("Not invertible")
4206*/
4207
4208static PyLongObject *
4209long_invmod(PyLongObject *a, PyLongObject *n)
4210{
4211 PyLongObject *b, *c;
4212
4213 /* Should only ever be called for positive n */
4214 assert(Py_SIZE(n) > 0);
4215
4216 b = (PyLongObject *)PyLong_FromLong(1L);
4217 if (b == NULL) {
4218 return NULL;
4219 }
4220 c = (PyLongObject *)PyLong_FromLong(0L);
4221 if (c == NULL) {
4222 Py_DECREF(b);
4223 return NULL;
4224 }
4225 Py_INCREF(a);
4226 Py_INCREF(n);
4227
4228 /* references now owned: a, b, c, n */
4229 while (Py_SIZE(n) != 0) {
4230 PyLongObject *q, *r, *s, *t;
4231
4232 if (l_divmod(a, n, &q, &r) == -1) {
4233 goto Error;
4234 }
4235 Py_DECREF(a);
4236 a = n;
4237 n = r;
4238 t = (PyLongObject *)long_mul(q, c);
4239 Py_DECREF(q);
4240 if (t == NULL) {
4241 goto Error;
4242 }
4243 s = (PyLongObject *)long_sub(b, t);
4244 Py_DECREF(t);
4245 if (s == NULL) {
4246 goto Error;
4247 }
4248 Py_DECREF(b);
4249 b = c;
4250 c = s;
4251 }
4252 /* references now owned: a, b, c, n */
4253
4254 Py_DECREF(c);
4255 Py_DECREF(n);
Petr Viktorin1e375c62019-06-03 02:28:29 +02004256 if (long_compare(a, (PyLongObject *)_PyLong_One)) {
Mark Dickinsonc5299672019-06-02 10:24:06 +01004257 /* a != 1; we don't have an inverse. */
4258 Py_DECREF(a);
4259 Py_DECREF(b);
4260 PyErr_SetString(PyExc_ValueError,
4261 "base is not invertible for the given modulus");
4262 return NULL;
4263 }
4264 else {
4265 /* a == 1; b gives an inverse modulo n */
4266 Py_DECREF(a);
4267 return b;
4268 }
4269
4270 Error:
4271 Py_DECREF(a);
4272 Py_DECREF(b);
4273 Py_DECREF(c);
4274 Py_DECREF(n);
4275 return NULL;
4276}
4277
4278
Tim Peters47e52ee2004-08-30 02:44:38 +00004279/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004280static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004281long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4284 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 PyLongObject *z = NULL; /* accumulated result */
4287 Py_ssize_t i, j, k; /* counters */
4288 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 /* 5-ary values. If the exponent is large enough, table is
4291 * precomputed so that table[i] == a**i % c for i in range(32).
4292 */
4293 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4294 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 /* a, b, c = v, w, x */
4297 CHECK_BINOP(v, w);
4298 a = (PyLongObject*)v; Py_INCREF(a);
4299 b = (PyLongObject*)w; Py_INCREF(b);
4300 if (PyLong_Check(x)) {
4301 c = (PyLongObject *)x;
4302 Py_INCREF(x);
4303 }
4304 else if (x == Py_None)
4305 c = NULL;
4306 else {
4307 Py_DECREF(a);
4308 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004309 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 }
Tim Peters4c483c42001-09-05 06:24:58 +00004311
Mark Dickinsonc5299672019-06-02 10:24:06 +01004312 if (Py_SIZE(b) < 0 && c == NULL) {
4313 /* if exponent is negative and there's no modulus:
4314 return a float. This works because we know
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 that this calls float_pow() which converts its
4316 arguments to double. */
Mark Dickinsonc5299672019-06-02 10:24:06 +01004317 Py_DECREF(a);
4318 Py_DECREF(b);
4319 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 if (c) {
4323 /* if modulus == 0:
4324 raise ValueError() */
4325 if (Py_SIZE(c) == 0) {
4326 PyErr_SetString(PyExc_ValueError,
4327 "pow() 3rd argument cannot be 0");
4328 goto Error;
4329 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 /* if modulus < 0:
4332 negativeOutput = True
4333 modulus = -modulus */
4334 if (Py_SIZE(c) < 0) {
4335 negativeOutput = 1;
4336 temp = (PyLongObject *)_PyLong_Copy(c);
4337 if (temp == NULL)
4338 goto Error;
4339 Py_DECREF(c);
4340 c = temp;
4341 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004342 _PyLong_Negate(&c);
4343 if (c == NULL)
4344 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 /* if modulus == 1:
4348 return 0 */
4349 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4350 z = (PyLongObject *)PyLong_FromLong(0L);
4351 goto Done;
4352 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004353
Mark Dickinsonc5299672019-06-02 10:24:06 +01004354 /* if exponent is negative, negate the exponent and
4355 replace the base with a modular inverse */
4356 if (Py_SIZE(b) < 0) {
4357 temp = (PyLongObject *)_PyLong_Copy(b);
4358 if (temp == NULL)
4359 goto Error;
4360 Py_DECREF(b);
4361 b = temp;
4362 temp = NULL;
4363 _PyLong_Negate(&b);
4364 if (b == NULL)
4365 goto Error;
4366
4367 temp = long_invmod(a, c);
4368 if (temp == NULL)
4369 goto Error;
4370 Py_DECREF(a);
4371 a = temp;
4372 }
4373
Tim Peters81a93152013-10-05 16:53:52 -05004374 /* Reduce base by modulus in some cases:
4375 1. If base < 0. Forcing the base non-negative makes things easier.
4376 2. If base is obviously larger than the modulus. The "small
4377 exponent" case later can multiply directly by base repeatedly,
4378 while the "large exponent" case multiplies directly by base 31
4379 times. It can be unboundedly faster to multiply by
4380 base % modulus instead.
4381 We could _always_ do this reduction, but l_divmod() isn't cheap,
4382 so we only do it when it buys something. */
4383 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 if (l_divmod(a, c, NULL, &temp) < 0)
4385 goto Error;
4386 Py_DECREF(a);
4387 a = temp;
4388 temp = NULL;
4389 }
4390 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 /* At this point a, b, and c are guaranteed non-negative UNLESS
4393 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 z = (PyLongObject *)PyLong_FromLong(1L);
4396 if (z == NULL)
4397 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 /* Perform a modular reduction, X = X % c, but leave X alone if c
4400 * is NULL.
4401 */
4402#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004403 do { \
4404 if (c != NULL) { \
4405 if (l_divmod(X, c, NULL, &temp) < 0) \
4406 goto Error; \
4407 Py_XDECREF(X); \
4408 X = temp; \
4409 temp = NULL; \
4410 } \
4411 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 /* Multiply two values, then reduce the result:
4414 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004415#define MULT(X, Y, result) \
4416 do { \
4417 temp = (PyLongObject *)long_mul(X, Y); \
4418 if (temp == NULL) \
4419 goto Error; \
4420 Py_XDECREF(result); \
4421 result = temp; \
4422 temp = NULL; \
4423 REDUCE(result); \
4424 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4427 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4428 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4429 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4430 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004433 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004435 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 }
4437 }
4438 }
4439 else {
4440 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4441 Py_INCREF(z); /* still holds 1L */
4442 table[0] = z;
4443 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004444 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4447 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4450 const int index = (bi >> j) & 0x1f;
4451 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004452 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004454 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 }
4456 }
4457 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 if (negativeOutput && (Py_SIZE(z) != 0)) {
4460 temp = (PyLongObject *)long_sub(z, c);
4461 if (temp == NULL)
4462 goto Error;
4463 Py_DECREF(z);
4464 z = temp;
4465 temp = NULL;
4466 }
4467 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004468
Mark Dickinson22b20182010-05-10 21:27:53 +00004469 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004470 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004472 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4474 for (i = 0; i < 32; ++i)
4475 Py_XDECREF(table[i]);
4476 }
4477 Py_DECREF(a);
4478 Py_DECREF(b);
4479 Py_XDECREF(c);
4480 Py_XDECREF(temp);
4481 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004482}
4483
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004484static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004485long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 /* Implement ~x as -(x+1) */
4488 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004489 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004491 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 if (x == NULL)
4493 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004494 _PyLong_Negate(&x);
4495 /* No need for maybe_small_long here, since any small
4496 longs will have been caught in the Py_SIZE <= 1 fast path. */
4497 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004498}
4499
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004500static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004501long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004504 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 return PyLong_FromLong(-MEDIUM_VALUE(v));
4506 z = (PyLongObject *)_PyLong_Copy(v);
4507 if (z != NULL)
4508 Py_SIZE(z) = -(Py_SIZE(v));
4509 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004510}
4511
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004512static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004513long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 if (Py_SIZE(v) < 0)
4516 return long_neg(v);
4517 else
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004518 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004519}
4520
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004521static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004522long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004525}
4526
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004527/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4528static int
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004529divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004530{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004531 assert(PyLong_Check(shiftby));
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004532 assert(Py_SIZE(shiftby) >= 0);
4533 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4534 if (lshiftby >= 0) {
4535 *wordshift = lshiftby / PyLong_SHIFT;
4536 *remshift = lshiftby % PyLong_SHIFT;
4537 return 0;
4538 }
4539 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4540 be that PyLong_AsSsize_t raised an OverflowError. */
4541 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4542 PyErr_Clear();
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004543 PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004544 if (wordshift_obj == NULL) {
4545 return -1;
4546 }
4547 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4548 Py_DECREF(wordshift_obj);
4549 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4550 return 0;
4551 }
4552 PyErr_Clear();
4553 /* Clip the value. With such large wordshift the right shift
4554 returns 0 and the left shift raises an error in _PyLong_New(). */
4555 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4556 *remshift = 0;
4557 return 0;
4558}
4559
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004560static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004561long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 PyLongObject *z = NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004564 Py_ssize_t newsize, hishift, i, j;
4565 digit lomask, himask;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 if (Py_SIZE(a) < 0) {
4568 /* Right shifting negative numbers is harder */
4569 PyLongObject *a1, *a2;
4570 a1 = (PyLongObject *) long_invert(a);
4571 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004572 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004573 a2 = (PyLongObject *) long_rshift1(a1, wordshift, remshift);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 Py_DECREF(a1);
4575 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004576 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 z = (PyLongObject *) long_invert(a2);
4578 Py_DECREF(a2);
4579 }
4580 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004581 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 if (newsize <= 0)
4583 return PyLong_FromLong(0);
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004584 hishift = PyLong_SHIFT - remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 lomask = ((digit)1 << hishift) - 1;
4586 himask = PyLong_MASK ^ lomask;
4587 z = _PyLong_New(newsize);
4588 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004589 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 for (i = 0, j = wordshift; i < newsize; i++, j++) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004591 z->ob_digit[i] = (a->ob_digit[j] >> remshift) & lomask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004593 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004595 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004597 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004598}
4599
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004600static PyObject *
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004601long_rshift(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004602{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004603 Py_ssize_t wordshift;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004604 digit remshift;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004607
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004608 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004609 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004610 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004612 if (Py_SIZE(a) == 0) {
4613 return PyLong_FromLong(0);
4614 }
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004615 if (divmod_shift(b, &wordshift, &remshift) < 0)
4616 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004617 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4618}
4619
4620/* Return a >> shiftby. */
4621PyObject *
4622_PyLong_Rshift(PyObject *a, size_t shiftby)
4623{
4624 Py_ssize_t wordshift;
4625 digit remshift;
4626
4627 assert(PyLong_Check(a));
4628 if (Py_SIZE(a) == 0) {
4629 return PyLong_FromLong(0);
4630 }
4631 wordshift = shiftby / PyLong_SHIFT;
4632 remshift = shiftby % PyLong_SHIFT;
4633 return long_rshift1((PyLongObject *)a, wordshift, remshift);
4634}
4635
4636static PyObject *
4637long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4638{
4639 /* This version due to Tim Peters */
4640 PyLongObject *z = NULL;
4641 Py_ssize_t oldsize, newsize, i, j;
4642 twodigits accum;
4643
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004644 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004645 newsize = oldsize + wordshift;
4646 if (remshift)
4647 ++newsize;
4648 z = _PyLong_New(newsize);
4649 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004650 return NULL;
4651 if (Py_SIZE(a) < 0) {
4652 assert(Py_REFCNT(z) == 1);
4653 Py_SIZE(z) = -Py_SIZE(z);
4654 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 for (i = 0; i < wordshift; i++)
4656 z->ob_digit[i] = 0;
4657 accum = 0;
4658 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4659 accum |= (twodigits)a->ob_digit[j] << remshift;
4660 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4661 accum >>= PyLong_SHIFT;
4662 }
4663 if (remshift)
4664 z->ob_digit[newsize-1] = (digit)accum;
4665 else
4666 assert(!accum);
4667 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004669}
4670
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03004671static PyObject *
4672long_lshift(PyObject *a, PyObject *b)
4673{
4674 Py_ssize_t wordshift;
4675 digit remshift;
4676
4677 CHECK_BINOP(a, b);
4678
4679 if (Py_SIZE(b) < 0) {
4680 PyErr_SetString(PyExc_ValueError, "negative shift count");
4681 return NULL;
4682 }
4683 if (Py_SIZE(a) == 0) {
4684 return PyLong_FromLong(0);
4685 }
4686 if (divmod_shift(b, &wordshift, &remshift) < 0)
4687 return NULL;
4688 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4689}
4690
4691/* Return a << shiftby. */
4692PyObject *
4693_PyLong_Lshift(PyObject *a, size_t shiftby)
4694{
4695 Py_ssize_t wordshift;
4696 digit remshift;
4697
4698 assert(PyLong_Check(a));
4699 if (Py_SIZE(a) == 0) {
4700 return PyLong_FromLong(0);
4701 }
4702 wordshift = shiftby / PyLong_SHIFT;
4703 remshift = shiftby % PyLong_SHIFT;
4704 return long_lshift1((PyLongObject *)a, wordshift, remshift);
4705}
4706
Mark Dickinson27a87a22009-10-25 20:43:34 +00004707/* Compute two's complement of digit vector a[0:m], writing result to
4708 z[0:m]. The digit vector a need not be normalized, but should not
4709 be entirely zero. a and z may point to the same digit vector. */
4710
4711static void
4712v_complement(digit *z, digit *a, Py_ssize_t m)
4713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 Py_ssize_t i;
4715 digit carry = 1;
4716 for (i = 0; i < m; ++i) {
4717 carry += a[i] ^ PyLong_MASK;
4718 z[i] = carry & PyLong_MASK;
4719 carry >>= PyLong_SHIFT;
4720 }
4721 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004722}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004723
4724/* Bitwise and/xor/or operations */
4725
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004726static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004727long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004728 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004729 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 int nega, negb, negz;
4732 Py_ssize_t size_a, size_b, size_z, i;
4733 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 /* Bitwise operations for negative numbers operate as though
4736 on a two's complement representation. So convert arguments
4737 from sign-magnitude to two's complement, and convert the
4738 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004741 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 nega = Py_SIZE(a) < 0;
4743 if (nega) {
4744 z = _PyLong_New(size_a);
4745 if (z == NULL)
4746 return NULL;
4747 v_complement(z->ob_digit, a->ob_digit, size_a);
4748 a = z;
4749 }
4750 else
4751 /* Keep reference count consistent. */
4752 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004755 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 negb = Py_SIZE(b) < 0;
4757 if (negb) {
4758 z = _PyLong_New(size_b);
4759 if (z == NULL) {
4760 Py_DECREF(a);
4761 return NULL;
4762 }
4763 v_complement(z->ob_digit, b->ob_digit, size_b);
4764 b = z;
4765 }
4766 else
4767 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769 /* Swap a and b if necessary to ensure size_a >= size_b. */
4770 if (size_a < size_b) {
4771 z = a; a = b; b = z;
4772 size_z = size_a; size_a = size_b; size_b = size_z;
4773 negz = nega; nega = negb; negb = negz;
4774 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 /* JRH: The original logic here was to allocate the result value (z)
4777 as the longer of the two operands. However, there are some cases
4778 where the result is guaranteed to be shorter than that: AND of two
4779 positives, OR of two negatives: use the shorter number. AND with
4780 mixed signs: use the positive number. OR with mixed signs: use the
4781 negative number.
4782 */
4783 switch (op) {
4784 case '^':
4785 negz = nega ^ negb;
4786 size_z = size_a;
4787 break;
4788 case '&':
4789 negz = nega & negb;
4790 size_z = negb ? size_a : size_b;
4791 break;
4792 case '|':
4793 negz = nega | negb;
4794 size_z = negb ? size_b : size_a;
4795 break;
4796 default:
stratakisa10d4262019-03-18 18:59:20 +01004797 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 /* We allow an extra digit if z is negative, to make sure that
4801 the final two's complement of z doesn't overflow. */
4802 z = _PyLong_New(size_z + negz);
4803 if (z == NULL) {
4804 Py_DECREF(a);
4805 Py_DECREF(b);
4806 return NULL;
4807 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 /* Compute digits for overlap of a and b. */
4810 switch(op) {
4811 case '&':
4812 for (i = 0; i < size_b; ++i)
4813 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4814 break;
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 default:
stratakisa10d4262019-03-18 18:59:20 +01004824 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 /* Copy any remaining digits of a, inverting if necessary. */
4828 if (op == '^' && negb)
4829 for (; i < size_z; ++i)
4830 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4831 else if (i < size_z)
4832 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4833 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 /* Complement result if negative. */
4836 if (negz) {
4837 Py_SIZE(z) = -(Py_SIZE(z));
4838 z->ob_digit[size_z] = PyLong_MASK;
4839 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4840 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 Py_DECREF(a);
4843 Py_DECREF(b);
4844 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004845}
4846
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004847static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004848long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 PyObject *c;
4851 CHECK_BINOP(a, b);
4852 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4853 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004854}
4855
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004856static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004857long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 PyObject *c;
4860 CHECK_BINOP(a, b);
4861 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4862 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004863}
4864
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004865static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004866long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 PyObject *c;
4869 CHECK_BINOP(a, b);
4870 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4871 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004872}
4873
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004874static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03004875long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 if (PyLong_CheckExact(v))
4878 Py_INCREF(v);
4879 else
4880 v = _PyLong_Copy((PyLongObject *)v);
4881 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004882}
4883
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004884PyObject *
4885_PyLong_GCD(PyObject *aarg, PyObject *barg)
4886{
4887 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4888 stwodigits x, y, q, s, t, c_carry, d_carry;
4889 stwodigits A, B, C, D, T;
4890 int nbits, k;
4891 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4892 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4893
4894 a = (PyLongObject *)aarg;
4895 b = (PyLongObject *)barg;
4896 size_a = Py_SIZE(a);
4897 size_b = Py_SIZE(b);
4898 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4899 Py_INCREF(a);
4900 Py_INCREF(b);
4901 goto simple;
4902 }
4903
4904 /* Initial reduction: make sure that 0 <= b <= a. */
4905 a = (PyLongObject *)long_abs(a);
4906 if (a == NULL)
4907 return NULL;
4908 b = (PyLongObject *)long_abs(b);
4909 if (b == NULL) {
4910 Py_DECREF(a);
4911 return NULL;
4912 }
4913 if (long_compare(a, b) < 0) {
4914 r = a;
4915 a = b;
4916 b = r;
4917 }
4918 /* We now own references to a and b */
4919
4920 alloc_a = Py_SIZE(a);
4921 alloc_b = Py_SIZE(b);
4922 /* reduce until a fits into 2 digits */
4923 while ((size_a = Py_SIZE(a)) > 2) {
4924 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4925 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4926 corresponding bits of b into y */
4927 size_b = Py_SIZE(b);
4928 assert(size_b <= size_a);
4929 if (size_b == 0) {
4930 if (size_a < alloc_a) {
4931 r = (PyLongObject *)_PyLong_Copy(a);
4932 Py_DECREF(a);
4933 }
4934 else
4935 r = a;
4936 Py_DECREF(b);
4937 Py_XDECREF(c);
4938 Py_XDECREF(d);
4939 return (PyObject *)r;
4940 }
4941 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4942 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4943 (a->ob_digit[size_a-3] >> nbits));
4944
4945 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4946 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4947 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4948
4949 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4950 larger than PyLong_MASK during the algorithm. */
4951 A = 1; B = 0; C = 0; D = 1;
4952 for (k=0;; k++) {
4953 if (y-C == 0)
4954 break;
4955 q = (x+(A-1))/(y-C);
4956 s = B+q*D;
4957 t = x-q*y;
4958 if (s > t)
4959 break;
4960 x = y; y = t;
4961 t = A+q*C; A = D; B = C; C = s; D = t;
4962 }
4963
4964 if (k == 0) {
4965 /* no progress; do a Euclidean step */
4966 if (l_divmod(a, b, NULL, &r) < 0)
4967 goto error;
4968 Py_DECREF(a);
4969 a = b;
4970 b = r;
4971 alloc_a = alloc_b;
4972 alloc_b = Py_SIZE(b);
4973 continue;
4974 }
4975
4976 /*
4977 a, b = A*b-B*a, D*a-C*b if k is odd
4978 a, b = A*a-B*b, D*b-C*a if k is even
4979 */
4980 if (k&1) {
4981 T = -A; A = -B; B = T;
4982 T = -C; C = -D; D = T;
4983 }
4984 if (c != NULL)
4985 Py_SIZE(c) = size_a;
4986 else if (Py_REFCNT(a) == 1) {
4987 Py_INCREF(a);
4988 c = a;
4989 }
4990 else {
4991 alloc_a = size_a;
4992 c = _PyLong_New(size_a);
4993 if (c == NULL)
4994 goto error;
4995 }
4996
4997 if (d != NULL)
4998 Py_SIZE(d) = size_a;
4999 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
5000 Py_INCREF(b);
5001 d = b;
5002 Py_SIZE(d) = size_a;
5003 }
5004 else {
5005 alloc_b = size_a;
5006 d = _PyLong_New(size_a);
5007 if (d == NULL)
5008 goto error;
5009 }
5010 a_end = a->ob_digit + size_a;
5011 b_end = b->ob_digit + size_b;
5012
5013 /* compute new a and new b in parallel */
5014 a_digit = a->ob_digit;
5015 b_digit = b->ob_digit;
5016 c_digit = c->ob_digit;
5017 d_digit = d->ob_digit;
5018 c_carry = 0;
5019 d_carry = 0;
5020 while (b_digit < b_end) {
5021 c_carry += (A * *a_digit) - (B * *b_digit);
5022 d_carry += (D * *b_digit++) - (C * *a_digit++);
5023 *c_digit++ = (digit)(c_carry & PyLong_MASK);
5024 *d_digit++ = (digit)(d_carry & PyLong_MASK);
5025 c_carry >>= PyLong_SHIFT;
5026 d_carry >>= PyLong_SHIFT;
5027 }
5028 while (a_digit < a_end) {
5029 c_carry += A * *a_digit;
5030 d_carry -= C * *a_digit++;
5031 *c_digit++ = (digit)(c_carry & PyLong_MASK);
5032 *d_digit++ = (digit)(d_carry & PyLong_MASK);
5033 c_carry >>= PyLong_SHIFT;
5034 d_carry >>= PyLong_SHIFT;
5035 }
5036 assert(c_carry == 0);
5037 assert(d_carry == 0);
5038
5039 Py_INCREF(c);
5040 Py_INCREF(d);
5041 Py_DECREF(a);
5042 Py_DECREF(b);
5043 a = long_normalize(c);
5044 b = long_normalize(d);
5045 }
5046 Py_XDECREF(c);
5047 Py_XDECREF(d);
5048
5049simple:
5050 assert(Py_REFCNT(a) > 0);
5051 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02005052/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
5053 undefined behaviour when LONG_MAX type is smaller than 60 bits */
5054#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005055 /* a fits into a long, so b must too */
5056 x = PyLong_AsLong((PyObject *)a);
5057 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07005058#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005059 x = PyLong_AsLongLong((PyObject *)a);
5060 y = PyLong_AsLongLong((PyObject *)b);
5061#else
5062# error "_PyLong_GCD"
5063#endif
5064 x = Py_ABS(x);
5065 y = Py_ABS(y);
5066 Py_DECREF(a);
5067 Py_DECREF(b);
5068
5069 /* usual Euclidean algorithm for longs */
5070 while (y != 0) {
5071 t = y;
5072 y = x % y;
5073 x = t;
5074 }
Victor Stinner5783fd22015-09-19 13:39:03 +02005075#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005076 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07005077#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03005078 return PyLong_FromLongLong(x);
5079#else
5080# error "_PyLong_GCD"
5081#endif
5082
5083error:
5084 Py_DECREF(a);
5085 Py_DECREF(b);
5086 Py_XDECREF(c);
5087 Py_XDECREF(d);
5088 return NULL;
5089}
5090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005091static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00005092long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 double result;
5095 result = PyLong_AsDouble(v);
5096 if (result == -1.0 && PyErr_Occurred())
5097 return NULL;
5098 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005099}
5100
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005101static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005102long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5103
5104/*[clinic input]
5105@classmethod
5106int.__new__ as long_new
5107 x: object(c_default="NULL") = 0
5108 /
5109 base as obase: object(c_default="NULL") = 10
5110[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00005111
Tim Peters6d6c1a32001-08-02 04:15:00 +00005112static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005113long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5114/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00005115{
Gregory P. Smitha689e522012-12-25 22:38:32 -08005116 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005119 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005120 if (x == NULL) {
5121 if (obase != NULL) {
5122 PyErr_SetString(PyExc_TypeError,
5123 "int() missing string argument");
5124 return NULL;
5125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02005127 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005128 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005130
Gregory P. Smitha689e522012-12-25 22:38:32 -08005131 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005132 if (base == -1 && PyErr_Occurred())
5133 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08005134 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005135 PyErr_SetString(PyExc_ValueError,
Sanyam Khurana28b62482017-11-14 03:19:26 +05305136 "int() base must be >= 2 and <= 36, or 0");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00005137 return NULL;
5138 }
5139
5140 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005141 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005143 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005144 if (PyByteArray_Check(x))
5145 string = PyByteArray_AS_STRING(x);
5146 else
5147 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03005148 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 }
5150 else {
5151 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00005152 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 return NULL;
5154 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005155}
5156
Serhiy Storchaka95949422013-08-27 19:40:23 +03005157/* Wimpy, slow approach to tp_new calls for subtypes of int:
5158 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00005159 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03005160 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00005161*/
5162static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005163long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00005164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 PyLongObject *tmp, *newobj;
5166 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00005167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02005169 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 if (tmp == NULL)
5171 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02005172 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 n = Py_SIZE(tmp);
5174 if (n < 0)
5175 n = -n;
5176 newobj = (PyLongObject *)type->tp_alloc(type, n);
5177 if (newobj == NULL) {
5178 Py_DECREF(tmp);
5179 return NULL;
5180 }
5181 assert(PyLong_Check(newobj));
5182 Py_SIZE(newobj) = Py_SIZE(tmp);
5183 for (i = 0; i < n; i++)
5184 newobj->ob_digit[i] = tmp->ob_digit[i];
5185 Py_DECREF(tmp);
5186 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00005187}
5188
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005189/*[clinic input]
5190int.__getnewargs__
5191[clinic start generated code]*/
5192
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005193static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005194int___getnewargs___impl(PyObject *self)
5195/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005196{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005197 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005198}
5199
Guido van Rossumb43daf72007-08-01 18:08:08 +00005200static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005201long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00005204}
5205
5206static PyObject *
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005207long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00005210}
5211
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005212/*[clinic input]
5213int.__format__
5214
5215 format_spec: unicode
5216 /
5217[clinic start generated code]*/
5218
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005219static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005220int___format___impl(PyObject *self, PyObject *format_spec)
5221/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00005222{
Victor Stinnerd3f08822012-05-29 12:57:52 +02005223 _PyUnicodeWriter writer;
5224 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00005225
Victor Stinner8f674cc2013-04-17 23:02:17 +02005226 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02005227 ret = _PyLong_FormatAdvancedWriter(
5228 &writer,
5229 self,
5230 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5231 if (ret == -1) {
5232 _PyUnicodeWriter_Dealloc(&writer);
5233 return NULL;
5234 }
5235 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00005236}
5237
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005238/* Return a pair (q, r) such that a = b * q + r, and
5239 abs(r) <= abs(b)/2, with equality possible only if q is even.
5240 In other words, q == a / b, rounded to the nearest integer using
5241 round-half-to-even. */
5242
5243PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005244_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005245{
5246 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005247 PyObject *twice_rem, *result, *temp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005248 int cmp, quo_is_odd, quo_is_neg;
5249
5250 /* Equivalent Python code:
5251
5252 def divmod_near(a, b):
5253 q, r = divmod(a, b)
5254 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5255 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5256 # positive, 2 * r < b if b negative.
5257 greater_than_half = 2*r > b if b > 0 else 2*r < b
5258 exactly_half = 2*r == b
5259 if greater_than_half or exactly_half and q % 2 == 1:
5260 q += 1
5261 r -= b
5262 return q, r
5263
5264 */
5265 if (!PyLong_Check(a) || !PyLong_Check(b)) {
5266 PyErr_SetString(PyExc_TypeError,
5267 "non-integer arguments in division");
5268 return NULL;
5269 }
5270
5271 /* Do a and b have different signs? If so, quotient is negative. */
5272 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5273
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005274 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5275 goto error;
5276
5277 /* compare twice the remainder with the divisor, to see
5278 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005279 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005280 if (twice_rem == NULL)
5281 goto error;
5282 if (quo_is_neg) {
5283 temp = long_neg((PyLongObject*)twice_rem);
5284 Py_DECREF(twice_rem);
5285 twice_rem = temp;
5286 if (twice_rem == NULL)
5287 goto error;
5288 }
5289 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5290 Py_DECREF(twice_rem);
5291
5292 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
5293 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
5294 /* fix up quotient */
5295 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005296 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005297 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005298 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005299 Py_DECREF(quo);
5300 quo = (PyLongObject *)temp;
5301 if (quo == NULL)
5302 goto error;
5303 /* and remainder */
5304 if (quo_is_neg)
5305 temp = long_add(rem, (PyLongObject *)b);
5306 else
5307 temp = long_sub(rem, (PyLongObject *)b);
5308 Py_DECREF(rem);
5309 rem = (PyLongObject *)temp;
5310 if (rem == NULL)
5311 goto error;
5312 }
5313
5314 result = PyTuple_New(2);
5315 if (result == NULL)
5316 goto error;
5317
5318 /* PyTuple_SET_ITEM steals references */
5319 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5320 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005321 return result;
5322
5323 error:
5324 Py_XDECREF(quo);
5325 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005326 return NULL;
5327}
5328
Eric Smith8c663262007-08-25 02:26:07 +00005329static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005330long_round(PyObject *self, PyObject *args)
5331{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005332 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005333
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005334 /* To round an integer m to the nearest 10**n (n positive), we make use of
5335 * the divmod_near operation, defined by:
5336 *
5337 * divmod_near(a, b) = (q, r)
5338 *
5339 * where q is the nearest integer to the quotient a / b (the
5340 * nearest even integer in the case of a tie) and r == a - q * b.
5341 * Hence q * b = a - r is the nearest multiple of b to a,
5342 * preferring even multiples in the case of a tie.
5343 *
5344 * So the nearest multiple of 10**n to m is:
5345 *
5346 * m - divmod_near(m, 10**n)[1].
5347 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5349 return NULL;
5350 if (o_ndigits == NULL)
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005351 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005352
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005353 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 if (ndigits == NULL)
5355 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005356
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005357 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 if (Py_SIZE(ndigits) >= 0) {
5359 Py_DECREF(ndigits);
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005360 return long_long(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005362
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005363 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5364 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005366 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005368 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005369
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005370 result = PyLong_FromLong(10L);
5371 if (result == NULL) {
5372 Py_DECREF(ndigits);
5373 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005375
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005376 temp = long_pow(result, ndigits, Py_None);
5377 Py_DECREF(ndigits);
5378 Py_DECREF(result);
5379 result = temp;
5380 if (result == NULL)
5381 return NULL;
5382
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005383 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005384 Py_DECREF(result);
5385 result = temp;
5386 if (result == NULL)
5387 return NULL;
5388
5389 temp = long_sub((PyLongObject *)self,
5390 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5391 Py_DECREF(result);
5392 result = temp;
5393
5394 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005395}
5396
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005397/*[clinic input]
5398int.__sizeof__ -> Py_ssize_t
5399
5400Returns size in memory, in bytes.
5401[clinic start generated code]*/
5402
5403static Py_ssize_t
5404int___sizeof___impl(PyObject *self)
5405/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005408
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005409 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5410 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005411}
5412
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005413/*[clinic input]
5414int.bit_length
5415
5416Number of bits necessary to represent self in binary.
5417
5418>>> bin(37)
5419'0b100101'
5420>>> (37).bit_length()
54216
5422[clinic start generated code]*/
5423
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005424static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005425int_bit_length_impl(PyObject *self)
5426/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005429 Py_ssize_t ndigits;
5430 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005432
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005433 assert(self != NULL);
5434 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005435
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005436 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 if (ndigits == 0)
5438 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005439
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005440 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005441 msd_bits = bits_in_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5444 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 /* expression above may overflow; use Python integers instead */
5447 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5448 if (result == NULL)
5449 return NULL;
5450 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5451 if (x == NULL)
5452 goto error;
5453 y = (PyLongObject *)long_mul(result, x);
5454 Py_DECREF(x);
5455 if (y == NULL)
5456 goto error;
5457 Py_DECREF(result);
5458 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5461 if (x == NULL)
5462 goto error;
5463 y = (PyLongObject *)long_add(result, x);
5464 Py_DECREF(x);
5465 if (y == NULL)
5466 goto error;
5467 Py_DECREF(result);
5468 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005471
Mark Dickinson22b20182010-05-10 21:27:53 +00005472 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 Py_DECREF(result);
5474 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005475}
5476
Christian Heimes53876d92008-04-19 00:31:39 +00005477#if 0
5478static PyObject *
5479long_is_finite(PyObject *v)
5480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005482}
5483#endif
5484
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005485/*[clinic input]
Lisa Roach5ac70432018-09-13 23:56:23 -07005486int.as_integer_ratio
5487
5488Return integer ratio.
5489
5490Return a pair of integers, whose ratio is exactly equal to the original int
5491and with a positive denominator.
5492
5493>>> (10).as_integer_ratio()
5494(10, 1)
5495>>> (-10).as_integer_ratio()
5496(-10, 1)
5497>>> (0).as_integer_ratio()
5498(0, 1)
5499[clinic start generated code]*/
5500
5501static PyObject *
5502int_as_integer_ratio_impl(PyObject *self)
5503/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5504{
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005505 PyObject *ratio_tuple;
Serhiy Storchakab2e20252018-10-20 00:46:31 +03005506 PyObject *numerator = long_long(self);
Raymond Hettinger00bc08e2018-09-14 01:00:11 -07005507 if (numerator == NULL) {
5508 return NULL;
5509 }
5510 ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_One);
5511 Py_DECREF(numerator);
5512 return ratio_tuple;
Lisa Roach5ac70432018-09-13 23:56:23 -07005513}
5514
5515/*[clinic input]
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005516int.to_bytes
5517
5518 length: Py_ssize_t
5519 Length of bytes object to use. An OverflowError is raised if the
5520 integer is not representable with the given number of bytes.
5521 byteorder: unicode
5522 The byte order used to represent the integer. If byteorder is 'big',
5523 the most significant byte is at the beginning of the byte array. If
5524 byteorder is 'little', the most significant byte is at the end of the
5525 byte array. To request the native byte order of the host system, use
5526 `sys.byteorder' as the byte order value.
5527 *
5528 signed as is_signed: bool = False
5529 Determines whether two's complement is used to represent the integer.
5530 If signed is False and a negative integer is given, an OverflowError
5531 is raised.
5532
5533Return an array of bytes representing an integer.
5534[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005535
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005536static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005537int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5538 int is_signed)
5539/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005543
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005544 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005546 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 little_endian = 0;
5548 else {
5549 PyErr_SetString(PyExc_ValueError,
5550 "byteorder must be either 'little' or 'big'");
5551 return NULL;
5552 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 if (length < 0) {
5555 PyErr_SetString(PyExc_ValueError,
5556 "length argument must be non-negative");
5557 return NULL;
5558 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005560 bytes = PyBytes_FromStringAndSize(NULL, length);
5561 if (bytes == NULL)
5562 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005563
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005564 if (_PyLong_AsByteArray((PyLongObject *)self,
5565 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 length, little_endian, is_signed) < 0) {
5567 Py_DECREF(bytes);
5568 return NULL;
5569 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005572}
5573
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005574/*[clinic input]
5575@classmethod
5576int.from_bytes
5577
5578 bytes as bytes_obj: object
5579 Holds the array of bytes to convert. The argument must either
5580 support the buffer protocol or be an iterable object producing bytes.
5581 Bytes and bytearray are examples of built-in objects that support the
5582 buffer protocol.
5583 byteorder: unicode
5584 The byte order used to represent the integer. If byteorder is 'big',
5585 the most significant byte is at the beginning of the byte array. If
5586 byteorder is 'little', the most significant byte is at the end of the
5587 byte array. To request the native byte order of the host system, use
5588 `sys.byteorder' as the byte order value.
5589 *
5590 signed as is_signed: bool = False
5591 Indicates whether two's complement is used to represent the integer.
5592
5593Return the integer represented by the given array of bytes.
5594[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005595
5596static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005597int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5598 PyObject *byteorder, int is_signed)
5599/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005602 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005603
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005604 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005605 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005606 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005607 little_endian = 0;
5608 else {
5609 PyErr_SetString(PyExc_ValueError,
5610 "byteorder must be either 'little' or 'big'");
5611 return NULL;
5612 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005613
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005614 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005615 if (bytes == NULL)
5616 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005618 long_obj = _PyLong_FromByteArray(
5619 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5620 little_endian, is_signed);
5621 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005622
Zackery Spytz7bb9cd02018-10-05 15:02:23 -06005623 if (long_obj != NULL && type != &PyLong_Type) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02005624 Py_SETREF(long_obj, _PyObject_CallOneArg((PyObject *)type, long_obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005628}
5629
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005630static PyObject *
5631long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5632{
5633 return long_long(self);
5634}
5635
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005636static PyMethodDef long_methods[] = {
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005637 {"conjugate", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005639 INT_BIT_LENGTH_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00005640#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005641 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5642 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005643#endif
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005644 INT_TO_BYTES_METHODDEF
5645 INT_FROM_BYTES_METHODDEF
Lisa Roach5ac70432018-09-13 23:56:23 -07005646 INT_AS_INTEGER_RATIO_METHODDEF
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005647 {"__trunc__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005648 "Truncating an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005649 {"__floor__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 "Flooring an Integral returns itself."},
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005651 {"__ceil__", long_long_meth, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 "Ceiling of an Integral returns itself."},
5653 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5654 "Rounding an Integral returns itself.\n"
5655 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005656 INT___GETNEWARGS___METHODDEF
5657 INT___FORMAT___METHODDEF
5658 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005660};
5661
Guido van Rossumb43daf72007-08-01 18:08:08 +00005662static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005663 {"real",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005664 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005665 "the real part of a complex number",
5666 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005667 {"imag",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005668 long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005669 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005670 NULL},
5671 {"numerator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005672 (getter)long_long_meth, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005673 "the numerator of a rational number in lowest terms",
5674 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005675 {"denominator",
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005676 long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005677 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005678 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005679 {NULL} /* Sentinel */
5680};
5681
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005682PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005683"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005684int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005685\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005686Convert a number or string to an integer, or return 0 if no arguments\n\
5687are given. If x is a number, return x.__int__(). For floating point\n\
5688numbers, this truncates towards zero.\n\
5689\n\
5690If x is not a number or if base is given, then x must be a string,\n\
5691bytes, or bytearray instance representing an integer literal in the\n\
5692given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5693by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5694Base 0 means to interpret the base from the string as an integer literal.\n\
5695>>> int('0b100', base=0)\n\
56964");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005697
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005698static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005699 (binaryfunc)long_add, /*nb_add*/
5700 (binaryfunc)long_sub, /*nb_subtract*/
5701 (binaryfunc)long_mul, /*nb_multiply*/
5702 long_mod, /*nb_remainder*/
5703 long_divmod, /*nb_divmod*/
5704 long_pow, /*nb_power*/
5705 (unaryfunc)long_neg, /*nb_negative*/
Serhiy Storchaka6405fee2018-04-30 15:35:08 +03005706 long_long, /*tp_positive*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005707 (unaryfunc)long_abs, /*tp_absolute*/
5708 (inquiry)long_bool, /*tp_bool*/
5709 (unaryfunc)long_invert, /*nb_invert*/
5710 long_lshift, /*nb_lshift*/
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03005711 long_rshift, /*nb_rshift*/
Mark Dickinson22b20182010-05-10 21:27:53 +00005712 long_and, /*nb_and*/
5713 long_xor, /*nb_xor*/
5714 long_or, /*nb_or*/
5715 long_long, /*nb_int*/
5716 0, /*nb_reserved*/
5717 long_float, /*nb_float*/
5718 0, /* nb_inplace_add */
5719 0, /* nb_inplace_subtract */
5720 0, /* nb_inplace_multiply */
5721 0, /* nb_inplace_remainder */
5722 0, /* nb_inplace_power */
5723 0, /* nb_inplace_lshift */
5724 0, /* nb_inplace_rshift */
5725 0, /* nb_inplace_and */
5726 0, /* nb_inplace_xor */
5727 0, /* nb_inplace_or */
5728 long_div, /* nb_floor_divide */
5729 long_true_divide, /* nb_true_divide */
5730 0, /* nb_inplace_floor_divide */
5731 0, /* nb_inplace_true_divide */
5732 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005733};
5734
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005735PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5737 "int", /* tp_name */
5738 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5739 sizeof(digit), /* tp_itemsize */
Inada Naoki7d408692019-05-29 17:23:27 +09005740 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005741 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 0, /* tp_getattr */
5743 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005744 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005745 long_to_decimal_string, /* tp_repr */
5746 &long_as_number, /* tp_as_number */
5747 0, /* tp_as_sequence */
5748 0, /* tp_as_mapping */
5749 (hashfunc)long_hash, /* tp_hash */
5750 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03005751 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 PyObject_GenericGetAttr, /* tp_getattro */
5753 0, /* tp_setattro */
5754 0, /* tp_as_buffer */
5755 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5756 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5757 long_doc, /* tp_doc */
5758 0, /* tp_traverse */
5759 0, /* tp_clear */
5760 long_richcompare, /* tp_richcompare */
5761 0, /* tp_weaklistoffset */
5762 0, /* tp_iter */
5763 0, /* tp_iternext */
5764 long_methods, /* tp_methods */
5765 0, /* tp_members */
5766 long_getset, /* tp_getset */
5767 0, /* tp_base */
5768 0, /* tp_dict */
5769 0, /* tp_descr_get */
5770 0, /* tp_descr_set */
5771 0, /* tp_dictoffset */
5772 0, /* tp_init */
5773 0, /* tp_alloc */
5774 long_new, /* tp_new */
5775 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005776};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005777
Mark Dickinsonbd792642009-03-18 20:06:12 +00005778static PyTypeObject Int_InfoType;
5779
5780PyDoc_STRVAR(int_info__doc__,
5781"sys.int_info\n\
5782\n\
5783A struct sequence that holds information about Python's\n\
5784internal representation of integers. The attributes are read only.");
5785
5786static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005787 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005788 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005789 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005790};
5791
5792static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 "sys.int_info", /* name */
5794 int_info__doc__, /* doc */
5795 int_info_fields, /* fields */
5796 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005797};
5798
5799PyObject *
5800PyLong_GetInfo(void)
5801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005802 PyObject* int_info;
5803 int field = 0;
5804 int_info = PyStructSequence_New(&Int_InfoType);
5805 if (int_info == NULL)
5806 return NULL;
5807 PyStructSequence_SET_ITEM(int_info, field++,
5808 PyLong_FromLong(PyLong_SHIFT));
5809 PyStructSequence_SET_ITEM(int_info, field++,
5810 PyLong_FromLong(sizeof(digit)));
5811 if (PyErr_Occurred()) {
5812 Py_CLEAR(int_info);
5813 return NULL;
5814 }
5815 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005816}
5817
Guido van Rossumddefaf32007-01-14 03:31:43 +00005818int
5819_PyLong_Init(void)
5820{
5821#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 int ival, size;
5823 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005825 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5826 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5827 if (Py_TYPE(v) == &PyLong_Type) {
5828 /* The element is already initialized, most likely
5829 * the Python interpreter was initialized before.
5830 */
5831 Py_ssize_t refcnt;
5832 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5835 _Py_NewReference(op);
5836 /* _Py_NewReference sets the ref count to 1 but
5837 * the ref count might be larger. Set the refcnt
5838 * to the original refcnt + 1 */
5839 Py_REFCNT(op) = refcnt + 1;
5840 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005841 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005842 }
5843 else {
Victor Stinnerb509d522018-11-23 14:27:38 +01005844 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 }
5846 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005847 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005848 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005849#endif
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005850 _PyLong_Zero = PyLong_FromLong(0);
5851 if (_PyLong_Zero == NULL)
5852 return 0;
5853 _PyLong_One = PyLong_FromLong(1);
5854 if (_PyLong_One == NULL)
5855 return 0;
5856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005857 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005858 if (Int_InfoType.tp_name == NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005859 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02005860 return 0;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01005861 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02005862 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005864 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005865}
5866
5867void
Victor Stinnerbed48172019-08-27 00:12:32 +02005868_PyLong_Fini(void)
Guido van Rossumddefaf32007-01-14 03:31:43 +00005869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005870 /* Integers are currently statically allocated. Py_DECREF is not
5871 needed, but Python must forget about the reference or multiple
5872 reinitializations will fail. */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005873 Py_CLEAR(_PyLong_One);
5874 Py_CLEAR(_PyLong_Zero);
Guido van Rossumddefaf32007-01-14 03:31:43 +00005875#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005876 int i;
5877 PyLongObject *v = small_ints;
5878 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5879 _Py_DEC_REFTOTAL;
5880 _Py_ForgetReference((PyObject*)v);
5881 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005882#endif
5883}