Branch data Line data Source code
1 : : /* Long (arbitrary precision) integer object implementation */
2 : :
3 : : /* XXX The functional organization of this file is terrible */
4 : :
5 : : #include "Python.h"
6 : : #include "pycore_bitutils.h" // _Py_popcount32()
7 : : #include "pycore_initconfig.h" // _PyStatus_OK()
8 : : #include "pycore_long.h" // _Py_SmallInts
9 : : #include "pycore_object.h" // _PyObject_InitVar()
10 : : #include "pycore_pystate.h" // _Py_IsMainInterpreter()
11 : : #include "pycore_runtime.h" // _PY_NSMALLPOSINTS
12 : : #include "pycore_structseq.h" // _PyStructSequence_FiniType()
13 : :
14 : : #include <ctype.h>
15 : : #include <float.h>
16 : : #include <stddef.h>
17 : : #include <stdlib.h> // abs()
18 : :
19 : : #include "clinic/longobject.c.h"
20 : : /*[clinic input]
21 : : class int "PyObject *" "&PyLong_Type"
22 : : [clinic start generated code]*/
23 : : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
24 : :
25 : : /* Is this PyLong of size 1, 0 or -1? */
26 : : #define IS_MEDIUM_VALUE(x) (((size_t)Py_SIZE(x)) + 1U < 3U)
27 : :
28 : : /* convert a PyLong of size 1, 0 or -1 to a C integer */
29 : : static inline stwodigits
30 : 8100669 : medium_value(PyLongObject *x)
31 : : {
32 : : assert(IS_MEDIUM_VALUE(x));
33 : 8100669 : return ((stwodigits)Py_SIZE(x)) * x->long_value.ob_digit[0];
34 : : }
35 : :
36 : : #define IS_SMALL_INT(ival) (-_PY_NSMALLNEGINTS <= (ival) && (ival) < _PY_NSMALLPOSINTS)
37 : : #define IS_SMALL_UINT(ival) ((ival) < _PY_NSMALLPOSINTS)
38 : :
39 : : #define _MAX_STR_DIGITS_ERROR_FMT_TO_INT "Exceeds the limit (%d digits) for integer string conversion: value has %zd digits; use sys.set_int_max_str_digits() to increase the limit"
40 : : #define _MAX_STR_DIGITS_ERROR_FMT_TO_STR "Exceeds the limit (%d digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit"
41 : :
42 : : /* If defined, use algorithms from the _pylong.py module */
43 : : #define WITH_PYLONG_MODULE 1
44 : :
45 : : static inline void
46 : 459221 : _Py_DECREF_INT(PyLongObject *op)
47 : : {
48 : : assert(PyLong_CheckExact(op));
49 : 459221 : _Py_DECREF_SPECIALIZED((PyObject *)op, (destructor)PyObject_Free);
50 : 459221 : }
51 : :
52 : : static inline int
53 : 1492606 : is_medium_int(stwodigits x)
54 : : {
55 : : /* Take care that we are comparing unsigned values. */
56 : 1492606 : twodigits x_plus_mask = ((twodigits)x) + PyLong_MASK;
57 : 1492606 : return x_plus_mask < ((twodigits)PyLong_MASK) + PyLong_BASE;
58 : : }
59 : :
60 : : static PyObject *
61 : 7079198 : get_small_int(sdigit ival)
62 : : {
63 : : assert(IS_SMALL_INT(ival));
64 : 7079198 : PyObject *v = (PyObject *)&_PyLong_SMALL_INTS[_PY_NSMALLNEGINTS + ival];
65 : 7079198 : return Py_NewRef(v);
66 : : }
67 : :
68 : : static PyLongObject *
69 : 1104435 : maybe_small_long(PyLongObject *v)
70 : : {
71 [ + - + + ]: 1104435 : if (v && IS_MEDIUM_VALUE(v)) {
72 : 139204 : stwodigits ival = medium_value(v);
73 [ + + + + ]: 139204 : if (IS_SMALL_INT(ival)) {
74 : 132913 : _Py_DECREF_INT(v);
75 : 132913 : return (PyLongObject *)get_small_int((sdigit)ival);
76 : : }
77 : : }
78 : 971522 : return v;
79 : : }
80 : :
81 : : /* For int multiplication, use the O(N**2) school algorithm unless
82 : : * both operands contain more than KARATSUBA_CUTOFF digits (this
83 : : * being an internal Python int digit, in base BASE).
84 : : */
85 : : #define KARATSUBA_CUTOFF 70
86 : : #define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
87 : :
88 : : /* For exponentiation, use the binary left-to-right algorithm unless the
89 : : ^ exponent contains more than HUGE_EXP_CUTOFF bits. In that case, do
90 : : * (no more than) EXP_WINDOW_SIZE bits at a time. The potential drawback is
91 : : * that a table of 2**(EXP_WINDOW_SIZE - 1) intermediate results is
92 : : * precomputed.
93 : : */
94 : : #define EXP_WINDOW_SIZE 5
95 : : #define EXP_TABLE_LEN (1 << (EXP_WINDOW_SIZE - 1))
96 : : /* Suppose the exponent has bit length e. All ways of doing this
97 : : * need e squarings. The binary method also needs a multiply for
98 : : * each bit set. In a k-ary method with window width w, a multiply
99 : : * for each non-zero window, so at worst (and likely!)
100 : : * ceiling(e/w). The k-ary sliding window method has the same
101 : : * worst case, but the window slides so it can sometimes skip
102 : : * over an all-zero window that the fixed-window method can't
103 : : * exploit. In addition, the windowing methods need multiplies
104 : : * to precompute a table of small powers.
105 : : *
106 : : * For the sliding window method with width 5, 16 precomputation
107 : : * multiplies are needed. Assuming about half the exponent bits
108 : : * are set, then, the binary method needs about e/2 extra mults
109 : : * and the window method about 16 + e/5.
110 : : *
111 : : * The latter is smaller for e > 53 1/3. We don't have direct
112 : : * access to the bit length, though, so call it 60, which is a
113 : : * multiple of a long digit's max bit length (15 or 30 so far).
114 : : */
115 : : #define HUGE_EXP_CUTOFF 60
116 : :
117 : : #define SIGCHECK(PyTryBlock) \
118 : : do { \
119 : : if (PyErr_CheckSignals()) PyTryBlock \
120 : : } while(0)
121 : :
122 : : /* Normalize (remove leading zeros from) an int object.
123 : : Doesn't attempt to free the storage--in most cases, due to the nature
124 : : of the algorithms used, this could save at most be one word anyway. */
125 : :
126 : : static PyLongObject *
127 : 2476354 : long_normalize(PyLongObject *v)
128 : : {
129 [ + + ]: 2476354 : Py_ssize_t j = Py_ABS(Py_SIZE(v));
130 : 2476354 : Py_ssize_t i = j;
131 : :
132 [ + + + + ]: 6345161 : while (i > 0 && v->long_value.ob_digit[i-1] == 0)
133 : 3868807 : --i;
134 [ + + ]: 2476354 : if (i != j) {
135 [ + + ]: 1278394 : Py_SET_SIZE(v, (Py_SIZE(v) < 0) ? -(i) : i);
136 : : }
137 : 2476354 : return v;
138 : : }
139 : :
140 : : /* Allocate a new int object with size digits.
141 : : Return NULL and set exception if we run out of memory. */
142 : :
143 : : #define MAX_LONG_DIGITS \
144 : : ((PY_SSIZE_T_MAX - offsetof(PyLongObject, long_value.ob_digit))/sizeof(digit))
145 : :
146 : : PyLongObject *
147 : 5001469 : _PyLong_New(Py_ssize_t size)
148 : : {
149 : : PyLongObject *result;
150 [ - + ]: 5001469 : if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
151 : 0 : PyErr_SetString(PyExc_OverflowError,
152 : : "too many digits in integer");
153 : 0 : return NULL;
154 : : }
155 : : /* Fast operations for single digit integers (including zero)
156 : : * assume that there is always at least one digit present. */
157 [ + + ]: 5001469 : Py_ssize_t ndigits = size ? size : 1;
158 : : /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
159 : : sizeof(digit)*size. Previous incarnations of this code used
160 : : sizeof(PyVarObject) instead of the offsetof, but this risks being
161 : : incorrect in the presence of padding between the PyVarObject header
162 : : and the digits. */
163 : 5001469 : result = PyObject_Malloc(offsetof(PyLongObject, long_value.ob_digit) +
164 : : ndigits*sizeof(digit));
165 [ - + ]: 5001469 : if (!result) {
166 : 0 : PyErr_NoMemory();
167 : 0 : return NULL;
168 : : }
169 : 5001469 : _PyObject_InitVar((PyVarObject*)result, &PyLong_Type, size);
170 : 5001469 : return result;
171 : : }
172 : :
173 : : PyObject *
174 : 1214 : _PyLong_Copy(PyLongObject *src)
175 : : {
176 : : PyLongObject *result;
177 : : Py_ssize_t i;
178 : :
179 : : assert(src != NULL);
180 : 1214 : i = Py_SIZE(src);
181 [ + + ]: 1214 : if (i < 0)
182 : 1083 : i = -(i);
183 [ + + ]: 1214 : if (i < 2) {
184 : 40 : stwodigits ival = medium_value(src);
185 [ + - + - ]: 40 : if (IS_SMALL_INT(ival)) {
186 : 40 : return get_small_int((sdigit)ival);
187 : : }
188 : : }
189 : 1174 : result = _PyLong_New(i);
190 [ + - ]: 1174 : if (result != NULL) {
191 : 1174 : Py_SET_SIZE(result, Py_SIZE(src));
192 [ + + ]: 6320 : while (--i >= 0) {
193 : 5146 : result->long_value.ob_digit[i] = src->long_value.ob_digit[i];
194 : : }
195 : : }
196 : 1174 : return (PyObject *)result;
197 : : }
198 : :
199 : : static PyObject *
200 : 2735177 : _PyLong_FromMedium(sdigit x)
201 : : {
202 : : assert(!IS_SMALL_INT(x));
203 : : assert(is_medium_int(x));
204 : : /* We could use a freelist here */
205 : 2735177 : PyLongObject *v = PyObject_Malloc(sizeof(PyLongObject));
206 [ - + ]: 2735177 : if (v == NULL) {
207 : 0 : PyErr_NoMemory();
208 : 0 : return NULL;
209 : : }
210 [ + + ]: 2735177 : Py_ssize_t sign = x < 0 ? -1: 1;
211 : 2735177 : digit abs_x = x < 0 ? -x : x;
212 : 2735177 : _PyObject_InitVar((PyVarObject*)v, &PyLong_Type, sign);
213 : 2735177 : v->long_value.ob_digit[0] = abs_x;
214 : 2735177 : return (PyObject*)v;
215 : : }
216 : :
217 : : static PyObject *
218 : 101381 : _PyLong_FromLarge(stwodigits ival)
219 : : {
220 : : twodigits abs_ival;
221 : : int sign;
222 : : assert(!is_medium_int(ival));
223 : :
224 [ + + ]: 101381 : if (ival < 0) {
225 : : /* negate: can't write this as abs_ival = -ival since that
226 : : invokes undefined behaviour when ival is LONG_MIN */
227 : 3 : abs_ival = 0U-(twodigits)ival;
228 : 3 : sign = -1;
229 : : }
230 : : else {
231 : 101378 : abs_ival = (twodigits)ival;
232 : 101378 : sign = 1;
233 : : }
234 : : /* Must be at least two digits */
235 : : assert(abs_ival >> PyLong_SHIFT != 0);
236 : 101381 : twodigits t = abs_ival >> (PyLong_SHIFT * 2);
237 : 101381 : Py_ssize_t ndigits = 2;
238 [ - + ]: 101381 : while (t) {
239 : 0 : ++ndigits;
240 : 0 : t >>= PyLong_SHIFT;
241 : : }
242 : 101381 : PyLongObject *v = _PyLong_New(ndigits);
243 [ + - ]: 101381 : if (v != NULL) {
244 : 101381 : digit *p = v->long_value.ob_digit;
245 : 101381 : Py_SET_SIZE(v, ndigits * sign);
246 : 101381 : t = abs_ival;
247 [ + + ]: 304143 : while (t) {
248 : 202762 : *p++ = Py_SAFE_DOWNCAST(
249 : : t & PyLong_MASK, twodigits, digit);
250 : 202762 : t >>= PyLong_SHIFT;
251 : : }
252 : : }
253 : 101381 : return (PyObject *)v;
254 : : }
255 : :
256 : : /* Create a new int object from a C word-sized int */
257 : : static inline PyObject *
258 : 4039689 : _PyLong_FromSTwoDigits(stwodigits x)
259 : : {
260 [ + + + + ]: 4039689 : if (IS_SMALL_INT(x)) {
261 : 2547083 : return get_small_int((sdigit)x);
262 : : }
263 : : assert(x != 0);
264 [ + + ]: 1492606 : if (is_medium_int(x)) {
265 : 1391225 : return _PyLong_FromMedium((sdigit)x);
266 : : }
267 : 101381 : return _PyLong_FromLarge(x);
268 : : }
269 : :
270 : : int
271 : 0 : _PyLong_AssignValue(PyObject **target, Py_ssize_t value)
272 : : {
273 : 0 : PyObject *old = *target;
274 [ # # # # ]: 0 : if (IS_SMALL_INT(value)) {
275 : 0 : *target = get_small_int(Py_SAFE_DOWNCAST(value, Py_ssize_t, sdigit));
276 : 0 : Py_XDECREF(old);
277 : 0 : return 0;
278 : : }
279 [ # # # # : 0 : else if (old != NULL && PyLong_CheckExact(old) &&
# # ]
280 [ # # ]: 0 : Py_REFCNT(old) == 1 && Py_SIZE(old) == 1 &&
281 [ # # ]: 0 : (size_t)value <= PyLong_MASK)
282 : : {
283 : : // Mutate in place if there are no other references the old
284 : : // object. This avoids an allocation in a common case.
285 : : // Since the primary use-case is iterating over ranges, which
286 : : // are typically positive, only do this optimization
287 : : // for positive integers (for now).
288 : 0 : ((PyLongObject *)old)->long_value.ob_digit[0] =
289 : 0 : Py_SAFE_DOWNCAST(value, Py_ssize_t, digit);
290 : 0 : return 0;
291 : : }
292 : : else {
293 : 0 : *target = PyLong_FromSsize_t(value);
294 : 0 : Py_XDECREF(old);
295 [ # # ]: 0 : if (*target == NULL) {
296 : 0 : return -1;
297 : : }
298 : 0 : return 0;
299 : : }
300 : : }
301 : :
302 : : /* If a freshly-allocated int is already shared, it must
303 : : be a small integer, so negating it must go to PyLong_FromLong */
304 : : Py_LOCAL_INLINE(void)
305 : 12621 : _PyLong_Negate(PyLongObject **x_p)
306 : : {
307 : : PyLongObject *x;
308 : :
309 : 12621 : x = (PyLongObject *)*x_p;
310 [ + - ]: 12621 : if (Py_REFCNT(x) == 1) {
311 : 12621 : Py_SET_SIZE(x, -Py_SIZE(x));
312 : 12621 : return;
313 : : }
314 : :
315 : 0 : *x_p = (PyLongObject *)_PyLong_FromSTwoDigits(-medium_value(x));
316 : 0 : Py_DECREF(x);
317 : : }
318 : :
319 : : /* Create a new int object from a C long int */
320 : :
321 : : PyObject *
322 : 4755647 : PyLong_FromLong(long ival)
323 : : {
324 : : PyLongObject *v;
325 : : unsigned long abs_ival, t;
326 : : int ndigits;
327 : :
328 : : /* Handle small and medium cases. */
329 [ + + + + ]: 4755647 : if (IS_SMALL_INT(ival)) {
330 : 2895988 : return get_small_int((sdigit)ival);
331 : : }
332 [ + + + + ]: 1859659 : if (-(long)PyLong_MASK <= ival && ival <= (long)PyLong_MASK) {
333 : 1338418 : return _PyLong_FromMedium((sdigit)ival);
334 : : }
335 : :
336 : : /* Count digits (at least two - smaller cases were handled above). */
337 [ + + ]: 521241 : abs_ival = ival < 0 ? 0U-(unsigned long)ival : (unsigned long)ival;
338 : : /* Do shift in two steps to avoid possible undefined behavior. */
339 : 521241 : t = abs_ival >> PyLong_SHIFT >> PyLong_SHIFT;
340 : 521241 : ndigits = 2;
341 [ + + ]: 521253 : while (t) {
342 : 12 : ++ndigits;
343 : 12 : t >>= PyLong_SHIFT;
344 : : }
345 : :
346 : : /* Construct output value. */
347 : 521241 : v = _PyLong_New(ndigits);
348 [ + - ]: 521241 : if (v != NULL) {
349 : 521241 : digit *p = v->long_value.ob_digit;
350 [ + + ]: 521241 : Py_SET_SIZE(v, ival < 0 ? -ndigits : ndigits);
351 : 521241 : t = abs_ival;
352 [ + + ]: 1563735 : while (t) {
353 : 1042494 : *p++ = (digit)(t & PyLong_MASK);
354 : 1042494 : t >>= PyLong_SHIFT;
355 : : }
356 : : }
357 : 521241 : return (PyObject *)v;
358 : : }
359 : :
360 : : #define PYLONG_FROM_UINT(INT_TYPE, ival) \
361 : : do { \
362 : : if (IS_SMALL_UINT(ival)) { \
363 : : return get_small_int((sdigit)(ival)); \
364 : : } \
365 : : /* Count the number of Python digits. */ \
366 : : Py_ssize_t ndigits = 0; \
367 : : INT_TYPE t = (ival); \
368 : : while (t) { \
369 : : ++ndigits; \
370 : : t >>= PyLong_SHIFT; \
371 : : } \
372 : : PyLongObject *v = _PyLong_New(ndigits); \
373 : : if (v == NULL) { \
374 : : return NULL; \
375 : : } \
376 : : digit *p = v->long_value.ob_digit; \
377 : : while ((ival)) { \
378 : : *p++ = (digit)((ival) & PyLong_MASK); \
379 : : (ival) >>= PyLong_SHIFT; \
380 : : } \
381 : : return (PyObject *)v; \
382 : : } while(0)
383 : :
384 : : /* Create a new int object from a C unsigned long int */
385 : :
386 : : PyObject *
387 : 1176208 : PyLong_FromUnsignedLong(unsigned long ival)
388 : : {
389 [ + + + + : 3877414 : PYLONG_FROM_UINT(unsigned long, ival);
- + + + ]
390 : : }
391 : :
392 : : /* Create a new int object from a C unsigned long long int. */
393 : :
394 : : PyObject *
395 : 141030 : PyLong_FromUnsignedLongLong(unsigned long long ival)
396 : : {
397 [ + + + + : 679438 : PYLONG_FROM_UINT(unsigned long long, ival);
- + + + ]
398 : : }
399 : :
400 : : /* Create a new int object from a C size_t. */
401 : :
402 : : PyObject *
403 : 1027 : PyLong_FromSize_t(size_t ival)
404 : : {
405 [ + - - - : 1027 : PYLONG_FROM_UINT(size_t, ival);
- - - - ]
406 : : }
407 : :
408 : : /* Create a new int object from a C double */
409 : :
410 : : PyObject *
411 : 550204 : PyLong_FromDouble(double dval)
412 : : {
413 : : /* Try to get out cheap if this fits in a long. When a finite value of real
414 : : * floating type is converted to an integer type, the value is truncated
415 : : * toward zero. If the value of the integral part cannot be represented by
416 : : * the integer type, the behavior is undefined. Thus, we must check that
417 : : * value is in range (LONG_MIN - 1, LONG_MAX + 1). If a long has more bits
418 : : * of precision than a double, casting LONG_MIN - 1 to double may yield an
419 : : * approximation, but LONG_MAX + 1 is a power of two and can be represented
420 : : * as double exactly (assuming FLT_RADIX is 2 or 16), so for simplicity
421 : : * check against [-(LONG_MAX + 1), LONG_MAX + 1).
422 : : */
423 : 550204 : const double int_max = (unsigned long)LONG_MAX + 1;
424 [ + - + - ]: 550204 : if (-int_max < dval && dval < int_max) {
425 : 550204 : return PyLong_FromLong((long)dval);
426 : : }
427 : :
428 : : PyLongObject *v;
429 : : double frac;
430 : : int i, ndig, expo, neg;
431 : 0 : neg = 0;
432 [ # # ]: 0 : if (Py_IS_INFINITY(dval)) {
433 : 0 : PyErr_SetString(PyExc_OverflowError,
434 : : "cannot convert float infinity to integer");
435 : 0 : return NULL;
436 : : }
437 [ # # ]: 0 : if (Py_IS_NAN(dval)) {
438 : 0 : PyErr_SetString(PyExc_ValueError,
439 : : "cannot convert float NaN to integer");
440 : 0 : return NULL;
441 : : }
442 [ # # ]: 0 : if (dval < 0.0) {
443 : 0 : neg = 1;
444 : 0 : dval = -dval;
445 : : }
446 : 0 : frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
447 : : assert(expo > 0);
448 : 0 : ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
449 : 0 : v = _PyLong_New(ndig);
450 [ # # ]: 0 : if (v == NULL)
451 : 0 : return NULL;
452 : 0 : frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
453 [ # # ]: 0 : for (i = ndig; --i >= 0; ) {
454 : 0 : digit bits = (digit)frac;
455 : 0 : v->long_value.ob_digit[i] = bits;
456 : 0 : frac = frac - (double)bits;
457 : 0 : frac = ldexp(frac, PyLong_SHIFT);
458 : : }
459 [ # # ]: 0 : if (neg) {
460 : 0 : Py_SET_SIZE(v, -(Py_SIZE(v)));
461 : : }
462 : 0 : return (PyObject *)v;
463 : : }
464 : :
465 : : /* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
466 : : * anything about what happens when a signed integer operation overflows,
467 : : * and some compilers think they're doing you a favor by being "clever"
468 : : * then. The bit pattern for the largest positive signed long is
469 : : * (unsigned long)LONG_MAX, and for the smallest negative signed long
470 : : * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
471 : : * However, some other compilers warn about applying unary minus to an
472 : : * unsigned operand. Hence the weird "0-".
473 : : */
474 : : #define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
475 : : #define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
476 : :
477 : : /* Get a C long int from an int object or any object that has an __index__
478 : : method.
479 : :
480 : : On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
481 : : the result. Otherwise *overflow is 0.
482 : :
483 : : For other errors (e.g., TypeError), return -1 and set an error condition.
484 : : In this case *overflow will be 0.
485 : : */
486 : :
487 : : long
488 : 1815326 : PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
489 : : {
490 : : /* This version by Tim Peters */
491 : : PyLongObject *v;
492 : : unsigned long x, prev;
493 : : long res;
494 : : Py_ssize_t i;
495 : : int sign;
496 : 1815326 : int do_decref = 0; /* if PyNumber_Index was called */
497 : :
498 : 1815326 : *overflow = 0;
499 [ - + ]: 1815326 : if (vv == NULL) {
500 : 0 : PyErr_BadInternalCall();
501 : 0 : return -1;
502 : : }
503 : :
504 [ + + ]: 1815326 : if (PyLong_Check(vv)) {
505 : 1813893 : v = (PyLongObject *)vv;
506 : : }
507 : : else {
508 : 1433 : v = (PyLongObject *)_PyNumber_Index(vv);
509 [ + - ]: 1433 : if (v == NULL)
510 : 1433 : return -1;
511 : 0 : do_decref = 1;
512 : : }
513 : :
514 : 1813893 : res = -1;
515 : 1813893 : i = Py_SIZE(v);
516 : :
517 [ + + + + ]: 1813893 : switch (i) {
518 : 25364 : case -1:
519 : 25364 : res = -(sdigit)v->long_value.ob_digit[0];
520 : 25364 : break;
521 : 75910 : case 0:
522 : 75910 : res = 0;
523 : 75910 : break;
524 : 1712275 : case 1:
525 : 1712275 : res = v->long_value.ob_digit[0];
526 : 1712275 : break;
527 : 344 : default:
528 : 344 : sign = 1;
529 : 344 : x = 0;
530 [ + + ]: 344 : if (i < 0) {
531 : 24 : sign = -1;
532 : 24 : i = -(i);
533 : : }
534 [ + + ]: 1043 : while (--i >= 0) {
535 : 790 : prev = x;
536 : 790 : x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
537 [ + + ]: 790 : if ((x >> PyLong_SHIFT) != prev) {
538 : 91 : *overflow = sign;
539 : 91 : goto exit;
540 : : }
541 : : }
542 : : /* Haven't lost any bits, but casting to long requires extra
543 : : * care (see comment above).
544 : : */
545 [ + + ]: 253 : if (x <= (unsigned long)LONG_MAX) {
546 : 249 : res = (long)x * sign;
547 : : }
548 [ - + - - ]: 4 : else if (sign < 0 && x == PY_ABS_LONG_MIN) {
549 : 0 : res = LONG_MIN;
550 : : }
551 : : else {
552 : 4 : *overflow = sign;
553 : : /* res is already set to -1 */
554 : : }
555 : : }
556 : 1813893 : exit:
557 [ - + ]: 1813893 : if (do_decref) {
558 : 0 : Py_DECREF(v);
559 : : }
560 : 1813893 : return res;
561 : : }
562 : :
563 : : /* Get a C long int from an int object or any object that has an __index__
564 : : method. Return -1 and set an error if overflow occurs. */
565 : :
566 : : long
567 : 822035 : PyLong_AsLong(PyObject *obj)
568 : : {
569 : : int overflow;
570 : 822035 : long result = PyLong_AsLongAndOverflow(obj, &overflow);
571 [ + + ]: 822035 : if (overflow) {
572 : : /* XXX: could be cute and give a different
573 : : message for overflow == -1 */
574 : 25 : PyErr_SetString(PyExc_OverflowError,
575 : : "Python int too large to convert to C long");
576 : : }
577 : 822035 : return result;
578 : : }
579 : :
580 : : /* Get a C int from an int object or any object that has an __index__
581 : : method. Return -1 and set an error if overflow occurs. */
582 : :
583 : : int
584 : 374007 : _PyLong_AsInt(PyObject *obj)
585 : : {
586 : : int overflow;
587 : 374007 : long result = PyLong_AsLongAndOverflow(obj, &overflow);
588 [ + - + - : 374007 : if (overflow || result > INT_MAX || result < INT_MIN) {
- + ]
589 : : /* XXX: could be cute and give a different
590 : : message for overflow == -1 */
591 : 0 : PyErr_SetString(PyExc_OverflowError,
592 : : "Python int too large to convert to C int");
593 : 0 : return -1;
594 : : }
595 : 374007 : return (int)result;
596 : : }
597 : :
598 : : /* Get a Py_ssize_t from an int object.
599 : : Returns -1 and sets an error condition if overflow occurs. */
600 : :
601 : : Py_ssize_t
602 : 1910603 : PyLong_AsSsize_t(PyObject *vv) {
603 : : PyLongObject *v;
604 : : size_t x, prev;
605 : : Py_ssize_t i;
606 : : int sign;
607 : :
608 [ - + ]: 1910603 : if (vv == NULL) {
609 : 0 : PyErr_BadInternalCall();
610 : 0 : return -1;
611 : : }
612 [ - + ]: 1910603 : if (!PyLong_Check(vv)) {
613 : 0 : PyErr_SetString(PyExc_TypeError, "an integer is required");
614 : 0 : return -1;
615 : : }
616 : :
617 : 1910603 : v = (PyLongObject *)vv;
618 : 1910603 : i = Py_SIZE(v);
619 [ + + + + ]: 1910603 : switch (i) {
620 : 3113 : case -1: return -(sdigit)v->long_value.ob_digit[0];
621 : 244096 : case 0: return 0;
622 : 1663077 : case 1: return v->long_value.ob_digit[0];
623 : : }
624 : 317 : sign = 1;
625 : 317 : x = 0;
626 [ + + ]: 317 : if (i < 0) {
627 : 8 : sign = -1;
628 : 8 : i = -(i);
629 : : }
630 [ + + ]: 1267 : while (--i >= 0) {
631 : 950 : prev = x;
632 : 950 : x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
633 [ - + ]: 950 : if ((x >> PyLong_SHIFT) != prev)
634 : 0 : goto overflow;
635 : : }
636 : : /* Haven't lost any bits, but casting to a signed type requires
637 : : * extra care (see comment above).
638 : : */
639 [ + - ]: 317 : if (x <= (size_t)PY_SSIZE_T_MAX) {
640 : 317 : return (Py_ssize_t)x * sign;
641 : : }
642 [ # # # # ]: 0 : else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
643 : 0 : return PY_SSIZE_T_MIN;
644 : : }
645 : : /* else overflow */
646 : :
647 : 0 : overflow:
648 : 0 : PyErr_SetString(PyExc_OverflowError,
649 : : "Python int too large to convert to C ssize_t");
650 : 0 : return -1;
651 : : }
652 : :
653 : : /* Get a C unsigned long int from an int object.
654 : : Returns -1 and sets an error condition if overflow occurs. */
655 : :
656 : : unsigned long
657 : 5780 : PyLong_AsUnsignedLong(PyObject *vv)
658 : : {
659 : : PyLongObject *v;
660 : : unsigned long x, prev;
661 : : Py_ssize_t i;
662 : :
663 [ - + ]: 5780 : if (vv == NULL) {
664 : 0 : PyErr_BadInternalCall();
665 : 0 : return (unsigned long)-1;
666 : : }
667 [ - + ]: 5780 : if (!PyLong_Check(vv)) {
668 : 0 : PyErr_SetString(PyExc_TypeError, "an integer is required");
669 : 0 : return (unsigned long)-1;
670 : : }
671 : :
672 : 5780 : v = (PyLongObject *)vv;
673 : 5780 : i = Py_SIZE(v);
674 : 5780 : x = 0;
675 [ - + ]: 5780 : if (i < 0) {
676 : 0 : PyErr_SetString(PyExc_OverflowError,
677 : : "can't convert negative value to unsigned int");
678 : 0 : return (unsigned long) -1;
679 : : }
680 [ + + + ]: 5780 : switch (i) {
681 : 1026 : case 0: return 0;
682 : 4465 : case 1: return v->long_value.ob_digit[0];
683 : : }
684 [ + + ]: 867 : while (--i >= 0) {
685 : 578 : prev = x;
686 : 578 : x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
687 [ - + ]: 578 : if ((x >> PyLong_SHIFT) != prev) {
688 : 0 : PyErr_SetString(PyExc_OverflowError,
689 : : "Python int too large to convert "
690 : : "to C unsigned long");
691 : 0 : return (unsigned long) -1;
692 : : }
693 : : }
694 : 289 : return x;
695 : : }
696 : :
697 : : /* Get a C size_t from an int object. Returns (size_t)-1 and sets
698 : : an error condition if overflow occurs. */
699 : :
700 : : size_t
701 : 91 : PyLong_AsSize_t(PyObject *vv)
702 : : {
703 : : PyLongObject *v;
704 : : size_t x, prev;
705 : : Py_ssize_t i;
706 : :
707 [ - + ]: 91 : if (vv == NULL) {
708 : 0 : PyErr_BadInternalCall();
709 : 0 : return (size_t) -1;
710 : : }
711 [ - + ]: 91 : if (!PyLong_Check(vv)) {
712 : 0 : PyErr_SetString(PyExc_TypeError, "an integer is required");
713 : 0 : return (size_t)-1;
714 : : }
715 : :
716 : 91 : v = (PyLongObject *)vv;
717 : 91 : i = Py_SIZE(v);
718 : 91 : x = 0;
719 [ - + ]: 91 : if (i < 0) {
720 : 0 : PyErr_SetString(PyExc_OverflowError,
721 : : "can't convert negative value to size_t");
722 : 0 : return (size_t) -1;
723 : : }
724 [ - + - ]: 91 : switch (i) {
725 : 0 : case 0: return 0;
726 : 91 : case 1: return v->long_value.ob_digit[0];
727 : : }
728 [ # # ]: 0 : while (--i >= 0) {
729 : 0 : prev = x;
730 : 0 : x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
731 [ # # ]: 0 : if ((x >> PyLong_SHIFT) != prev) {
732 : 0 : PyErr_SetString(PyExc_OverflowError,
733 : : "Python int too large to convert to C size_t");
734 : 0 : return (size_t) -1;
735 : : }
736 : : }
737 : 0 : return x;
738 : : }
739 : :
740 : : /* Get a C unsigned long int from an int object, ignoring the high bits.
741 : : Returns -1 and sets an error condition if an error occurs. */
742 : :
743 : : static unsigned long
744 : 6 : _PyLong_AsUnsignedLongMask(PyObject *vv)
745 : : {
746 : : PyLongObject *v;
747 : : unsigned long x;
748 : : Py_ssize_t i;
749 : : int sign;
750 : :
751 [ + - - + ]: 6 : if (vv == NULL || !PyLong_Check(vv)) {
752 : 0 : PyErr_BadInternalCall();
753 : 0 : return (unsigned long) -1;
754 : : }
755 : 6 : v = (PyLongObject *)vv;
756 : 6 : i = Py_SIZE(v);
757 [ - + - ]: 6 : switch (i) {
758 : 0 : case 0: return 0;
759 : 6 : case 1: return v->long_value.ob_digit[0];
760 : : }
761 : 0 : sign = 1;
762 : 0 : x = 0;
763 [ # # ]: 0 : if (i < 0) {
764 : 0 : sign = -1;
765 : 0 : i = -i;
766 : : }
767 [ # # ]: 0 : while (--i >= 0) {
768 : 0 : x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
769 : : }
770 : 0 : return x * sign;
771 : : }
772 : :
773 : : unsigned long
774 : 6 : PyLong_AsUnsignedLongMask(PyObject *op)
775 : : {
776 : : PyLongObject *lo;
777 : : unsigned long val;
778 : :
779 [ - + ]: 6 : if (op == NULL) {
780 : 0 : PyErr_BadInternalCall();
781 : 0 : return (unsigned long)-1;
782 : : }
783 : :
784 [ + - ]: 6 : if (PyLong_Check(op)) {
785 : 6 : return _PyLong_AsUnsignedLongMask(op);
786 : : }
787 : :
788 : 0 : lo = (PyLongObject *)_PyNumber_Index(op);
789 [ # # ]: 0 : if (lo == NULL)
790 : 0 : return (unsigned long)-1;
791 : :
792 : 0 : val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
793 : 0 : Py_DECREF(lo);
794 : 0 : return val;
795 : : }
796 : :
797 : : int
798 : 29011 : _PyLong_Sign(PyObject *vv)
799 : : {
800 : 29011 : PyLongObject *v = (PyLongObject *)vv;
801 : :
802 : : assert(v != NULL);
803 : : assert(PyLong_Check(v));
804 : :
805 [ + + + + ]: 29011 : return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
806 : : }
807 : :
808 : : static int
809 : 592664 : bit_length_digit(digit x)
810 : : {
811 : : // digit can be larger than unsigned long, but only PyLong_SHIFT bits
812 : : // of it will be ever used.
813 : : static_assert(PyLong_SHIFT <= sizeof(unsigned long) * 8,
814 : : "digit is larger than unsigned long");
815 : 592664 : return _Py_bit_length((unsigned long)x);
816 : : }
817 : :
818 : : size_t
819 : 14430 : _PyLong_NumBits(PyObject *vv)
820 : : {
821 : 14430 : PyLongObject *v = (PyLongObject *)vv;
822 : 14430 : size_t result = 0;
823 : : Py_ssize_t ndigits;
824 : : int msd_bits;
825 : :
826 : : assert(v != NULL);
827 : : assert(PyLong_Check(v));
828 [ + + ]: 14430 : ndigits = Py_ABS(Py_SIZE(v));
829 : : assert(ndigits == 0 || v->long_value.ob_digit[ndigits - 1] != 0);
830 [ + + ]: 14430 : if (ndigits > 0) {
831 : 14400 : digit msd = v->long_value.ob_digit[ndigits - 1];
832 [ - + ]: 14400 : if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
833 : 0 : goto Overflow;
834 : 14400 : result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
835 : 14400 : msd_bits = bit_length_digit(msd);
836 [ - + ]: 14400 : if (SIZE_MAX - msd_bits < result)
837 : 0 : goto Overflow;
838 : 14400 : result += msd_bits;
839 : : }
840 : 14430 : return result;
841 : :
842 : 0 : Overflow:
843 : 0 : PyErr_SetString(PyExc_OverflowError, "int has too many bits "
844 : : "to express in a platform size_t");
845 : 0 : return (size_t)-1;
846 : : }
847 : :
848 : : PyObject *
849 : 1183 : _PyLong_FromByteArray(const unsigned char* bytes, size_t n,
850 : : int little_endian, int is_signed)
851 : : {
852 : : const unsigned char* pstartbyte; /* LSB of bytes */
853 : : int incr; /* direction to move pstartbyte */
854 : : const unsigned char* pendbyte; /* MSB of bytes */
855 : : size_t numsignificantbytes; /* number of bytes that matter */
856 : : Py_ssize_t ndigits; /* number of Python int digits */
857 : : PyLongObject* v; /* result */
858 : 1183 : Py_ssize_t idigit = 0; /* next free index in v->long_value.ob_digit */
859 : :
860 [ - + ]: 1183 : if (n == 0)
861 : 0 : return PyLong_FromLong(0L);
862 : :
863 [ + - ]: 1183 : if (little_endian) {
864 : 1183 : pstartbyte = bytes;
865 : 1183 : pendbyte = bytes + n - 1;
866 : 1183 : incr = 1;
867 : : }
868 : : else {
869 : 0 : pstartbyte = bytes + n - 1;
870 : 0 : pendbyte = bytes;
871 : 0 : incr = -1;
872 : : }
873 : :
874 [ - + ]: 1183 : if (is_signed)
875 : 0 : is_signed = *pendbyte >= 0x80;
876 : :
877 : : /* Compute numsignificantbytes. This consists of finding the most
878 : : significant byte. Leading 0 bytes are insignificant if the number
879 : : is positive, and leading 0xff bytes if negative. */
880 : : {
881 : : size_t i;
882 : 1183 : const unsigned char* p = pendbyte;
883 : 1183 : const int pincr = -incr; /* search MSB to LSB */
884 [ - + ]: 1183 : const unsigned char insignificant = is_signed ? 0xff : 0x00;
885 : :
886 [ + + ]: 3491 : for (i = 0; i < n; ++i, p += pincr) {
887 [ + + ]: 3105 : if (*p != insignificant)
888 : 797 : break;
889 : : }
890 : 1183 : numsignificantbytes = n - i;
891 : : /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
892 : : actually has 2 significant bytes. OTOH, 0xff0001 ==
893 : : -0x00ffff, so we wouldn't *need* to bump it there; but we
894 : : do for 0xffff = -0x0001. To be safe without bothering to
895 : : check every case, bump it regardless. */
896 [ - + - - ]: 1183 : if (is_signed && numsignificantbytes < n)
897 : 0 : ++numsignificantbytes;
898 : : }
899 : :
900 : : /* How many Python int digits do we need? We have
901 : : 8*numsignificantbytes bits, and each Python int digit has
902 : : PyLong_SHIFT bits, so it's the ceiling of the quotient. */
903 : : /* catch overflow before it happens */
904 [ - + ]: 1183 : if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
905 : 0 : PyErr_SetString(PyExc_OverflowError,
906 : : "byte array too long to convert to int");
907 : 0 : return NULL;
908 : : }
909 : 1183 : ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
910 : 1183 : v = _PyLong_New(ndigits);
911 [ - + ]: 1183 : if (v == NULL)
912 : 0 : return NULL;
913 : :
914 : : /* Copy the bits over. The tricky parts are computing 2's-comp on
915 : : the fly for signed numbers, and dealing with the mismatch between
916 : : 8-bit bytes and (probably) 15-bit Python digits.*/
917 : : {
918 : : size_t i;
919 : 1183 : twodigits carry = 1; /* for 2's-comp calculation */
920 : 1183 : twodigits accum = 0; /* sliding register */
921 : 1183 : unsigned int accumbits = 0; /* number of bits in accum */
922 : 1183 : const unsigned char* p = pstartbyte;
923 : :
924 [ + + ]: 3607 : for (i = 0; i < numsignificantbytes; ++i, p += incr) {
925 : 2424 : twodigits thisbyte = *p;
926 : : /* Compute correction for 2's comp, if needed. */
927 [ - + ]: 2424 : if (is_signed) {
928 : 0 : thisbyte = (0xff ^ thisbyte) + carry;
929 : 0 : carry = thisbyte >> 8;
930 : 0 : thisbyte &= 0xff;
931 : : }
932 : : /* Because we're going LSB to MSB, thisbyte is
933 : : more significant than what's already in accum,
934 : : so needs to be prepended to accum. */
935 : 2424 : accum |= thisbyte << accumbits;
936 : 2424 : accumbits += 8;
937 [ + + ]: 2424 : if (accumbits >= PyLong_SHIFT) {
938 : : /* There's enough to fill a Python digit. */
939 : : assert(idigit < ndigits);
940 : 411 : v->long_value.ob_digit[idigit] = (digit)(accum & PyLong_MASK);
941 : 411 : ++idigit;
942 : 411 : accum >>= PyLong_SHIFT;
943 : 411 : accumbits -= PyLong_SHIFT;
944 : : assert(accumbits < PyLong_SHIFT);
945 : : }
946 : : }
947 : : assert(accumbits < PyLong_SHIFT);
948 [ + + ]: 1183 : if (accumbits) {
949 : : assert(idigit < ndigits);
950 : 797 : v->long_value.ob_digit[idigit] = (digit)accum;
951 : 797 : ++idigit;
952 : : }
953 : : }
954 : :
955 [ - + ]: 1183 : Py_SET_SIZE(v, is_signed ? -idigit : idigit);
956 : 1183 : return (PyObject *)maybe_small_long(long_normalize(v));
957 : : }
958 : :
959 : : int
960 : 11704 : _PyLong_AsByteArray(PyLongObject* v,
961 : : unsigned char* bytes, size_t n,
962 : : int little_endian, int is_signed)
963 : : {
964 : : Py_ssize_t i; /* index into v->long_value.ob_digit */
965 : : Py_ssize_t ndigits; /* |v->ob_size| */
966 : : twodigits accum; /* sliding register */
967 : : unsigned int accumbits; /* # bits in accum */
968 : : int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
969 : : digit carry; /* for computing 2's-comp */
970 : : size_t j; /* # bytes filled */
971 : : unsigned char* p; /* pointer to next byte in bytes */
972 : : int pincr; /* direction to move p */
973 : :
974 : : assert(v != NULL && PyLong_Check(v));
975 : :
976 [ - + ]: 11704 : if (Py_SIZE(v) < 0) {
977 : 0 : ndigits = -(Py_SIZE(v));
978 [ # # ]: 0 : if (!is_signed) {
979 : 0 : PyErr_SetString(PyExc_OverflowError,
980 : : "can't convert negative int to unsigned");
981 : 0 : return -1;
982 : : }
983 : 0 : do_twos_comp = 1;
984 : : }
985 : : else {
986 : 11704 : ndigits = Py_SIZE(v);
987 : 11704 : do_twos_comp = 0;
988 : : }
989 : :
990 [ + - ]: 11704 : if (little_endian) {
991 : 11704 : p = bytes;
992 : 11704 : pincr = 1;
993 : : }
994 : : else {
995 : 0 : p = bytes + n - 1;
996 : 0 : pincr = -1;
997 : : }
998 : :
999 : : /* Copy over all the Python digits.
1000 : : It's crucial that every Python digit except for the MSD contribute
1001 : : exactly PyLong_SHIFT bits to the total, so first assert that the int is
1002 : : normalized. */
1003 : : assert(ndigits == 0 || v->long_value.ob_digit[ndigits - 1] != 0);
1004 : 11704 : j = 0;
1005 : 11704 : accum = 0;
1006 : 11704 : accumbits = 0;
1007 : 11704 : carry = do_twos_comp ? 1 : 0;
1008 [ + + ]: 45771 : for (i = 0; i < ndigits; ++i) {
1009 : 34067 : digit thisdigit = v->long_value.ob_digit[i];
1010 [ - + ]: 34067 : if (do_twos_comp) {
1011 : 0 : thisdigit = (thisdigit ^ PyLong_MASK) + carry;
1012 : 0 : carry = thisdigit >> PyLong_SHIFT;
1013 : 0 : thisdigit &= PyLong_MASK;
1014 : : }
1015 : : /* Because we're going LSB to MSB, thisdigit is more
1016 : : significant than what's already in accum, so needs to be
1017 : : prepended to accum. */
1018 : 34067 : accum |= (twodigits)thisdigit << accumbits;
1019 : :
1020 : : /* The most-significant digit may be (probably is) at least
1021 : : partly empty. */
1022 [ + + ]: 34067 : if (i == ndigits - 1) {
1023 : : /* Count # of sign bits -- they needn't be stored,
1024 : : * although for signed conversion we need later to
1025 : : * make sure at least one sign bit gets stored. */
1026 [ - + ]: 11544 : digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
1027 [ + + ]: 54088 : while (s != 0) {
1028 : 42544 : s >>= 1;
1029 : 42544 : accumbits++;
1030 : : }
1031 : : }
1032 : : else
1033 : 22523 : accumbits += PyLong_SHIFT;
1034 : :
1035 : : /* Store as many bytes as possible. */
1036 [ + + ]: 118650 : while (accumbits >= 8) {
1037 [ - + ]: 84583 : if (j >= n)
1038 : 0 : goto Overflow;
1039 : 84583 : ++j;
1040 : 84583 : *p = (unsigned char)(accum & 0xff);
1041 : 84583 : p += pincr;
1042 : 84583 : accumbits -= 8;
1043 : 84583 : accum >>= 8;
1044 : : }
1045 : : }
1046 : :
1047 : : /* Store the straggler (if any). */
1048 : : assert(accumbits < 8);
1049 : : assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
1050 [ + + ]: 11704 : if (accumbits > 0) {
1051 [ - + ]: 6041 : if (j >= n)
1052 : 0 : goto Overflow;
1053 : 6041 : ++j;
1054 [ - + ]: 6041 : if (do_twos_comp) {
1055 : : /* Fill leading bits of the byte with sign bits
1056 : : (appropriately pretending that the int had an
1057 : : infinite supply of sign bits). */
1058 : 0 : accum |= (~(twodigits)0) << accumbits;
1059 : : }
1060 : 6041 : *p = (unsigned char)(accum & 0xff);
1061 : 6041 : p += pincr;
1062 : : }
1063 [ + + + - : 5663 : else if (j == n && n > 0 && is_signed) {
- + ]
1064 : : /* The main loop filled the byte array exactly, so the code
1065 : : just above didn't get to ensure there's a sign bit, and the
1066 : : loop below wouldn't add one either. Make sure a sign bit
1067 : : exists. */
1068 : 0 : unsigned char msb = *(p - pincr);
1069 : 0 : int sign_bit_set = msb >= 0x80;
1070 : : assert(accumbits == 0);
1071 [ # # ]: 0 : if (sign_bit_set == do_twos_comp)
1072 : 0 : return 0;
1073 : : else
1074 : 0 : goto Overflow;
1075 : : }
1076 : :
1077 : : /* Fill remaining bytes with copies of the sign bit. */
1078 : : {
1079 [ - + ]: 11704 : unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1080 [ + + ]: 12654 : for ( ; j < n; ++j, p += pincr)
1081 : 950 : *p = signbyte;
1082 : : }
1083 : :
1084 : 11704 : return 0;
1085 : :
1086 : 0 : Overflow:
1087 : 0 : PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1088 : 0 : return -1;
1089 : :
1090 : : }
1091 : :
1092 : : /* Create a new int object from a C pointer */
1093 : :
1094 : : PyObject *
1095 : 43189 : PyLong_FromVoidPtr(void *p)
1096 : : {
1097 : : #if SIZEOF_VOID_P <= SIZEOF_LONG
1098 : 43189 : return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
1099 : : #else
1100 : :
1101 : : #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
1102 : : # error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
1103 : : #endif
1104 : : return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
1105 : : #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
1106 : :
1107 : : }
1108 : :
1109 : : /* Get a C pointer from an int object. */
1110 : :
1111 : : void *
1112 : 5 : PyLong_AsVoidPtr(PyObject *vv)
1113 : : {
1114 : : #if SIZEOF_VOID_P <= SIZEOF_LONG
1115 : : long x;
1116 : :
1117 [ + - - + ]: 5 : if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1118 : 0 : x = PyLong_AsLong(vv);
1119 : : else
1120 : 5 : x = PyLong_AsUnsignedLong(vv);
1121 : : #else
1122 : :
1123 : : #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
1124 : : # error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
1125 : : #endif
1126 : : long long x;
1127 : :
1128 : : if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1129 : : x = PyLong_AsLongLong(vv);
1130 : : else
1131 : : x = PyLong_AsUnsignedLongLong(vv);
1132 : :
1133 : : #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
1134 : :
1135 [ - + - - ]: 5 : if (x == -1 && PyErr_Occurred())
1136 : 0 : return NULL;
1137 : 5 : return (void *)x;
1138 : : }
1139 : :
1140 : : /* Initial long long support by Chris Herborth (chrish@qnx.com), later
1141 : : * rewritten to use the newer PyLong_{As,From}ByteArray API.
1142 : : */
1143 : :
1144 : : #define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
1145 : :
1146 : : /* Create a new int object from a C long long int. */
1147 : :
1148 : : PyObject *
1149 : 14189 : PyLong_FromLongLong(long long ival)
1150 : : {
1151 : : PyLongObject *v;
1152 : : unsigned long long abs_ival, t;
1153 : : int ndigits;
1154 : :
1155 : : /* Handle small and medium cases. */
1156 [ + + + + ]: 14189 : if (IS_SMALL_INT(ival)) {
1157 : 101 : return get_small_int((sdigit)ival);
1158 : : }
1159 [ + + + + ]: 14088 : if (-(long long)PyLong_MASK <= ival && ival <= (long long)PyLong_MASK) {
1160 : 5534 : return _PyLong_FromMedium((sdigit)ival);
1161 : : }
1162 : :
1163 : : /* Count digits (at least two - smaller cases were handled above). */
1164 [ + + ]: 8554 : abs_ival = ival < 0 ? 0U-(unsigned long long)ival : (unsigned long long)ival;
1165 : : /* Do shift in two steps to avoid possible undefined behavior. */
1166 : 8554 : t = abs_ival >> PyLong_SHIFT >> PyLong_SHIFT;
1167 : 8554 : ndigits = 2;
1168 [ + + ]: 8748 : while (t) {
1169 : 194 : ++ndigits;
1170 : 194 : t >>= PyLong_SHIFT;
1171 : : }
1172 : :
1173 : : /* Construct output value. */
1174 : 8554 : v = _PyLong_New(ndigits);
1175 [ + - ]: 8554 : if (v != NULL) {
1176 : 8554 : digit *p = v->long_value.ob_digit;
1177 [ + + ]: 8554 : Py_SET_SIZE(v, ival < 0 ? -ndigits : ndigits);
1178 : 8554 : t = abs_ival;
1179 [ + + ]: 25856 : while (t) {
1180 : 17302 : *p++ = (digit)(t & PyLong_MASK);
1181 : 17302 : t >>= PyLong_SHIFT;
1182 : : }
1183 : : }
1184 : 8554 : return (PyObject *)v;
1185 : : }
1186 : :
1187 : : /* Create a new int object from a C Py_ssize_t. */
1188 : :
1189 : : PyObject *
1190 : 1673998 : PyLong_FromSsize_t(Py_ssize_t ival)
1191 : : {
1192 : : PyLongObject *v;
1193 : : size_t abs_ival;
1194 : : size_t t; /* unsigned so >> doesn't propagate sign bit */
1195 : 1673998 : int ndigits = 0;
1196 : 1673998 : int negative = 0;
1197 : :
1198 [ + + + + ]: 1673998 : if (IS_SMALL_INT(ival)) {
1199 : 1056644 : return get_small_int((sdigit)ival);
1200 : : }
1201 : :
1202 [ + + ]: 617354 : if (ival < 0) {
1203 : : /* avoid signed overflow when ival = SIZE_T_MIN */
1204 : 36 : abs_ival = (size_t)(-1-ival)+1;
1205 : 36 : negative = 1;
1206 : : }
1207 : : else {
1208 : 617318 : abs_ival = (size_t)ival;
1209 : : }
1210 : :
1211 : : /* Count the number of Python digits. */
1212 : 617354 : t = abs_ival;
1213 [ + + ]: 1235475 : while (t) {
1214 : 618121 : ++ndigits;
1215 : 618121 : t >>= PyLong_SHIFT;
1216 : : }
1217 : 617354 : v = _PyLong_New(ndigits);
1218 [ + - ]: 617354 : if (v != NULL) {
1219 : 617354 : digit *p = v->long_value.ob_digit;
1220 [ + + ]: 617354 : Py_SET_SIZE(v, negative ? -ndigits : ndigits);
1221 : 617354 : t = abs_ival;
1222 [ + + ]: 1235475 : while (t) {
1223 : 618121 : *p++ = (digit)(t & PyLong_MASK);
1224 : 618121 : t >>= PyLong_SHIFT;
1225 : : }
1226 : : }
1227 : 617354 : return (PyObject *)v;
1228 : : }
1229 : :
1230 : : /* Get a C long long int from an int object or any object that has an
1231 : : __index__ method. Return -1 and set an error if overflow occurs. */
1232 : :
1233 : : long long
1234 : 0 : PyLong_AsLongLong(PyObject *vv)
1235 : : {
1236 : : PyLongObject *v;
1237 : : long long bytes;
1238 : : int res;
1239 : 0 : int do_decref = 0; /* if PyNumber_Index was called */
1240 : :
1241 [ # # ]: 0 : if (vv == NULL) {
1242 : 0 : PyErr_BadInternalCall();
1243 : 0 : return -1;
1244 : : }
1245 : :
1246 [ # # ]: 0 : if (PyLong_Check(vv)) {
1247 : 0 : v = (PyLongObject *)vv;
1248 : : }
1249 : : else {
1250 : 0 : v = (PyLongObject *)_PyNumber_Index(vv);
1251 [ # # ]: 0 : if (v == NULL)
1252 : 0 : return -1;
1253 : 0 : do_decref = 1;
1254 : : }
1255 : :
1256 : 0 : res = 0;
1257 [ # # # # ]: 0 : switch(Py_SIZE(v)) {
1258 : 0 : case -1:
1259 : 0 : bytes = -(sdigit)v->long_value.ob_digit[0];
1260 : 0 : break;
1261 : 0 : case 0:
1262 : 0 : bytes = 0;
1263 : 0 : break;
1264 : 0 : case 1:
1265 : 0 : bytes = v->long_value.ob_digit[0];
1266 : 0 : break;
1267 : 0 : default:
1268 : 0 : res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
1269 : : SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
1270 : : }
1271 [ # # ]: 0 : if (do_decref) {
1272 : 0 : Py_DECREF(v);
1273 : : }
1274 : :
1275 : : /* Plan 9 can't handle long long in ? : expressions */
1276 [ # # ]: 0 : if (res < 0)
1277 : 0 : return (long long)-1;
1278 : : else
1279 : 0 : return bytes;
1280 : : }
1281 : :
1282 : : /* Get a C unsigned long long int from an int object.
1283 : : Return -1 and set an error if overflow occurs. */
1284 : :
1285 : : unsigned long long
1286 : 14203 : PyLong_AsUnsignedLongLong(PyObject *vv)
1287 : : {
1288 : : PyLongObject *v;
1289 : : unsigned long long bytes;
1290 : : int res;
1291 : :
1292 [ - + ]: 14203 : if (vv == NULL) {
1293 : 0 : PyErr_BadInternalCall();
1294 : 0 : return (unsigned long long)-1;
1295 : : }
1296 [ - + ]: 14203 : if (!PyLong_Check(vv)) {
1297 : 0 : PyErr_SetString(PyExc_TypeError, "an integer is required");
1298 : 0 : return (unsigned long long)-1;
1299 : : }
1300 : :
1301 : 14203 : v = (PyLongObject*)vv;
1302 [ - + + ]: 14203 : switch(Py_SIZE(v)) {
1303 : 0 : case 0: return 0;
1304 : 3001 : case 1: return v->long_value.ob_digit[0];
1305 : : }
1306 : :
1307 : 11202 : res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1308 : : SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
1309 : :
1310 : : /* Plan 9 can't handle long long in ? : expressions */
1311 [ - + ]: 11202 : if (res < 0)
1312 : 0 : return (unsigned long long)res;
1313 : : else
1314 : 11202 : return bytes;
1315 : : }
1316 : :
1317 : : /* Get a C unsigned long int from an int object, ignoring the high bits.
1318 : : Returns -1 and sets an error condition if an error occurs. */
1319 : :
1320 : : static unsigned long long
1321 : 8 : _PyLong_AsUnsignedLongLongMask(PyObject *vv)
1322 : : {
1323 : : PyLongObject *v;
1324 : : unsigned long long x;
1325 : : Py_ssize_t i;
1326 : : int sign;
1327 : :
1328 [ + - - + ]: 8 : if (vv == NULL || !PyLong_Check(vv)) {
1329 : 0 : PyErr_BadInternalCall();
1330 : 0 : return (unsigned long long) -1;
1331 : : }
1332 : 8 : v = (PyLongObject *)vv;
1333 [ + - - ]: 8 : switch(Py_SIZE(v)) {
1334 : 8 : case 0: return 0;
1335 : 0 : case 1: return v->long_value.ob_digit[0];
1336 : : }
1337 : 0 : i = Py_SIZE(v);
1338 : 0 : sign = 1;
1339 : 0 : x = 0;
1340 [ # # ]: 0 : if (i < 0) {
1341 : 0 : sign = -1;
1342 : 0 : i = -i;
1343 : : }
1344 [ # # ]: 0 : while (--i >= 0) {
1345 : 0 : x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
1346 : : }
1347 : 0 : return x * sign;
1348 : : }
1349 : :
1350 : : unsigned long long
1351 : 8 : PyLong_AsUnsignedLongLongMask(PyObject *op)
1352 : : {
1353 : : PyLongObject *lo;
1354 : : unsigned long long val;
1355 : :
1356 [ - + ]: 8 : if (op == NULL) {
1357 : 0 : PyErr_BadInternalCall();
1358 : 0 : return (unsigned long long)-1;
1359 : : }
1360 : :
1361 [ + - ]: 8 : if (PyLong_Check(op)) {
1362 : 8 : return _PyLong_AsUnsignedLongLongMask(op);
1363 : : }
1364 : :
1365 : 0 : lo = (PyLongObject *)_PyNumber_Index(op);
1366 [ # # ]: 0 : if (lo == NULL)
1367 : 0 : return (unsigned long long)-1;
1368 : :
1369 : 0 : val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1370 : 0 : Py_DECREF(lo);
1371 : 0 : return val;
1372 : : }
1373 : :
1374 : : /* Get a C long long int from an int object or any object that has an
1375 : : __index__ method.
1376 : :
1377 : : On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1378 : : the result. Otherwise *overflow is 0.
1379 : :
1380 : : For other errors (e.g., TypeError), return -1 and set an error condition.
1381 : : In this case *overflow will be 0.
1382 : : */
1383 : :
1384 : : long long
1385 : 113683 : PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1386 : : {
1387 : : /* This version by Tim Peters */
1388 : : PyLongObject *v;
1389 : : unsigned long long x, prev;
1390 : : long long res;
1391 : : Py_ssize_t i;
1392 : : int sign;
1393 : 113683 : int do_decref = 0; /* if PyNumber_Index was called */
1394 : :
1395 : 113683 : *overflow = 0;
1396 [ - + ]: 113683 : if (vv == NULL) {
1397 : 0 : PyErr_BadInternalCall();
1398 : 0 : return -1;
1399 : : }
1400 : :
1401 [ + - ]: 113683 : if (PyLong_Check(vv)) {
1402 : 113683 : v = (PyLongObject *)vv;
1403 : : }
1404 : : else {
1405 : 0 : v = (PyLongObject *)_PyNumber_Index(vv);
1406 [ # # ]: 0 : if (v == NULL)
1407 : 0 : return -1;
1408 : 0 : do_decref = 1;
1409 : : }
1410 : :
1411 : 113683 : res = -1;
1412 : 113683 : i = Py_SIZE(v);
1413 : :
1414 [ - + + + ]: 113683 : switch (i) {
1415 : 0 : case -1:
1416 : 0 : res = -(sdigit)v->long_value.ob_digit[0];
1417 : 0 : break;
1418 : 1518 : case 0:
1419 : 1518 : res = 0;
1420 : 1518 : break;
1421 : 112152 : case 1:
1422 : 112152 : res = v->long_value.ob_digit[0];
1423 : 112152 : break;
1424 : 13 : default:
1425 : 13 : sign = 1;
1426 : 13 : x = 0;
1427 [ - + ]: 13 : if (i < 0) {
1428 : 0 : sign = -1;
1429 : 0 : i = -(i);
1430 : : }
1431 [ + - ]: 39 : while (--i >= 0) {
1432 : 39 : prev = x;
1433 : 39 : x = (x << PyLong_SHIFT) + v->long_value.ob_digit[i];
1434 [ + + ]: 39 : if ((x >> PyLong_SHIFT) != prev) {
1435 : 13 : *overflow = sign;
1436 : 13 : goto exit;
1437 : : }
1438 : : }
1439 : : /* Haven't lost any bits, but casting to long requires extra
1440 : : * care (see comment above).
1441 : : */
1442 [ # # ]: 0 : if (x <= (unsigned long long)LLONG_MAX) {
1443 : 0 : res = (long long)x * sign;
1444 : : }
1445 [ # # # # ]: 0 : else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1446 : 0 : res = LLONG_MIN;
1447 : : }
1448 : : else {
1449 : 0 : *overflow = sign;
1450 : : /* res is already set to -1 */
1451 : : }
1452 : : }
1453 : 113683 : exit:
1454 [ - + ]: 113683 : if (do_decref) {
1455 : 0 : Py_DECREF(v);
1456 : : }
1457 : 113683 : return res;
1458 : : }
1459 : :
1460 : : int
1461 : 0 : _PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1462 : : {
1463 : : unsigned long uval;
1464 : :
1465 [ # # # # ]: 0 : if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1466 : 0 : PyErr_SetString(PyExc_ValueError, "value must be positive");
1467 : 0 : return 0;
1468 : : }
1469 : 0 : uval = PyLong_AsUnsignedLong(obj);
1470 [ # # # # ]: 0 : if (uval == (unsigned long)-1 && PyErr_Occurred())
1471 : 0 : return 0;
1472 [ # # ]: 0 : if (uval > USHRT_MAX) {
1473 : 0 : PyErr_SetString(PyExc_OverflowError,
1474 : : "Python int too large for C unsigned short");
1475 : 0 : return 0;
1476 : : }
1477 : :
1478 : 0 : *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1479 : 0 : return 1;
1480 : : }
1481 : :
1482 : : int
1483 : 0 : _PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1484 : : {
1485 : : unsigned long uval;
1486 : :
1487 [ # # # # ]: 0 : if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1488 : 0 : PyErr_SetString(PyExc_ValueError, "value must be positive");
1489 : 0 : return 0;
1490 : : }
1491 : 0 : uval = PyLong_AsUnsignedLong(obj);
1492 [ # # # # ]: 0 : if (uval == (unsigned long)-1 && PyErr_Occurred())
1493 : 0 : return 0;
1494 [ # # ]: 0 : if (uval > UINT_MAX) {
1495 : 0 : PyErr_SetString(PyExc_OverflowError,
1496 : : "Python int too large for C unsigned int");
1497 : 0 : return 0;
1498 : : }
1499 : :
1500 : 0 : *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1501 : 0 : return 1;
1502 : : }
1503 : :
1504 : : int
1505 : 0 : _PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1506 : : {
1507 : : unsigned long uval;
1508 : :
1509 [ # # # # ]: 0 : if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1510 : 0 : PyErr_SetString(PyExc_ValueError, "value must be positive");
1511 : 0 : return 0;
1512 : : }
1513 : 0 : uval = PyLong_AsUnsignedLong(obj);
1514 [ # # # # ]: 0 : if (uval == (unsigned long)-1 && PyErr_Occurred())
1515 : 0 : return 0;
1516 : :
1517 : 0 : *(unsigned long *)ptr = uval;
1518 : 0 : return 1;
1519 : : }
1520 : :
1521 : : int
1522 : 0 : _PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1523 : : {
1524 : : unsigned long long uval;
1525 : :
1526 [ # # # # ]: 0 : if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1527 : 0 : PyErr_SetString(PyExc_ValueError, "value must be positive");
1528 : 0 : return 0;
1529 : : }
1530 : 0 : uval = PyLong_AsUnsignedLongLong(obj);
1531 [ # # # # ]: 0 : if (uval == (unsigned long long)-1 && PyErr_Occurred())
1532 : 0 : return 0;
1533 : :
1534 : 0 : *(unsigned long long *)ptr = uval;
1535 : 0 : return 1;
1536 : : }
1537 : :
1538 : : int
1539 : 0 : _PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1540 : : {
1541 : : size_t uval;
1542 : :
1543 [ # # # # ]: 0 : if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
1544 : 0 : PyErr_SetString(PyExc_ValueError, "value must be positive");
1545 : 0 : return 0;
1546 : : }
1547 : 0 : uval = PyLong_AsSize_t(obj);
1548 [ # # # # ]: 0 : if (uval == (size_t)-1 && PyErr_Occurred())
1549 : 0 : return 0;
1550 : :
1551 : 0 : *(size_t *)ptr = uval;
1552 : 0 : return 1;
1553 : : }
1554 : :
1555 : :
1556 : : #define CHECK_BINOP(v,w) \
1557 : : do { \
1558 : : if (!PyLong_Check(v) || !PyLong_Check(w)) \
1559 : : Py_RETURN_NOTIMPLEMENTED; \
1560 : : } while(0)
1561 : :
1562 : : /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1563 : : * is modified in place, by adding y to it. Carries are propagated as far as
1564 : : * x[m-1], and the remaining carry (0 or 1) is returned.
1565 : : */
1566 : : static digit
1567 : 962 : v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
1568 : : {
1569 : : Py_ssize_t i;
1570 : 962 : digit carry = 0;
1571 : :
1572 : : assert(m >= n);
1573 [ + + ]: 113775 : for (i = 0; i < n; ++i) {
1574 : 112813 : carry += x[i] + y[i];
1575 : 112813 : x[i] = carry & PyLong_MASK;
1576 : 112813 : carry >>= PyLong_SHIFT;
1577 : : assert((carry & 1) == carry);
1578 : : }
1579 [ + + + - ]: 1115 : for (; carry && i < m; ++i) {
1580 : 153 : carry += x[i];
1581 : 153 : x[i] = carry & PyLong_MASK;
1582 : 153 : carry >>= PyLong_SHIFT;
1583 : : assert((carry & 1) == carry);
1584 : : }
1585 : 962 : return carry;
1586 : : }
1587 : :
1588 : : /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1589 : : * is modified in place, by subtracting y from it. Borrows are propagated as
1590 : : * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1591 : : */
1592 : : static digit
1593 : 1924 : v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
1594 : : {
1595 : : Py_ssize_t i;
1596 : 1924 : digit borrow = 0;
1597 : :
1598 : : assert(m >= n);
1599 [ + + ]: 201550 : for (i = 0; i < n; ++i) {
1600 : 199626 : borrow = x[i] - y[i] - borrow;
1601 : 199626 : x[i] = borrow & PyLong_MASK;
1602 : 199626 : borrow >>= PyLong_SHIFT;
1603 : 199626 : borrow &= 1; /* keep only 1 sign bit */
1604 : : }
1605 [ + + + - ]: 2245 : for (; borrow && i < m; ++i) {
1606 : 321 : borrow = x[i] - borrow;
1607 : 321 : x[i] = borrow & PyLong_MASK;
1608 : 321 : borrow >>= PyLong_SHIFT;
1609 : 321 : borrow &= 1;
1610 : : }
1611 : 1924 : return borrow;
1612 : : }
1613 : :
1614 : : /* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1615 : : * result in z[0:m], and return the d bits shifted out of the top.
1616 : : */
1617 : : static digit
1618 : 171063 : v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
1619 : : {
1620 : : Py_ssize_t i;
1621 : 171063 : digit carry = 0;
1622 : :
1623 : : assert(0 <= d && d < PyLong_SHIFT);
1624 [ + + ]: 5537561 : for (i=0; i < m; i++) {
1625 : 5366498 : twodigits acc = (twodigits)a[i] << d | carry;
1626 : 5366498 : z[i] = (digit)acc & PyLong_MASK;
1627 : 5366498 : carry = (digit)(acc >> PyLong_SHIFT);
1628 : : }
1629 : 171063 : return carry;
1630 : : }
1631 : :
1632 : : /* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1633 : : * result in z[0:m], and return the d bits shifted out of the bottom.
1634 : : */
1635 : : static digit
1636 : 84551 : v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1637 : : {
1638 : : Py_ssize_t i;
1639 : 84551 : digit carry = 0;
1640 : 84551 : digit mask = ((digit)1 << d) - 1U;
1641 : :
1642 : : assert(0 <= d && d < PyLong_SHIFT);
1643 [ + + ]: 2726762 : for (i=m; i-- > 0;) {
1644 : 2642211 : twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1645 : 2642211 : carry = (digit)acc & mask;
1646 : 2642211 : z[i] = (digit)(acc >> d);
1647 : : }
1648 : 84551 : return carry;
1649 : : }
1650 : :
1651 : : /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1652 : : in pout, and returning the remainder. pin and pout point at the LSD.
1653 : : It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1654 : : _PyLong_Format, but that should be done with great care since ints are
1655 : : immutable.
1656 : :
1657 : : This version of the code can be 20% faster than the pre-2022 version
1658 : : on todays compilers on architectures like amd64. It evolved from Mark
1659 : : Dickinson observing that a 128:64 divide instruction was always being
1660 : : generated by the compiler despite us working with 30-bit digit values.
1661 : : See the thread for full context:
1662 : :
1663 : : https://mail.python.org/archives/list/python-dev@python.org/thread/ZICIMX5VFCX4IOFH5NUPVHCUJCQ4Q7QM/#NEUNFZU3TQU4CPTYZNF3WCN7DOJBBTK5
1664 : :
1665 : : If you ever want to change this code, pay attention to performance using
1666 : : different compilers, optimization levels, and cpu architectures. Beware of
1667 : : PGO/FDO builds doing value specialization such as a fast path for //10. :)
1668 : :
1669 : : Verify that 17 isn't specialized and this works as a quick test:
1670 : : python -m timeit -s 'x = 10**1000; r=x//10; assert r == 10**999, r' 'x//17'
1671 : : */
1672 : : static digit
1673 : 22906 : inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
1674 : : {
1675 : 22906 : digit remainder = 0;
1676 : :
1677 : : assert(n > 0 && n <= PyLong_MASK);
1678 [ + + ]: 248723 : while (--size >= 0) {
1679 : : twodigits dividend;
1680 : 225817 : dividend = ((twodigits)remainder << PyLong_SHIFT) | pin[size];
1681 : : digit quotient;
1682 : 225817 : quotient = (digit)(dividend / n);
1683 : 225817 : remainder = dividend % n;
1684 : 225817 : pout[size] = quotient;
1685 : : }
1686 : 22906 : return remainder;
1687 : : }
1688 : :
1689 : :
1690 : : /* Divide an integer by a digit, returning both the quotient
1691 : : (as function result) and the remainder (through *prem).
1692 : : The sign of a is ignored; n should not be zero. */
1693 : :
1694 : : static PyLongObject *
1695 : 22906 : divrem1(PyLongObject *a, digit n, digit *prem)
1696 : : {
1697 [ + + ]: 22906 : const Py_ssize_t size = Py_ABS(Py_SIZE(a));
1698 : : PyLongObject *z;
1699 : :
1700 : : assert(n > 0 && n <= PyLong_MASK);
1701 : 22906 : z = _PyLong_New(size);
1702 [ - + ]: 22906 : if (z == NULL)
1703 : 0 : return NULL;
1704 : 22906 : *prem = inplace_divrem1(z->long_value.ob_digit, a->long_value.ob_digit, size, n);
1705 : 22906 : return long_normalize(z);
1706 : : }
1707 : :
1708 : : /* Remainder of long pin, w/ size digits, by non-zero digit n,
1709 : : returning the remainder. pin points at the LSD. */
1710 : :
1711 : : static digit
1712 : 9807 : inplace_rem1(digit *pin, Py_ssize_t size, digit n)
1713 : : {
1714 : 9807 : twodigits rem = 0;
1715 : :
1716 : : assert(n > 0 && n <= PyLong_MASK);
1717 [ + + ]: 362821 : while (--size >= 0)
1718 : 353014 : rem = ((rem << PyLong_SHIFT) | pin[size]) % n;
1719 : 9807 : return (digit)rem;
1720 : : }
1721 : :
1722 : : /* Get the remainder of an integer divided by a digit, returning
1723 : : the remainder as the result of the function. The sign of a is
1724 : : ignored; n should not be zero. */
1725 : :
1726 : : static PyLongObject *
1727 : 9807 : rem1(PyLongObject *a, digit n)
1728 : : {
1729 [ - + ]: 9807 : const Py_ssize_t size = Py_ABS(Py_SIZE(a));
1730 : :
1731 : : assert(n > 0 && n <= PyLong_MASK);
1732 : 9807 : return (PyLongObject *)PyLong_FromLong(
1733 : 9807 : (long)inplace_rem1(a->long_value.ob_digit, size, n)
1734 : : );
1735 : : }
1736 : :
1737 : : #ifdef WITH_PYLONG_MODULE
1738 : : /* asymptotically faster long_to_decimal_string, using _pylong.py */
1739 : : static int
1740 : 0 : pylong_int_to_decimal_string(PyObject *aa,
1741 : : PyObject **p_output,
1742 : : _PyUnicodeWriter *writer,
1743 : : _PyBytesWriter *bytes_writer,
1744 : : char **bytes_str)
1745 : : {
1746 : 0 : PyObject *s = NULL;
1747 : 0 : PyObject *mod = PyImport_ImportModule("_pylong");
1748 [ # # ]: 0 : if (mod == NULL) {
1749 : 0 : return -1;
1750 : : }
1751 : 0 : s = PyObject_CallMethod(mod, "int_to_decimal_string", "O", aa);
1752 [ # # ]: 0 : if (s == NULL) {
1753 : 0 : goto error;
1754 : : }
1755 [ # # ]: 0 : if (!PyUnicode_Check(s)) {
1756 : 0 : PyErr_SetString(PyExc_TypeError,
1757 : : "_pylong.int_to_decimal_string did not return a str");
1758 : 0 : goto error;
1759 : : }
1760 [ # # ]: 0 : if (writer) {
1761 : 0 : Py_ssize_t size = PyUnicode_GET_LENGTH(s);
1762 [ # # # # : 0 : if (_PyUnicodeWriter_Prepare(writer, size, '9') == -1) {
# # # # ]
1763 : 0 : goto error;
1764 : : }
1765 [ # # ]: 0 : if (_PyUnicodeWriter_WriteStr(writer, s) < 0) {
1766 : 0 : goto error;
1767 : : }
1768 : 0 : goto success;
1769 : : }
1770 [ # # ]: 0 : else if (bytes_writer) {
1771 : 0 : Py_ssize_t size = PyUnicode_GET_LENGTH(s);
1772 : 0 : const void *data = PyUnicode_DATA(s);
1773 : 0 : int kind = PyUnicode_KIND(s);
1774 : 0 : *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, size);
1775 [ # # ]: 0 : if (*bytes_str == NULL) {
1776 : 0 : goto error;
1777 : : }
1778 : 0 : char *p = *bytes_str;
1779 [ # # ]: 0 : for (Py_ssize_t i=0; i < size; i++) {
1780 : 0 : Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1781 : 0 : *p++ = (char) ch;
1782 : : }
1783 : 0 : (*bytes_str) = p;
1784 : 0 : goto success;
1785 : : }
1786 : : else {
1787 : 0 : *p_output = Py_NewRef(s);
1788 : 0 : goto success;
1789 : : }
1790 : :
1791 : 0 : error:
1792 : 0 : Py_DECREF(mod);
1793 : 0 : Py_XDECREF(s);
1794 : 0 : return -1;
1795 : :
1796 : 0 : success:
1797 : 0 : Py_DECREF(mod);
1798 : 0 : Py_DECREF(s);
1799 : 0 : return 0;
1800 : : }
1801 : : #endif /* WITH_PYLONG_MODULE */
1802 : :
1803 : : /* Convert an integer to a base 10 string. Returns a new non-shared
1804 : : string. (Return value is non-shared so that callers can modify the
1805 : : returned value if necessary.) */
1806 : :
1807 : : static int
1808 : 317650 : long_to_decimal_string_internal(PyObject *aa,
1809 : : PyObject **p_output,
1810 : : _PyUnicodeWriter *writer,
1811 : : _PyBytesWriter *bytes_writer,
1812 : : char **bytes_str)
1813 : : {
1814 : : PyLongObject *scratch, *a;
1815 : 317650 : PyObject *str = NULL;
1816 : : Py_ssize_t size, strlen, size_a, i, j;
1817 : : digit *pout, *pin, rem, tenpow;
1818 : : int negative;
1819 : : int d;
1820 : : int kind;
1821 : :
1822 : 317650 : a = (PyLongObject *)aa;
1823 [ + - - + ]: 317650 : if (a == NULL || !PyLong_Check(a)) {
1824 : 0 : PyErr_BadInternalCall();
1825 : 0 : return -1;
1826 : : }
1827 [ + + ]: 317650 : size_a = Py_ABS(Py_SIZE(a));
1828 : 317650 : negative = Py_SIZE(a) < 0;
1829 : :
1830 : : /* quick and dirty pre-check for overflowing the decimal digit limit,
1831 : : based on the inequality 10/3 >= log2(10)
1832 : :
1833 : : explanation in https://github.com/python/cpython/pull/96537
1834 : : */
1835 [ - + ]: 317650 : if (size_a >= 10 * _PY_LONG_MAX_STR_DIGITS_THRESHOLD
1836 : : / (3 * PyLong_SHIFT) + 2) {
1837 : 0 : PyInterpreterState *interp = _PyInterpreterState_GET();
1838 : 0 : int max_str_digits = interp->long_state.max_str_digits;
1839 [ # # ]: 0 : if ((max_str_digits > 0) &&
1840 [ # # ]: 0 : (max_str_digits / (3 * PyLong_SHIFT) <= (size_a - 11) / 10)) {
1841 : 0 : PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_STR,
1842 : : max_str_digits);
1843 : 0 : return -1;
1844 : : }
1845 : : }
1846 : :
1847 : : #if WITH_PYLONG_MODULE
1848 [ - + ]: 317650 : if (size_a > 1000) {
1849 : : /* Switch to _pylong.int_to_decimal_string(). */
1850 : 0 : return pylong_int_to_decimal_string(aa,
1851 : : p_output,
1852 : : writer,
1853 : : bytes_writer,
1854 : : bytes_str);
1855 : : }
1856 : : #endif
1857 : :
1858 : : /* quick and dirty upper bound for the number of digits
1859 : : required to express a in base _PyLong_DECIMAL_BASE:
1860 : :
1861 : : #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1862 : :
1863 : : But log2(a) < size_a * PyLong_SHIFT, and
1864 : : log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1865 : : > 3.3 * _PyLong_DECIMAL_SHIFT
1866 : :
1867 : : size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1868 : : size_a + size_a / d < size_a + size_a / floor(d),
1869 : : where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1870 : : (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
1871 : : */
1872 : 317650 : d = (33 * _PyLong_DECIMAL_SHIFT) /
1873 : : (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1874 : : assert(size_a < PY_SSIZE_T_MAX/2);
1875 : 317650 : size = 1 + size_a + size_a / d;
1876 : 317650 : scratch = _PyLong_New(size);
1877 [ - + ]: 317650 : if (scratch == NULL)
1878 : 0 : return -1;
1879 : :
1880 : : /* convert array of base _PyLong_BASE digits in pin to an array of
1881 : : base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1882 : : Volume 2 (3rd edn), section 4.4, Method 1b). */
1883 : 317650 : pin = a->long_value.ob_digit;
1884 : 317650 : pout = scratch->long_value.ob_digit;
1885 : 317650 : size = 0;
1886 [ + + ]: 540888 : for (i = size_a; --i >= 0; ) {
1887 : 223238 : digit hi = pin[i];
1888 [ + + ]: 223442 : for (j = 0; j < size; j++) {
1889 : 204 : twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1890 : 204 : hi = (digit)(z / _PyLong_DECIMAL_BASE);
1891 : 204 : pout[j] = (digit)(z - (twodigits)hi *
1892 : : _PyLong_DECIMAL_BASE);
1893 : : }
1894 [ + + ]: 446477 : while (hi) {
1895 : 223239 : pout[size++] = hi % _PyLong_DECIMAL_BASE;
1896 : 223239 : hi /= _PyLong_DECIMAL_BASE;
1897 : : }
1898 : : /* check for keyboard interrupt */
1899 [ - + ]: 223238 : SIGCHECK({
1900 : : Py_DECREF(scratch);
1901 : : return -1;
1902 : : });
1903 : : }
1904 : : /* pout should have at least one digit, so that the case when a = 0
1905 : : works correctly */
1906 [ + + ]: 317650 : if (size == 0)
1907 : 94608 : pout[size++] = 0;
1908 : :
1909 : : /* calculate exact length of output string, and allocate */
1910 : 317650 : strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1911 : 317650 : tenpow = 10;
1912 : 317650 : rem = pout[size-1];
1913 [ + + ]: 594943 : while (rem >= tenpow) {
1914 : 277293 : tenpow *= 10;
1915 : 277293 : strlen++;
1916 : : }
1917 [ - + ]: 317650 : if (strlen > _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
1918 : 0 : PyInterpreterState *interp = _PyInterpreterState_GET();
1919 : 0 : int max_str_digits = interp->long_state.max_str_digits;
1920 : 0 : Py_ssize_t strlen_nosign = strlen - negative;
1921 [ # # # # ]: 0 : if ((max_str_digits > 0) && (strlen_nosign > max_str_digits)) {
1922 : 0 : Py_DECREF(scratch);
1923 : 0 : PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_STR,
1924 : : max_str_digits);
1925 : 0 : return -1;
1926 : : }
1927 : : }
1928 [ + + ]: 317650 : if (writer) {
1929 [ + + - + : 134 : if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
+ - - + ]
1930 : 0 : Py_DECREF(scratch);
1931 : 0 : return -1;
1932 : : }
1933 : 134 : kind = writer->kind;
1934 : : }
1935 [ - + ]: 317516 : else if (bytes_writer) {
1936 : 0 : *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1937 [ # # ]: 0 : if (*bytes_str == NULL) {
1938 : 0 : Py_DECREF(scratch);
1939 : 0 : return -1;
1940 : : }
1941 : : }
1942 : : else {
1943 : 317516 : str = PyUnicode_New(strlen, '9');
1944 [ - + ]: 317516 : if (str == NULL) {
1945 : 0 : Py_DECREF(scratch);
1946 : 0 : return -1;
1947 : : }
1948 : 317516 : kind = PyUnicode_KIND(str);
1949 : : }
1950 : :
1951 : : #define WRITE_DIGITS(p) \
1952 : : do { \
1953 : : /* pout[0] through pout[size-2] contribute exactly \
1954 : : _PyLong_DECIMAL_SHIFT digits each */ \
1955 : : for (i=0; i < size - 1; i++) { \
1956 : : rem = pout[i]; \
1957 : : for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1958 : : *--p = '0' + rem % 10; \
1959 : : rem /= 10; \
1960 : : } \
1961 : : } \
1962 : : /* pout[size-1]: always produce at least one decimal digit */ \
1963 : : rem = pout[i]; \
1964 : : do { \
1965 : : *--p = '0' + rem % 10; \
1966 : : rem /= 10; \
1967 : : } while (rem != 0); \
1968 : : \
1969 : : /* and sign */ \
1970 : : if (negative) \
1971 : : *--p = '-'; \
1972 : : } while (0)
1973 : :
1974 : : #define WRITE_UNICODE_DIGITS(TYPE) \
1975 : : do { \
1976 : : if (writer) \
1977 : : p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1978 : : else \
1979 : : p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1980 : : \
1981 : : WRITE_DIGITS(p); \
1982 : : \
1983 : : /* check we've counted correctly */ \
1984 : : if (writer) \
1985 : : assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1986 : : else \
1987 : : assert(p == (TYPE*)PyUnicode_DATA(str)); \
1988 : : } while (0)
1989 : :
1990 : : /* fill the string right-to-left */
1991 [ - + ]: 317650 : if (bytes_writer) {
1992 : 0 : char *p = *bytes_str + strlen;
1993 [ # # # # : 0 : WRITE_DIGITS(p);
# # # # ]
1994 : : assert(p == *bytes_str);
1995 : : }
1996 [ + - ]: 317650 : else if (kind == PyUnicode_1BYTE_KIND) {
1997 : : Py_UCS1 *p;
1998 [ + + + + : 596913 : WRITE_UNICODE_DIGITS(Py_UCS1);
+ + + + +
+ ]
1999 : : }
2000 [ # # ]: 0 : else if (kind == PyUnicode_2BYTE_KIND) {
2001 : : Py_UCS2 *p;
2002 [ # # # # : 0 : WRITE_UNICODE_DIGITS(Py_UCS2);
# # # # #
# ]
2003 : : }
2004 : : else {
2005 : : Py_UCS4 *p;
2006 : : assert (kind == PyUnicode_4BYTE_KIND);
2007 [ # # # # : 0 : WRITE_UNICODE_DIGITS(Py_UCS4);
# # # # #
# ]
2008 : : }
2009 : : #undef WRITE_DIGITS
2010 : : #undef WRITE_UNICODE_DIGITS
2011 : :
2012 : 317650 : _Py_DECREF_INT(scratch);
2013 [ + + ]: 317650 : if (writer) {
2014 : 134 : writer->pos += strlen;
2015 : : }
2016 [ - + ]: 317516 : else if (bytes_writer) {
2017 : 0 : (*bytes_str) += strlen;
2018 : : }
2019 : : else {
2020 : : assert(_PyUnicode_CheckConsistency(str, 1));
2021 : 317516 : *p_output = (PyObject *)str;
2022 : : }
2023 : 317650 : return 0;
2024 : : }
2025 : :
2026 : : static PyObject *
2027 : 317511 : long_to_decimal_string(PyObject *aa)
2028 : : {
2029 : : PyObject *v;
2030 [ - + ]: 317511 : if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
2031 : 0 : return NULL;
2032 : 317511 : return v;
2033 : : }
2034 : :
2035 : : /* Convert an int object to a string, using a given conversion base,
2036 : : which should be one of 2, 8 or 16. Return a string object.
2037 : : If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
2038 : : if alternate is nonzero. */
2039 : :
2040 : : static int
2041 : 270270 : long_format_binary(PyObject *aa, int base, int alternate,
2042 : : PyObject **p_output, _PyUnicodeWriter *writer,
2043 : : _PyBytesWriter *bytes_writer, char **bytes_str)
2044 : : {
2045 : 270270 : PyLongObject *a = (PyLongObject *)aa;
2046 : 270270 : PyObject *v = NULL;
2047 : : Py_ssize_t sz;
2048 : : Py_ssize_t size_a;
2049 : : int kind;
2050 : : int negative;
2051 : : int bits;
2052 : :
2053 : : assert(base == 2 || base == 8 || base == 16);
2054 [ + - - + ]: 270270 : if (a == NULL || !PyLong_Check(a)) {
2055 : 0 : PyErr_BadInternalCall();
2056 : 0 : return -1;
2057 : : }
2058 [ - + ]: 270270 : size_a = Py_ABS(Py_SIZE(a));
2059 : 270270 : negative = Py_SIZE(a) < 0;
2060 : :
2061 : : /* Compute a rough upper bound for the length of the string */
2062 [ + - + - ]: 270270 : switch (base) {
2063 : 268270 : case 16:
2064 : 268270 : bits = 4;
2065 : 268270 : break;
2066 : 0 : case 8:
2067 : 0 : bits = 3;
2068 : 0 : break;
2069 : 2000 : case 2:
2070 : 2000 : bits = 1;
2071 : 2000 : break;
2072 : 0 : default:
2073 : 0 : Py_UNREACHABLE();
2074 : : }
2075 : :
2076 : : /* Compute exact length 'sz' of output string. */
2077 [ + + ]: 270270 : if (size_a == 0) {
2078 : 83904 : sz = 1;
2079 : : }
2080 : : else {
2081 : : Py_ssize_t size_a_in_bits;
2082 : : /* Ensure overflow doesn't occur during computation of sz. */
2083 [ - + ]: 186366 : if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
2084 : 0 : PyErr_SetString(PyExc_OverflowError,
2085 : : "int too large to format");
2086 : 0 : return -1;
2087 : : }
2088 : 372732 : size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
2089 : 186366 : bit_length_digit(a->long_value.ob_digit[size_a - 1]);
2090 : : /* Allow 1 character for a '-' sign. */
2091 : 186366 : sz = negative + (size_a_in_bits + (bits - 1)) / bits;
2092 : : }
2093 [ + - ]: 270270 : if (alternate) {
2094 : : /* 2 characters for prefix */
2095 : 270270 : sz += 2;
2096 : : }
2097 : :
2098 [ - + ]: 270270 : if (writer) {
2099 [ # # # # : 0 : if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
# # # # ]
2100 : 0 : return -1;
2101 : 0 : kind = writer->kind;
2102 : : }
2103 [ - + ]: 270270 : else if (bytes_writer) {
2104 : 0 : *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
2105 [ # # ]: 0 : if (*bytes_str == NULL)
2106 : 0 : return -1;
2107 : : }
2108 : : else {
2109 : 270270 : v = PyUnicode_New(sz, 'x');
2110 [ - + ]: 270270 : if (v == NULL)
2111 : 0 : return -1;
2112 : 270270 : kind = PyUnicode_KIND(v);
2113 : : }
2114 : :
2115 : : #define WRITE_DIGITS(p) \
2116 : : do { \
2117 : : if (size_a == 0) { \
2118 : : *--p = '0'; \
2119 : : } \
2120 : : else { \
2121 : : /* JRH: special case for power-of-2 bases */ \
2122 : : twodigits accum = 0; \
2123 : : int accumbits = 0; /* # of bits in accum */ \
2124 : : Py_ssize_t i; \
2125 : : for (i = 0; i < size_a; ++i) { \
2126 : : accum |= (twodigits)a->long_value.ob_digit[i] << accumbits; \
2127 : : accumbits += PyLong_SHIFT; \
2128 : : assert(accumbits >= bits); \
2129 : : do { \
2130 : : char cdigit; \
2131 : : cdigit = (char)(accum & (base - 1)); \
2132 : : cdigit += (cdigit < 10) ? '0' : 'a'-10; \
2133 : : *--p = cdigit; \
2134 : : accumbits -= bits; \
2135 : : accum >>= bits; \
2136 : : } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
2137 : : } \
2138 : : } \
2139 : : \
2140 : : if (alternate) { \
2141 : : if (base == 16) \
2142 : : *--p = 'x'; \
2143 : : else if (base == 8) \
2144 : : *--p = 'o'; \
2145 : : else /* (base == 2) */ \
2146 : : *--p = 'b'; \
2147 : : *--p = '0'; \
2148 : : } \
2149 : : if (negative) \
2150 : : *--p = '-'; \
2151 : : } while (0)
2152 : :
2153 : : #define WRITE_UNICODE_DIGITS(TYPE) \
2154 : : do { \
2155 : : if (writer) \
2156 : : p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
2157 : : else \
2158 : : p = (TYPE*)PyUnicode_DATA(v) + sz; \
2159 : : \
2160 : : WRITE_DIGITS(p); \
2161 : : \
2162 : : if (writer) \
2163 : : assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2164 : : else \
2165 : : assert(p == (TYPE*)PyUnicode_DATA(v)); \
2166 : : } while (0)
2167 : :
2168 [ - + ]: 270270 : if (bytes_writer) {
2169 : 0 : char *p = *bytes_str + sz;
2170 [ # # # # : 0 : WRITE_DIGITS(p);
# # # # #
# # # # #
# # # # ]
2171 : : assert(p == *bytes_str);
2172 : : }
2173 [ + - ]: 270270 : else if (kind == PyUnicode_1BYTE_KIND) {
2174 : : Py_UCS1 *p;
2175 [ - + + + : 806225 : WRITE_UNICODE_DIGITS(Py_UCS1);
+ + + + +
+ + + + -
+ + - + -
+ ]
2176 : : }
2177 [ # # ]: 0 : else if (kind == PyUnicode_2BYTE_KIND) {
2178 : : Py_UCS2 *p;
2179 [ # # # # : 0 : WRITE_UNICODE_DIGITS(Py_UCS2);
# # # # #
# # # # #
# # # # #
# ]
2180 : : }
2181 : : else {
2182 : : Py_UCS4 *p;
2183 : : assert (kind == PyUnicode_4BYTE_KIND);
2184 [ # # # # : 0 : WRITE_UNICODE_DIGITS(Py_UCS4);
# # # # #
# # # # #
# # # # #
# ]
2185 : : }
2186 : : #undef WRITE_DIGITS
2187 : : #undef WRITE_UNICODE_DIGITS
2188 : :
2189 [ - + ]: 270270 : if (writer) {
2190 : 0 : writer->pos += sz;
2191 : : }
2192 [ - + ]: 270270 : else if (bytes_writer) {
2193 : 0 : (*bytes_str) += sz;
2194 : : }
2195 : : else {
2196 : : assert(_PyUnicode_CheckConsistency(v, 1));
2197 : 270270 : *p_output = v;
2198 : : }
2199 : 270270 : return 0;
2200 : : }
2201 : :
2202 : : PyObject *
2203 : 270275 : _PyLong_Format(PyObject *obj, int base)
2204 : : {
2205 : : PyObject *str;
2206 : : int err;
2207 [ + + ]: 270275 : if (base == 10)
2208 : 5 : err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
2209 : : else
2210 : 270270 : err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
2211 [ - + ]: 270275 : if (err == -1)
2212 : 0 : return NULL;
2213 : 270275 : return str;
2214 : : }
2215 : :
2216 : : int
2217 : 134 : _PyLong_FormatWriter(_PyUnicodeWriter *writer,
2218 : : PyObject *obj,
2219 : : int base, int alternate)
2220 : : {
2221 [ + - ]: 134 : if (base == 10)
2222 : 134 : return long_to_decimal_string_internal(obj, NULL, writer,
2223 : : NULL, NULL);
2224 : : else
2225 : 0 : return long_format_binary(obj, base, alternate, NULL, writer,
2226 : : NULL, NULL);
2227 : : }
2228 : :
2229 : : char*
2230 : 0 : _PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2231 : : PyObject *obj,
2232 : : int base, int alternate)
2233 : : {
2234 : : char *str2;
2235 : : int res;
2236 : 0 : str2 = str;
2237 [ # # ]: 0 : if (base == 10)
2238 : 0 : res = long_to_decimal_string_internal(obj, NULL, NULL,
2239 : : writer, &str2);
2240 : : else
2241 : 0 : res = long_format_binary(obj, base, alternate, NULL, NULL,
2242 : : writer, &str2);
2243 [ # # ]: 0 : if (res < 0)
2244 : 0 : return NULL;
2245 : : assert(str2 != NULL);
2246 : 0 : return str2;
2247 : : }
2248 : :
2249 : : /* Table of digit values for 8-bit string -> integer conversion.
2250 : : * '0' maps to 0, ..., '9' maps to 9.
2251 : : * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2252 : : * All other indices map to 37.
2253 : : * Note that when converting a base B string, a char c is a legitimate
2254 : : * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
2255 : : */
2256 : : unsigned char _PyLong_DigitValue[256] = {
2257 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2258 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2259 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2260 : : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
2261 : : 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2262 : : 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2263 : : 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2264 : : 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2265 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2266 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2267 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2268 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2269 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2270 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2271 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2272 : : 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2273 : : };
2274 : :
2275 : : /* `start` and `end` point to the start and end of a string of base `base`
2276 : : * digits. base is a power of 2 (2, 4, 8, 16, or 32). An unnormalized int is
2277 : : * returned in *res. The string should be already validated by the caller and
2278 : : * consists only of valid digit characters and underscores. `digits` gives the
2279 : : * number of digit characters.
2280 : : *
2281 : : * The point to this routine is that it takes time linear in the
2282 : : * number of string characters.
2283 : : *
2284 : : * Return values:
2285 : : * -1 on syntax error (exception needs to be set, *res is untouched)
2286 : : * 0 else (exception may be set, in that case *res is set to NULL)
2287 : : */
2288 : : static int
2289 : 498 : long_from_binary_base(const char *start, const char *end, Py_ssize_t digits, int base, PyLongObject **res)
2290 : : {
2291 : : const char *p;
2292 : : int bits_per_char;
2293 : : Py_ssize_t n;
2294 : : PyLongObject *z;
2295 : : twodigits accum;
2296 : : int bits_in_accum;
2297 : : digit *pdigit;
2298 : :
2299 : : assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2300 : 498 : n = base;
2301 [ + + ]: 1500 : for (bits_per_char = -1; n; ++bits_per_char) {
2302 : 1002 : n >>= 1;
2303 : : }
2304 : :
2305 : : /* n <- the number of Python digits needed,
2306 : : = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2307 [ - + ]: 498 : if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
2308 : 0 : PyErr_SetString(PyExc_ValueError,
2309 : : "int string too large to convert");
2310 : 0 : *res = NULL;
2311 : 0 : return 0;
2312 : : }
2313 : 498 : n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
2314 : 498 : z = _PyLong_New(n);
2315 [ - + ]: 498 : if (z == NULL) {
2316 : 0 : *res = NULL;
2317 : 0 : return 0;
2318 : : }
2319 : : /* Read string from right, and fill in int from left; i.e.,
2320 : : * from least to most significant in both.
2321 : : */
2322 : 498 : accum = 0;
2323 : 498 : bits_in_accum = 0;
2324 : 498 : pdigit = z->long_value.ob_digit;
2325 : 498 : p = end;
2326 [ + + ]: 16402 : while (--p >= start) {
2327 : : int k;
2328 [ - + ]: 15904 : if (*p == '_') {
2329 : 0 : continue;
2330 : : }
2331 : 15904 : k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
2332 : : assert(k >= 0 && k < base);
2333 : 15904 : accum |= (twodigits)k << bits_in_accum;
2334 : 15904 : bits_in_accum += bits_per_char;
2335 [ + + ]: 15904 : if (bits_in_accum >= PyLong_SHIFT) {
2336 : 500 : *pdigit++ = (digit)(accum & PyLong_MASK);
2337 : : assert(pdigit - z->long_value.ob_digit <= n);
2338 : 500 : accum >>= PyLong_SHIFT;
2339 : 500 : bits_in_accum -= PyLong_SHIFT;
2340 : : assert(bits_in_accum < PyLong_SHIFT);
2341 : : }
2342 : : }
2343 [ + - ]: 498 : if (bits_in_accum) {
2344 : : assert(bits_in_accum <= PyLong_SHIFT);
2345 : 498 : *pdigit++ = (digit)accum;
2346 : : assert(pdigit - z->long_value.ob_digit <= n);
2347 : : }
2348 [ - + ]: 498 : while (pdigit - z->long_value.ob_digit < n)
2349 : 0 : *pdigit++ = 0;
2350 : 498 : *res = z;
2351 : 498 : return 0;
2352 : : }
2353 : :
2354 : : static PyObject *long_neg(PyLongObject *v);
2355 : :
2356 : : #ifdef WITH_PYLONG_MODULE
2357 : : /* asymptotically faster str-to-long conversion for base 10, using _pylong.py */
2358 : : static int
2359 : 0 : pylong_int_from_string(const char *start, const char *end, PyLongObject **res)
2360 : : {
2361 : 0 : PyObject *mod = PyImport_ImportModule("_pylong");
2362 [ # # ]: 0 : if (mod == NULL) {
2363 : 0 : goto error;
2364 : : }
2365 : 0 : PyObject *s = PyUnicode_FromStringAndSize(start, end-start);
2366 [ # # ]: 0 : if (s == NULL) {
2367 : 0 : Py_DECREF(mod);
2368 : 0 : goto error;
2369 : : }
2370 : 0 : PyObject *result = PyObject_CallMethod(mod, "int_from_string", "O", s);
2371 : 0 : Py_DECREF(s);
2372 : 0 : Py_DECREF(mod);
2373 [ # # ]: 0 : if (result == NULL) {
2374 : 0 : goto error;
2375 : : }
2376 [ # # ]: 0 : if (!PyLong_Check(result)) {
2377 : 0 : Py_DECREF(result);
2378 : 0 : PyErr_SetString(PyExc_TypeError,
2379 : : "_pylong.int_from_string did not return an int");
2380 : 0 : goto error;
2381 : : }
2382 : 0 : *res = (PyLongObject *)result;
2383 : 0 : return 0;
2384 : 0 : error:
2385 : 0 : *res = NULL;
2386 : 0 : return 0; // See the long_from_string_base() API comment.
2387 : : }
2388 : : #endif /* WITH_PYLONG_MODULE */
2389 : :
2390 : : /***
2391 : : long_from_non_binary_base: parameters and return values are the same as
2392 : : long_from_binary_base.
2393 : :
2394 : : Binary bases can be converted in time linear in the number of digits, because
2395 : : Python's representation base is binary. Other bases (including decimal!) use
2396 : : the simple quadratic-time algorithm below, complicated by some speed tricks.
2397 : :
2398 : : First some math: the largest integer that can be expressed in N base-B digits
2399 : : is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2400 : : case number of Python digits needed to hold it is the smallest integer n s.t.
2401 : :
2402 : : BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2403 : : BASE**n >= B**N [taking logs to base BASE]
2404 : : n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2405 : :
2406 : : The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2407 : : this quickly. A Python int with that much space is reserved near the start,
2408 : : and the result is computed into it.
2409 : :
2410 : : The input string is actually treated as being in base base**i (i.e., i digits
2411 : : are processed at a time), where two more static arrays hold:
2412 : :
2413 : : convwidth_base[base] = the largest integer i such that base**i <= BASE
2414 : : convmultmax_base[base] = base ** convwidth_base[base]
2415 : :
2416 : : The first of these is the largest i such that i consecutive input digits
2417 : : must fit in a single Python digit. The second is effectively the input
2418 : : base we're really using.
2419 : :
2420 : : Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2421 : : convmultmax_base[base], the result is "simply"
2422 : :
2423 : : (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2424 : :
2425 : : where B = convmultmax_base[base].
2426 : :
2427 : : Error analysis: as above, the number of Python digits `n` needed is worst-
2428 : : case
2429 : :
2430 : : n >= N * log(B)/log(BASE)
2431 : :
2432 : : where `N` is the number of input digits in base `B`. This is computed via
2433 : :
2434 : : size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2435 : :
2436 : : below. Two numeric concerns are how much space this can waste, and whether
2437 : : the computed result can be too small. To be concrete, assume BASE = 2**15,
2438 : : which is the default (and it's unlikely anyone changes that).
2439 : :
2440 : : Waste isn't a problem: provided the first input digit isn't 0, the difference
2441 : : between the worst-case input with N digits and the smallest input with N
2442 : : digits is about a factor of B, but B is small compared to BASE so at most
2443 : : one allocated Python digit can remain unused on that count. If
2444 : : N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2445 : : and adding 1 returns a result 1 larger than necessary. However, that can't
2446 : : happen: whenever B is a power of 2, long_from_binary_base() is called
2447 : : instead, and it's impossible for B**i to be an integer power of 2**15 when
2448 : : B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2449 : : an exact integer when B is not a power of 2, since B**i has a prime factor
2450 : : other than 2 in that case, but (2**15)**j's only prime factor is 2).
2451 : :
2452 : : The computed result can be too small if the true value of N*log(B)/log(BASE)
2453 : : is a little bit larger than an exact integer, but due to roundoff errors (in
2454 : : computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2455 : : yields a numeric result a little less than that integer. Unfortunately, "how
2456 : : close can a transcendental function get to an integer over some range?"
2457 : : questions are generally theoretically intractable. Computer analysis via
2458 : : continued fractions is practical: expand log(B)/log(BASE) via continued
2459 : : fractions, giving a sequence i/j of "the best" rational approximations. Then
2460 : : j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2461 : : we can get very close to being in trouble, but very rarely. For example,
2462 : : 76573 is a denominator in one of the continued-fraction approximations to
2463 : : log(10)/log(2**15), and indeed:
2464 : :
2465 : : >>> log(10)/log(2**15)*76573
2466 : : 16958.000000654003
2467 : :
2468 : : is very close to an integer. If we were working with IEEE single-precision,
2469 : : rounding errors could kill us. Finding worst cases in IEEE double-precision
2470 : : requires better-than-double-precision log() functions, and Tim didn't bother.
2471 : : Instead the code checks to see whether the allocated space is enough as each
2472 : : new Python digit is added, and copies the whole thing to a larger int if not.
2473 : : This should happen extremely rarely, and in fact I don't have a test case
2474 : : that triggers it(!). Instead the code was tested by artificially allocating
2475 : : just 1 digit at the start, so that the copying code was exercised for every
2476 : : digit beyond the first.
2477 : : ***/
2478 : : static int
2479 : 487 : long_from_non_binary_base(const char *start, const char *end, Py_ssize_t digits, int base, PyLongObject **res)
2480 : : {
2481 : : twodigits c; /* current input character */
2482 : : Py_ssize_t size_z;
2483 : : int i;
2484 : : int convwidth;
2485 : : twodigits convmultmax, convmult;
2486 : : digit *pz, *pzstop;
2487 : : PyLongObject *z;
2488 : : const char *p;
2489 : :
2490 : : static double log_base_BASE[37] = {0.0e0,};
2491 : : static int convwidth_base[37] = {0,};
2492 : : static twodigits convmultmax_base[37] = {0,};
2493 : :
2494 [ + + ]: 487 : if (log_base_BASE[base] == 0.0) {
2495 : 3 : twodigits convmax = base;
2496 : 3 : int i = 1;
2497 : :
2498 : 3 : log_base_BASE[base] = (log((double)base) /
2499 : : log((double)PyLong_BASE));
2500 : 24 : for (;;) {
2501 : 27 : twodigits next = convmax * base;
2502 [ + + ]: 27 : if (next > PyLong_BASE) {
2503 : 3 : break;
2504 : : }
2505 : 24 : convmax = next;
2506 : 24 : ++i;
2507 : : }
2508 : 3 : convmultmax_base[base] = convmax;
2509 : : assert(i > 0);
2510 : 3 : convwidth_base[base] = i;
2511 : : }
2512 : :
2513 : : /* Create an int object that can contain the largest possible
2514 : : * integer with this base and length. Note that there's no
2515 : : * need to initialize z->long_value.ob_digit -- no slot is read up before
2516 : : * being stored into.
2517 : : */
2518 : 487 : double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2519 [ - + ]: 487 : if (fsize_z > (double)MAX_LONG_DIGITS) {
2520 : : /* The same exception as in _PyLong_New(). */
2521 : 0 : PyErr_SetString(PyExc_OverflowError,
2522 : : "too many digits in integer");
2523 : 0 : *res = NULL;
2524 : 0 : return 0;
2525 : : }
2526 : 487 : size_z = (Py_ssize_t)fsize_z;
2527 : : /* Uncomment next line to test exceedingly rare copy code */
2528 : : /* size_z = 1; */
2529 : : assert(size_z > 0);
2530 : 487 : z = _PyLong_New(size_z);
2531 [ - + ]: 487 : if (z == NULL) {
2532 : 0 : *res = NULL;
2533 : 0 : return 0;
2534 : : }
2535 : 487 : Py_SET_SIZE(z, 0);
2536 : :
2537 : : /* `convwidth` consecutive input digits are treated as a single
2538 : : * digit in base `convmultmax`.
2539 : : */
2540 : 487 : convwidth = convwidth_base[base];
2541 : 487 : convmultmax = convmultmax_base[base];
2542 : :
2543 : : /* Work ;-) */
2544 : 487 : p = start;
2545 [ + + ]: 1067 : while (p < end) {
2546 [ - + ]: 580 : if (*p == '_') {
2547 : 0 : p++;
2548 : 0 : continue;
2549 : : }
2550 : : /* grab up to convwidth digits from the input string */
2551 : 580 : c = (digit)_PyLong_DigitValue[Py_CHARMASK(*p++)];
2552 [ + + + + ]: 1418 : for (i = 1; i < convwidth && p != end; ++p) {
2553 [ - + ]: 838 : if (*p == '_') {
2554 : 0 : continue;
2555 : : }
2556 : 838 : i++;
2557 : 838 : c = (twodigits)(c * base +
2558 : 838 : (int)_PyLong_DigitValue[Py_CHARMASK(*p)]);
2559 : : assert(c < PyLong_BASE);
2560 : : }
2561 : :
2562 : 580 : convmult = convmultmax;
2563 : : /* Calculate the shift only if we couldn't get
2564 : : * convwidth digits.
2565 : : */
2566 [ + + ]: 580 : if (i != convwidth) {
2567 : 483 : convmult = base;
2568 [ + + ]: 545 : for ( ; i > 1; --i) {
2569 : 62 : convmult *= base;
2570 : : }
2571 : : }
2572 : :
2573 : : /* Multiply z by convmult, and add c. */
2574 : 580 : pz = z->long_value.ob_digit;
2575 : 580 : pzstop = pz + Py_SIZE(z);
2576 [ + + ]: 840 : for (; pz < pzstop; ++pz) {
2577 : 260 : c += (twodigits)*pz * convmult;
2578 : 260 : *pz = (digit)(c & PyLong_MASK);
2579 : 260 : c >>= PyLong_SHIFT;
2580 : : }
2581 : : /* carry off the current end? */
2582 [ + + ]: 580 : if (c) {
2583 : : assert(c < PyLong_BASE);
2584 [ + - ]: 574 : if (Py_SIZE(z) < size_z) {
2585 : 574 : *pz = (digit)c;
2586 : 574 : Py_SET_SIZE(z, Py_SIZE(z) + 1);
2587 : : }
2588 : : else {
2589 : : PyLongObject *tmp;
2590 : : /* Extremely rare. Get more space. */
2591 : : assert(Py_SIZE(z) == size_z);
2592 : 0 : tmp = _PyLong_New(size_z + 1);
2593 [ # # ]: 0 : if (tmp == NULL) {
2594 : 0 : Py_DECREF(z);
2595 : 0 : *res = NULL;
2596 : 0 : return 0;
2597 : : }
2598 : 0 : memcpy(tmp->long_value.ob_digit,
2599 : 0 : z->long_value.ob_digit,
2600 : : sizeof(digit) * size_z);
2601 : 0 : Py_SETREF(z, tmp);
2602 : 0 : z->long_value.ob_digit[size_z] = (digit)c;
2603 : 0 : ++size_z;
2604 : : }
2605 : : }
2606 : : }
2607 : 487 : *res = z;
2608 : 487 : return 0;
2609 : : }
2610 : :
2611 : : /* *str points to the first digit in a string of base `base` digits. base is an
2612 : : * integer from 2 to 36 inclusive. Here we don't need to worry about prefixes
2613 : : * like 0x or leading +- signs. The string should be null terminated consisting
2614 : : * of ASCII digits and separating underscores possibly with trailing whitespace
2615 : : * but we have to validate all of those points here.
2616 : : *
2617 : : * If base is a power of 2 then the complexity is linear in the number of
2618 : : * characters in the string. Otherwise a quadratic algorithm is used for
2619 : : * non-binary bases.
2620 : : *
2621 : : * Return values:
2622 : : *
2623 : : * - Returns -1 on syntax error (exception needs to be set, *res is untouched)
2624 : : * - Returns 0 and sets *res to NULL for MemoryError, OverflowError, or
2625 : : * _pylong.int_from_string() errors.
2626 : : * - Returns 0 and sets *res to an unsigned, unnormalized PyLong (success!).
2627 : : *
2628 : : * Afterwards *str is set to point to the first non-digit (which may be *str!).
2629 : : */
2630 : : static int
2631 : 1365 : long_from_string_base(const char **str, int base, PyLongObject **res)
2632 : : {
2633 : : const char *start, *end, *p;
2634 : 1365 : char prev = 0;
2635 : 1365 : Py_ssize_t digits = 0;
2636 : 1365 : int is_binary_base = (base & (base - 1)) == 0;
2637 : :
2638 : : /* Here we do four things:
2639 : : *
2640 : : * - Find the `end` of the string.
2641 : : * - Validate the string.
2642 : : * - Count the number of `digits` (rather than underscores)
2643 : : * - Point *str to the end-of-string or first invalid character.
2644 : : */
2645 : 1365 : start = p = *str;
2646 : : /* Leading underscore not allowed. */
2647 [ + + ]: 1365 : if (*start == '_') {
2648 : 1 : return -1;
2649 : : }
2650 : : /* Verify all characters are digits and underscores. */
2651 [ + + - + ]: 18688 : while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2652 [ - + ]: 17324 : if (*p == '_') {
2653 : : /* Double underscore not allowed. */
2654 [ # # ]: 0 : if (prev == '_') {
2655 : 0 : *str = p - 1;
2656 : 0 : return -1;
2657 : : }
2658 : : } else {
2659 : 17324 : ++digits;
2660 : : }
2661 : 17324 : prev = *p;
2662 : 17324 : ++p;
2663 : : }
2664 : : /* Trailing underscore not allowed. */
2665 [ - + ]: 1364 : if (prev == '_') {
2666 : 0 : *str = p - 1;
2667 : 0 : return -1;
2668 : : }
2669 : 1364 : *str = end = p;
2670 : : /* Reject empty strings */
2671 [ + + ]: 1364 : if (start == end) {
2672 : 377 : return -1;
2673 : : }
2674 : : /* Allow only trailing whitespace after `end` */
2675 [ + + - + ]: 987 : while (*p && Py_ISSPACE(*p)) {
2676 : 0 : p++;
2677 : : }
2678 : 987 : *str = p;
2679 [ + + ]: 987 : if (*p != '\0') {
2680 : 2 : return -1;
2681 : : }
2682 : :
2683 : : /*
2684 : : * Pass a validated string consisting of only valid digits and underscores
2685 : : * to long_from_xxx_base.
2686 : : */
2687 [ + + ]: 985 : if (is_binary_base) {
2688 : : /* Use the linear algorithm for binary bases. */
2689 : 498 : return long_from_binary_base(start, end, digits, base, res);
2690 : : }
2691 : : else {
2692 : : /* Limit the size to avoid excessive computation attacks exploiting the
2693 : : * quadratic algorithm. */
2694 [ - + ]: 487 : if (digits > _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
2695 : 0 : PyInterpreterState *interp = _PyInterpreterState_GET();
2696 : 0 : int max_str_digits = interp->long_state.max_str_digits;
2697 [ # # # # ]: 0 : if ((max_str_digits > 0) && (digits > max_str_digits)) {
2698 : 0 : PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_INT,
2699 : : max_str_digits, digits);
2700 : 0 : *res = NULL;
2701 : 0 : return 0;
2702 : : }
2703 : : }
2704 : : #if WITH_PYLONG_MODULE
2705 [ - + - - ]: 487 : if (digits > 6000 && base == 10) {
2706 : : /* Switch to _pylong.int_from_string() */
2707 : 0 : return pylong_int_from_string(start, end, res);
2708 : : }
2709 : : #endif
2710 : : /* Use the quadratic algorithm for non binary bases. */
2711 : 487 : return long_from_non_binary_base(start, end, digits, base, res);
2712 : : }
2713 : : }
2714 : :
2715 : : /* Parses an int from a bytestring. Leading and trailing whitespace will be
2716 : : * ignored.
2717 : : *
2718 : : * If successful, a PyLong object will be returned and 'pend' will be pointing
2719 : : * to the first unused byte unless it's NULL.
2720 : : *
2721 : : * If unsuccessful, NULL will be returned.
2722 : : */
2723 : : PyObject *
2724 : 1365 : PyLong_FromString(const char *str, char **pend, int base)
2725 : : {
2726 : 1365 : int sign = 1, error_if_nonzero = 0;
2727 : 1365 : const char *orig_str = str;
2728 : 1365 : PyLongObject *z = NULL;
2729 : : PyObject *strobj;
2730 : : Py_ssize_t slen;
2731 : :
2732 [ + + + - : 1365 : if ((base != 0 && base < 2) || base > 36) {
- + ]
2733 : 0 : PyErr_SetString(PyExc_ValueError,
2734 : : "int() arg 2 must be >= 2 and <= 36");
2735 : 0 : return NULL;
2736 : : }
2737 [ + + + + ]: 1394 : while (*str != '\0' && Py_ISSPACE(*str)) {
2738 : 29 : ++str;
2739 : : }
2740 [ - + ]: 1365 : if (*str == '+') {
2741 : 0 : ++str;
2742 : : }
2743 [ + + ]: 1365 : else if (*str == '-') {
2744 : 76 : ++str;
2745 : 76 : sign = -1;
2746 : : }
2747 [ + + ]: 1365 : if (base == 0) {
2748 [ + + ]: 28 : if (str[0] != '0') {
2749 : 26 : base = 10;
2750 : : }
2751 [ - + - - ]: 2 : else if (str[1] == 'x' || str[1] == 'X') {
2752 : 2 : base = 16;
2753 : : }
2754 [ # # # # ]: 0 : else if (str[1] == 'o' || str[1] == 'O') {
2755 : 0 : base = 8;
2756 : : }
2757 [ # # # # ]: 0 : else if (str[1] == 'b' || str[1] == 'B') {
2758 : 0 : base = 2;
2759 : : }
2760 : : else {
2761 : : /* "old" (C-style) octal literal, now invalid.
2762 : : it might still be zero though */
2763 : 0 : error_if_nonzero = 1;
2764 : 0 : base = 10;
2765 : : }
2766 : : }
2767 [ + + + + ]: 1365 : if (str[0] == '0' &&
2768 [ - + - - : 471 : ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
- + ]
2769 [ - - - - : 469 : (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
+ + ]
2770 [ + - - + ]: 467 : (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
2771 : 2 : str += 2;
2772 : : /* One underscore allowed here. */
2773 [ - + ]: 2 : if (*str == '_') {
2774 : 0 : ++str;
2775 : : }
2776 : : }
2777 : :
2778 : : /* long_from_string_base is the main workhorse here. */
2779 : 1365 : int ret = long_from_string_base(&str, base, &z);
2780 [ + + ]: 1365 : if (ret == -1) {
2781 : : /* Syntax error. */
2782 : 380 : goto onError;
2783 : : }
2784 [ - + ]: 985 : if (z == NULL) {
2785 : : /* Error. exception already set. */
2786 : 0 : return NULL;
2787 : : }
2788 : :
2789 [ - + ]: 985 : if (error_if_nonzero) {
2790 : : /* reset the base to 0, else the exception message
2791 : : doesn't make too much sense */
2792 : 0 : base = 0;
2793 [ # # ]: 0 : if (Py_SIZE(z) != 0) {
2794 : 0 : goto onError;
2795 : : }
2796 : : /* there might still be other problems, therefore base
2797 : : remains zero here for the same reason */
2798 : : }
2799 : :
2800 : : /* Set sign and normalize */
2801 [ - + ]: 985 : if (sign < 0) {
2802 : 0 : Py_SET_SIZE(z, -(Py_SIZE(z)));
2803 : : }
2804 : 985 : long_normalize(z);
2805 : 985 : z = maybe_small_long(z);
2806 : :
2807 [ + + ]: 985 : if (pend != NULL) {
2808 : 957 : *pend = (char *)str;
2809 : : }
2810 : 985 : return (PyObject *) z;
2811 : :
2812 : 380 : onError:
2813 [ + - ]: 380 : if (pend != NULL) {
2814 : 380 : *pend = (char *)str;
2815 : : }
2816 : 380 : Py_XDECREF(z);
2817 [ + + ]: 380 : slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2818 : 380 : strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2819 [ - + ]: 380 : if (strobj == NULL) {
2820 : 0 : return NULL;
2821 : : }
2822 : 380 : PyErr_Format(PyExc_ValueError,
2823 : : "invalid literal for int() with base %d: %.200R",
2824 : : base, strobj);
2825 : 380 : Py_DECREF(strobj);
2826 : 380 : return NULL;
2827 : : }
2828 : :
2829 : : /* Since PyLong_FromString doesn't have a length parameter,
2830 : : * check here for possible NULs in the string.
2831 : : *
2832 : : * Reports an invalid literal as a bytes object.
2833 : : */
2834 : : PyObject *
2835 : 496 : _PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2836 : : {
2837 : : PyObject *result, *strobj;
2838 : 496 : char *end = NULL;
2839 : :
2840 : 496 : result = PyLong_FromString(s, &end, base);
2841 [ + - + - : 496 : if (end == NULL || (result != NULL && end == s + len))
+ - ]
2842 : 496 : return result;
2843 : 0 : Py_XDECREF(result);
2844 : 0 : strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2845 [ # # ]: 0 : if (strobj != NULL) {
2846 : 0 : PyErr_Format(PyExc_ValueError,
2847 : : "invalid literal for int() with base %d: %.200R",
2848 : : base, strobj);
2849 : 0 : Py_DECREF(strobj);
2850 : : }
2851 : 0 : return NULL;
2852 : : }
2853 : :
2854 : : PyObject *
2855 : 841 : PyLong_FromUnicodeObject(PyObject *u, int base)
2856 : : {
2857 : : PyObject *result, *asciidig;
2858 : : const char *buffer;
2859 : 841 : char *end = NULL;
2860 : : Py_ssize_t buflen;
2861 : :
2862 : 841 : asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
2863 [ - + ]: 841 : if (asciidig == NULL)
2864 : 0 : return NULL;
2865 : : assert(PyUnicode_IS_ASCII(asciidig));
2866 : : /* Simply get a pointer to existing ASCII characters. */
2867 : 841 : buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
2868 : : assert(buffer != NULL);
2869 : :
2870 : 841 : result = PyLong_FromString(buffer, &end, base);
2871 [ + - + + : 841 : if (end == NULL || (result != NULL && end == buffer + buflen)) {
+ - ]
2872 : 461 : Py_DECREF(asciidig);
2873 : 461 : return result;
2874 : : }
2875 : 380 : Py_DECREF(asciidig);
2876 : 380 : Py_XDECREF(result);
2877 : 380 : PyErr_Format(PyExc_ValueError,
2878 : : "invalid literal for int() with base %d: %.200R",
2879 : : base, u);
2880 : 380 : return NULL;
2881 : : }
2882 : :
2883 : : /* forward */
2884 : : static PyLongObject *x_divrem
2885 : : (PyLongObject *, PyLongObject *, PyLongObject **);
2886 : : static PyObject *long_long(PyObject *v);
2887 : :
2888 : : /* Int division with remainder, top-level routine */
2889 : :
2890 : : static int
2891 : 92197 : long_divrem(PyLongObject *a, PyLongObject *b,
2892 : : PyLongObject **pdiv, PyLongObject **prem)
2893 : : {
2894 [ + + - + ]: 92197 : Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
2895 : : PyLongObject *z;
2896 : :
2897 [ - + ]: 92197 : if (size_b == 0) {
2898 : 0 : PyErr_SetString(PyExc_ZeroDivisionError,
2899 : : "integer division or modulo by zero");
2900 : 0 : return -1;
2901 : : }
2902 [ + + + + ]: 92197 : if (size_a < size_b ||
2903 : 38392 : (size_a == size_b &&
2904 [ - + ]: 38392 : a->long_value.ob_digit[size_a-1] < b->long_value.ob_digit[size_b-1])) {
2905 : : /* |a| < |b|. */
2906 : 2145 : *prem = (PyLongObject *)long_long((PyObject *)a);
2907 [ - + ]: 2145 : if (*prem == NULL) {
2908 : 0 : return -1;
2909 : : }
2910 : 2145 : PyObject *zero = _PyLong_GetZero();
2911 : 2145 : *pdiv = (PyLongObject*)Py_NewRef(zero);
2912 : 2145 : return 0;
2913 : : }
2914 [ + + ]: 90052 : if (size_b == 1) {
2915 : 22906 : digit rem = 0;
2916 : 22906 : z = divrem1(a, b->long_value.ob_digit[0], &rem);
2917 [ - + ]: 22906 : if (z == NULL)
2918 : 0 : return -1;
2919 : 22906 : *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2920 [ - + ]: 22906 : if (*prem == NULL) {
2921 : 0 : Py_DECREF(z);
2922 : 0 : return -1;
2923 : : }
2924 : : }
2925 : : else {
2926 : 67146 : z = x_divrem(a, b, prem);
2927 : 67146 : *prem = maybe_small_long(*prem);
2928 [ - + ]: 67146 : if (z == NULL)
2929 : 0 : return -1;
2930 : : }
2931 : : /* Set the signs.
2932 : : The quotient z has the sign of a*b;
2933 : : the remainder r has the sign of a,
2934 : : so a = b*z + r. */
2935 [ + + ]: 90052 : if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2936 : 1030 : _PyLong_Negate(&z);
2937 [ - + ]: 1030 : if (z == NULL) {
2938 [ # # ]: 0 : Py_CLEAR(*prem);
2939 : 0 : return -1;
2940 : : }
2941 : : }
2942 [ + + + + ]: 90052 : if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2943 : 1022 : _PyLong_Negate(prem);
2944 [ - + ]: 1022 : if (*prem == NULL) {
2945 : 0 : Py_DECREF(z);
2946 [ # # ]: 0 : Py_CLEAR(*prem);
2947 : 0 : return -1;
2948 : : }
2949 : : }
2950 : 90052 : *pdiv = maybe_small_long(z);
2951 : 90052 : return 0;
2952 : : }
2953 : :
2954 : : /* Int remainder, top-level routine */
2955 : :
2956 : : static int
2957 : 27184 : long_rem(PyLongObject *a, PyLongObject *b, PyLongObject **prem)
2958 : : {
2959 [ - + - + ]: 27184 : Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
2960 : :
2961 [ - + ]: 27184 : if (size_b == 0) {
2962 : 0 : PyErr_SetString(PyExc_ZeroDivisionError,
2963 : : "integer modulo by zero");
2964 : 0 : return -1;
2965 : : }
2966 [ + - + + ]: 27184 : if (size_a < size_b ||
2967 : 17361 : (size_a == size_b &&
2968 [ - + ]: 17361 : a->long_value.ob_digit[size_a-1] < b->long_value.ob_digit[size_b-1])) {
2969 : : /* |a| < |b|. */
2970 : 0 : *prem = (PyLongObject *)long_long((PyObject *)a);
2971 : 0 : return -(*prem == NULL);
2972 : : }
2973 [ + + ]: 27184 : if (size_b == 1) {
2974 : 9807 : *prem = rem1(a, b->long_value.ob_digit[0]);
2975 [ - + ]: 9807 : if (*prem == NULL)
2976 : 0 : return -1;
2977 : : }
2978 : : else {
2979 : : /* Slow path using divrem. */
2980 : 17377 : Py_XDECREF(x_divrem(a, b, prem));
2981 : 17377 : *prem = maybe_small_long(*prem);
2982 [ - + ]: 17377 : if (*prem == NULL)
2983 : 0 : return -1;
2984 : : }
2985 : : /* Set the sign. */
2986 [ - + - - ]: 27184 : if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2987 : 0 : _PyLong_Negate(prem);
2988 [ # # ]: 0 : if (*prem == NULL) {
2989 [ # # ]: 0 : Py_CLEAR(*prem);
2990 : 0 : return -1;
2991 : : }
2992 : : }
2993 : 27184 : return 0;
2994 : : }
2995 : :
2996 : : /* Unsigned int division with remainder -- the algorithm. The arguments v1
2997 : : and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
2998 : :
2999 : : static PyLongObject *
3000 : 84527 : x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
3001 : : {
3002 : : PyLongObject *v, *w, *a;
3003 : : Py_ssize_t i, k, size_v, size_w;
3004 : : int d;
3005 : : digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
3006 : : twodigits vv;
3007 : : sdigit zhi;
3008 : : stwodigits z;
3009 : :
3010 : : /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
3011 : : edn.), section 4.3.1, Algorithm D], except that we don't explicitly
3012 : : handle the special case when the initial estimate q for a quotient
3013 : : digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
3014 : : that won't overflow a digit. */
3015 : :
3016 : : /* allocate space; w will also be used to hold the final remainder */
3017 [ + + ]: 84527 : size_v = Py_ABS(Py_SIZE(v1));
3018 [ - + ]: 84527 : size_w = Py_ABS(Py_SIZE(w1));
3019 : : assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
3020 : 84527 : v = _PyLong_New(size_v+1);
3021 [ - + ]: 84527 : if (v == NULL) {
3022 : 0 : *prem = NULL;
3023 : 0 : return NULL;
3024 : : }
3025 : 84527 : w = _PyLong_New(size_w);
3026 [ - + ]: 84527 : if (w == NULL) {
3027 : 0 : Py_DECREF(v);
3028 : 0 : *prem = NULL;
3029 : 0 : return NULL;
3030 : : }
3031 : :
3032 : : /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
3033 : : shift v1 left by the same amount. Results go into w and v. */
3034 : 84527 : d = PyLong_SHIFT - bit_length_digit(w1->long_value.ob_digit[size_w-1]);
3035 : 84527 : carry = v_lshift(w->long_value.ob_digit, w1->long_value.ob_digit, size_w, d);
3036 : : assert(carry == 0);
3037 : 84527 : carry = v_lshift(v->long_value.ob_digit, v1->long_value.ob_digit, size_v, d);
3038 [ + + + + ]: 84527 : if (carry != 0 || v->long_value.ob_digit[size_v-1] >= w->long_value.ob_digit[size_w-1]) {
3039 : 71119 : v->long_value.ob_digit[size_v] = carry;
3040 : 71119 : size_v++;
3041 : : }
3042 : :
3043 : : /* Now v->long_value.ob_digit[size_v-1] < w->long_value.ob_digit[size_w-1], so quotient has
3044 : : at most (and usually exactly) k = size_v - size_w digits. */
3045 : 84527 : k = size_v - size_w;
3046 : : assert(k >= 0);
3047 : 84527 : a = _PyLong_New(k);
3048 [ - + ]: 84527 : if (a == NULL) {
3049 : 0 : Py_DECREF(w);
3050 : 0 : Py_DECREF(v);
3051 : 0 : *prem = NULL;
3052 : 0 : return NULL;
3053 : : }
3054 : 84527 : v0 = v->long_value.ob_digit;
3055 : 84527 : w0 = w->long_value.ob_digit;
3056 : 84527 : wm1 = w0[size_w-1];
3057 : 84527 : wm2 = w0[size_w-2];
3058 [ + + ]: 233852 : for (vk = v0+k, ak = a->long_value.ob_digit + k; vk-- > v0;) {
3059 : : /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
3060 : : single-digit quotient q, remainder in vk[0:size_w]. */
3061 : :
3062 [ - + ]: 149325 : SIGCHECK({
3063 : : Py_DECREF(a);
3064 : : Py_DECREF(w);
3065 : : Py_DECREF(v);
3066 : : *prem = NULL;
3067 : : return NULL;
3068 : : });
3069 : :
3070 : : /* estimate quotient digit q; may overestimate by 1 (rare) */
3071 : 149325 : vtop = vk[size_w];
3072 : : assert(vtop <= wm1);
3073 : 149325 : vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
3074 : : /* The code used to compute the remainder via
3075 : : * r = (digit)(vv - (twodigits)wm1 * q);
3076 : : * and compilers generally generated code to do the * and -.
3077 : : * But modern processors generally compute q and r with a single
3078 : : * instruction, and modern optimizing compilers exploit that if we
3079 : : * _don't_ try to optimize it.
3080 : : */
3081 : 149325 : q = (digit)(vv / wm1);
3082 : 149325 : r = (digit)(vv % wm1);
3083 : 149325 : while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
3084 [ + + ]: 159391 : | vk[size_w-2])) {
3085 : 15083 : --q;
3086 : 15083 : r += wm1;
3087 [ + + ]: 15083 : if (r >= PyLong_BASE)
3088 : 5017 : break;
3089 : : }
3090 : : assert(q <= PyLong_BASE);
3091 : :
3092 : : /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
3093 : 149325 : zhi = 0;
3094 [ + + ]: 3784746 : for (i = 0; i < size_w; ++i) {
3095 : : /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
3096 : : -PyLong_BASE * q <= z < PyLong_BASE */
3097 : 3635421 : z = (sdigit)vk[i] + zhi -
3098 : 3635421 : (stwodigits)q * (stwodigits)w0[i];
3099 : 3635421 : vk[i] = (digit)z & PyLong_MASK;
3100 : 3635421 : zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
3101 : : z, PyLong_SHIFT);
3102 : : }
3103 : :
3104 : : /* add w back if q was too large (this branch taken rarely) */
3105 : : assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
3106 [ - + ]: 149325 : if ((sdigit)vtop + zhi < 0) {
3107 : 0 : carry = 0;
3108 [ # # ]: 0 : for (i = 0; i < size_w; ++i) {
3109 : 0 : carry += vk[i] + w0[i];
3110 : 0 : vk[i] = carry & PyLong_MASK;
3111 : 0 : carry >>= PyLong_SHIFT;
3112 : : }
3113 : 0 : --q;
3114 : : }
3115 : :
3116 : : /* store quotient digit */
3117 : : assert(q < PyLong_BASE);
3118 : 149325 : *--ak = q;
3119 : : }
3120 : :
3121 : : /* unshift remainder; we reuse w to store the result */
3122 : 84527 : carry = v_rshift(w0, v0, size_w, d);
3123 : : assert(carry==0);
3124 : 84527 : Py_DECREF(v);
3125 : :
3126 : 84527 : *prem = long_normalize(w);
3127 : 84527 : return long_normalize(a);
3128 : : }
3129 : :
3130 : : /* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
3131 : : abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
3132 : : rounded to DBL_MANT_DIG significant bits using round-half-to-even.
3133 : : If a == 0, return 0.0 and set *e = 0. If the resulting exponent
3134 : : e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
3135 : : -1.0. */
3136 : :
3137 : : /* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
3138 : : #if DBL_MANT_DIG == 53
3139 : : #define EXP2_DBL_MANT_DIG 9007199254740992.0
3140 : : #else
3141 : : #define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
3142 : : #endif
3143 : :
3144 : : double
3145 : 2029 : _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
3146 : : {
3147 : : Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
3148 : : /* See below for why x_digits is always large enough. */
3149 : : digit rem;
3150 : 2029 : digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
3151 : : double dx;
3152 : : /* Correction term for round-half-to-even rounding. For a digit x,
3153 : : "x + half_even_correction[x & 7]" gives x rounded to the nearest
3154 : : multiple of 4, rounding ties to a multiple of 8. */
3155 : : static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
3156 : :
3157 [ + + ]: 2029 : a_size = Py_ABS(Py_SIZE(a));
3158 [ - + ]: 2029 : if (a_size == 0) {
3159 : : /* Special case for 0: significand 0.0, exponent 0. */
3160 : 0 : *e = 0;
3161 : 0 : return 0.0;
3162 : : }
3163 : 2029 : a_bits = bit_length_digit(a->long_value.ob_digit[a_size-1]);
3164 : : /* The following is an overflow-free version of the check
3165 : : "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
3166 [ - + - - ]: 2029 : if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
3167 [ # # ]: 0 : (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
3168 : : a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
3169 : 0 : goto overflow;
3170 : 2029 : a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
3171 : :
3172 : : /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
3173 : : (shifting left if a_bits <= DBL_MANT_DIG + 2).
3174 : :
3175 : : Number of digits needed for result: write // for floor division.
3176 : : Then if shifting left, we end up using
3177 : :
3178 : : 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
3179 : :
3180 : : digits. If shifting right, we use
3181 : :
3182 : : a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
3183 : :
3184 : : digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
3185 : : the inequalities
3186 : :
3187 : : m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
3188 : : m // PyLong_SHIFT - n // PyLong_SHIFT <=
3189 : : 1 + (m - n - 1) // PyLong_SHIFT,
3190 : :
3191 : : valid for any integers m and n, we find that x_size satisfies
3192 : :
3193 : : x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
3194 : :
3195 : : in both cases.
3196 : : */
3197 [ + + ]: 2029 : if (a_bits <= DBL_MANT_DIG + 2) {
3198 : 2005 : shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
3199 : 2005 : shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
3200 : 2005 : x_size = shift_digits;
3201 : 2005 : rem = v_lshift(x_digits + x_size, a->long_value.ob_digit, a_size,
3202 : : (int)shift_bits);
3203 : 2005 : x_size += a_size;
3204 : 2005 : x_digits[x_size++] = rem;
3205 : : }
3206 : : else {
3207 : 24 : shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
3208 : 24 : shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
3209 : 24 : rem = v_rshift(x_digits, a->long_value.ob_digit + shift_digits,
3210 : : a_size - shift_digits, (int)shift_bits);
3211 : 24 : x_size = a_size - shift_digits;
3212 : : /* For correct rounding below, we need the least significant
3213 : : bit of x to be 'sticky' for this shift: if any of the bits
3214 : : shifted out was nonzero, we set the least significant bit
3215 : : of x. */
3216 [ + + ]: 24 : if (rem)
3217 : 9 : x_digits[0] |= 1;
3218 : : else
3219 [ + + ]: 257 : while (shift_digits > 0)
3220 [ - + ]: 242 : if (a->long_value.ob_digit[--shift_digits]) {
3221 : 0 : x_digits[0] |= 1;
3222 : 0 : break;
3223 : : }
3224 : : }
3225 : : assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
3226 : :
3227 : : /* Round, and convert to double. */
3228 : 2029 : x_digits[0] += half_even_correction[x_digits[0] & 7];
3229 : 2029 : dx = x_digits[--x_size];
3230 [ + + ]: 6087 : while (x_size > 0)
3231 : 4058 : dx = dx * PyLong_BASE + x_digits[--x_size];
3232 : :
3233 : : /* Rescale; make correction if result is 1.0. */
3234 : 2029 : dx /= 4.0 * EXP2_DBL_MANT_DIG;
3235 [ - + ]: 2029 : if (dx == 1.0) {
3236 [ # # ]: 0 : if (a_bits == PY_SSIZE_T_MAX)
3237 : 0 : goto overflow;
3238 : 0 : dx = 0.5;
3239 : 0 : a_bits += 1;
3240 : : }
3241 : :
3242 : 2029 : *e = a_bits;
3243 [ + + ]: 2029 : return Py_SIZE(a) < 0 ? -dx : dx;
3244 : :
3245 : 0 : overflow:
3246 : : /* exponent > PY_SSIZE_T_MAX */
3247 : 0 : PyErr_SetString(PyExc_OverflowError,
3248 : : "huge integer: number of bits overflows a Py_ssize_t");
3249 : 0 : *e = 0;
3250 : 0 : return -1.0;
3251 : : }
3252 : :
3253 : : /* Get a C double from an int object. Rounds to the nearest double,
3254 : : using the round-half-to-even rule in the case of a tie. */
3255 : :
3256 : : double
3257 : 483798 : PyLong_AsDouble(PyObject *v)
3258 : : {
3259 : : Py_ssize_t exponent;
3260 : : double x;
3261 : :
3262 [ - + ]: 483798 : if (v == NULL) {
3263 : 0 : PyErr_BadInternalCall();
3264 : 0 : return -1.0;
3265 : : }
3266 [ - + ]: 483798 : if (!PyLong_Check(v)) {
3267 : 0 : PyErr_SetString(PyExc_TypeError, "an integer is required");
3268 : 0 : return -1.0;
3269 : : }
3270 [ + + ]: 483798 : if (IS_MEDIUM_VALUE(v)) {
3271 : : /* Fast path; single digit long (31 bits) will cast safely
3272 : : to double. This improves performance of FP/long operations
3273 : : by 20%.
3274 : : */
3275 : 481773 : return (double)medium_value((PyLongObject *)v);
3276 : : }
3277 : 2025 : x = _PyLong_Frexp((PyLongObject *)v, &exponent);
3278 [ - + - - : 2025 : if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
+ + ]
3279 : 7 : PyErr_SetString(PyExc_OverflowError,
3280 : : "int too large to convert to float");
3281 : 7 : return -1.0;
3282 : : }
3283 : 2018 : return ldexp(x, (int)exponent);
3284 : : }
3285 : :
3286 : : /* Methods */
3287 : :
3288 : : /* if a < b, return a negative number
3289 : : if a == b, return 0
3290 : : if a > b, return a positive number */
3291 : :
3292 : : static Py_ssize_t
3293 : 320292 : long_compare(PyLongObject *a, PyLongObject *b)
3294 : : {
3295 : 320292 : Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
3296 [ + + ]: 320292 : if (sign == 0) {
3297 [ + + ]: 263173 : Py_ssize_t i = Py_ABS(Py_SIZE(a));
3298 : 263173 : sdigit diff = 0;
3299 [ + + ]: 1146148 : while (--i >= 0) {
3300 : 1077352 : diff = (sdigit) a->long_value.ob_digit[i] - (sdigit) b->long_value.ob_digit[i];
3301 [ + + ]: 1077352 : if (diff) {
3302 : 194377 : break;
3303 : : }
3304 : : }
3305 [ + + ]: 263173 : sign = Py_SIZE(a) < 0 ? -diff : diff;
3306 : : }
3307 : 320292 : return sign;
3308 : : }
3309 : :
3310 : : static PyObject *
3311 : 323165 : long_richcompare(PyObject *self, PyObject *other, int op)
3312 : : {
3313 : : Py_ssize_t result;
3314 [ + - + + ]: 323165 : CHECK_BINOP(self, other);
3315 [ + + ]: 321934 : if (self == other)
3316 : 29428 : result = 0;
3317 : : else
3318 : 292506 : result = long_compare((PyLongObject*)self, (PyLongObject*)other);
3319 [ + + + + : 321934 : Py_RETURN_RICHCOMPARE(result, 0, op);
+ + - + +
+ + + + +
+ + + +
+ ]
3320 : : }
3321 : :
3322 : : static Py_hash_t
3323 : 156692 : long_hash(PyLongObject *v)
3324 : : {
3325 : : Py_uhash_t x;
3326 : : Py_ssize_t i;
3327 : : int sign;
3328 : :
3329 : 156692 : i = Py_SIZE(v);
3330 [ + + + + ]: 156692 : switch(i) {
3331 [ + + ]: 5662 : case -1: return v->long_value.ob_digit[0]==1 ? -2 : -(sdigit)v->long_value.ob_digit[0];
3332 : 39042 : case 0: return 0;
3333 : 66847 : case 1: return v->long_value.ob_digit[0];
3334 : : }
3335 : 45141 : sign = 1;
3336 : 45141 : x = 0;
3337 [ + + ]: 45141 : if (i < 0) {
3338 : 25 : sign = -1;
3339 : 25 : i = -(i);
3340 : : }
3341 [ + + ]: 136092 : while (--i >= 0) {
3342 : : /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3343 : : want to compute x * 2**PyLong_SHIFT + v->long_value.ob_digit[i] modulo
3344 : : _PyHASH_MODULUS.
3345 : :
3346 : : The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3347 : : amounts to a rotation of the bits of x. To see this, write
3348 : :
3349 : : x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3350 : :
3351 : : where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3352 : : PyLong_SHIFT bits of x (those that are shifted out of the
3353 : : original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3354 : : _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3355 : : bits of x, shifted up. Then since 2**_PyHASH_BITS is
3356 : : congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3357 : : congruent to y modulo _PyHASH_MODULUS. So
3358 : :
3359 : : x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3360 : :
3361 : : The right-hand side is just the result of rotating the
3362 : : _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3363 : : not all _PyHASH_BITS bits of x are 1s, the same is true
3364 : : after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3365 : : the reduction of x*2**PyLong_SHIFT modulo
3366 : : _PyHASH_MODULUS. */
3367 : 90951 : x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3368 : 90951 : (x >> (_PyHASH_BITS - PyLong_SHIFT));
3369 : 90951 : x += v->long_value.ob_digit[i];
3370 [ + + ]: 90951 : if (x >= _PyHASH_MODULUS)
3371 : 45 : x -= _PyHASH_MODULUS;
3372 : : }
3373 : 45141 : x = x * sign;
3374 [ - + ]: 45141 : if (x == (Py_uhash_t)-1)
3375 : 0 : x = (Py_uhash_t)-2;
3376 : 45141 : return (Py_hash_t)x;
3377 : : }
3378 : :
3379 : :
3380 : : /* Add the absolute values of two integers. */
3381 : :
3382 : : static PyLongObject *
3383 : 317351 : x_add(PyLongObject *a, PyLongObject *b)
3384 : : {
3385 [ + + + + ]: 317351 : Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
3386 : : PyLongObject *z;
3387 : : Py_ssize_t i;
3388 : 317351 : digit carry = 0;
3389 : :
3390 : : /* Ensure a is the larger of the two: */
3391 [ + + ]: 317351 : if (size_a < size_b) {
3392 : 7785 : { PyLongObject *temp = a; a = b; b = temp; }
3393 : 7785 : { Py_ssize_t size_temp = size_a;
3394 : 7785 : size_a = size_b;
3395 : 7785 : size_b = size_temp; }
3396 : : }
3397 : 317351 : z = _PyLong_New(size_a+1);
3398 [ - + ]: 317351 : if (z == NULL)
3399 : 0 : return NULL;
3400 [ + + ]: 1596788 : for (i = 0; i < size_b; ++i) {
3401 : 1279437 : carry += a->long_value.ob_digit[i] + b->long_value.ob_digit[i];
3402 : 1279437 : z->long_value.ob_digit[i] = carry & PyLong_MASK;
3403 : 1279437 : carry >>= PyLong_SHIFT;
3404 : : }
3405 [ + + ]: 2501505 : for (; i < size_a; ++i) {
3406 : 2184154 : carry += a->long_value.ob_digit[i];
3407 : 2184154 : z->long_value.ob_digit[i] = carry & PyLong_MASK;
3408 : 2184154 : carry >>= PyLong_SHIFT;
3409 : : }
3410 : 317351 : z->long_value.ob_digit[i] = carry;
3411 : 317351 : return long_normalize(z);
3412 : : }
3413 : :
3414 : : /* Subtract the absolute values of two integers. */
3415 : :
3416 : : static PyLongObject *
3417 : 279542 : x_sub(PyLongObject *a, PyLongObject *b)
3418 : : {
3419 [ + + + + ]: 279542 : Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
3420 : : PyLongObject *z;
3421 : : Py_ssize_t i;
3422 : 279542 : int sign = 1;
3423 : 279542 : digit borrow = 0;
3424 : :
3425 : : /* Ensure a is the larger of the two: */
3426 [ + + ]: 279542 : if (size_a < size_b) {
3427 : 113640 : sign = -1;
3428 : 113640 : { PyLongObject *temp = a; a = b; b = temp; }
3429 : 113640 : { Py_ssize_t size_temp = size_a;
3430 : 113640 : size_a = size_b;
3431 : 113640 : size_b = size_temp; }
3432 : : }
3433 [ + + ]: 165902 : else if (size_a == size_b) {
3434 : : /* Find highest digit where a and b differ: */
3435 : 41821 : i = size_a;
3436 [ + + + + ]: 95750 : while (--i >= 0 && a->long_value.ob_digit[i] == b->long_value.ob_digit[i])
3437 : : ;
3438 [ + + ]: 41821 : if (i < 0)
3439 : 8 : return (PyLongObject *)PyLong_FromLong(0);
3440 [ + + ]: 41813 : if (a->long_value.ob_digit[i] < b->long_value.ob_digit[i]) {
3441 : 20235 : sign = -1;
3442 : 20235 : { PyLongObject *temp = a; a = b; b = temp; }
3443 : : }
3444 : 41813 : size_a = size_b = i+1;
3445 : : }
3446 : 279534 : z = _PyLong_New(size_a);
3447 [ - + ]: 279534 : if (z == NULL)
3448 : 0 : return NULL;
3449 [ + + ]: 1478767 : for (i = 0; i < size_b; ++i) {
3450 : : /* The following assumes unsigned arithmetic
3451 : : works module 2**N for some N>PyLong_SHIFT. */
3452 : 1199233 : borrow = a->long_value.ob_digit[i] - b->long_value.ob_digit[i] - borrow;
3453 : 1199233 : z->long_value.ob_digit[i] = borrow & PyLong_MASK;
3454 : 1199233 : borrow >>= PyLong_SHIFT;
3455 : 1199233 : borrow &= 1; /* Keep only one sign bit */
3456 : : }
3457 [ + + ]: 2391548 : for (; i < size_a; ++i) {
3458 : 2112014 : borrow = a->long_value.ob_digit[i] - borrow;
3459 : 2112014 : z->long_value.ob_digit[i] = borrow & PyLong_MASK;
3460 : 2112014 : borrow >>= PyLong_SHIFT;
3461 : 2112014 : borrow &= 1; /* Keep only one sign bit */
3462 : : }
3463 : : assert(borrow == 0);
3464 [ + + ]: 279534 : if (sign < 0) {
3465 : 133875 : Py_SET_SIZE(z, -Py_SIZE(z));
3466 : : }
3467 : 279534 : return maybe_small_long(long_normalize(z));
3468 : : }
3469 : :
3470 : : PyObject *
3471 : 1339425 : _PyLong_Add(PyLongObject *a, PyLongObject *b)
3472 : : {
3473 [ + + + + ]: 1339425 : if (IS_MEDIUM_VALUE(a) && IS_MEDIUM_VALUE(b)) {
3474 : 749795 : return _PyLong_FromSTwoDigits(medium_value(a) + medium_value(b));
3475 : : }
3476 : :
3477 : : PyLongObject *z;
3478 [ + + ]: 589630 : if (Py_SIZE(a) < 0) {
3479 [ + + ]: 258013 : if (Py_SIZE(b) < 0) {
3480 : 124258 : z = x_add(a, b);
3481 [ + - ]: 124258 : if (z != NULL) {
3482 : : /* x_add received at least one multiple-digit int,
3483 : : and thus z must be a multiple-digit int.
3484 : : That also means z is not an element of
3485 : : small_ints, so negating it in-place is safe. */
3486 : : assert(Py_REFCNT(z) == 1);
3487 : 124258 : Py_SET_SIZE(z, -(Py_SIZE(z)));
3488 : : }
3489 : : }
3490 : : else
3491 : 133755 : z = x_sub(b, a);
3492 : : }
3493 : : else {
3494 [ + + ]: 331617 : if (Py_SIZE(b) < 0)
3495 : 141474 : z = x_sub(a, b);
3496 : : else
3497 : 190143 : z = x_add(a, b);
3498 : : }
3499 : 589630 : return (PyObject *)z;
3500 : : }
3501 : :
3502 : : static PyObject *
3503 : 230851 : long_add(PyLongObject *a, PyLongObject *b)
3504 : : {
3505 [ + - + + ]: 230851 : CHECK_BINOP(a, b);
3506 : 29387 : return _PyLong_Add(a, b);
3507 : : }
3508 : :
3509 : : PyObject *
3510 : 1666880 : _PyLong_Subtract(PyLongObject *a, PyLongObject *b)
3511 : : {
3512 : : PyLongObject *z;
3513 : :
3514 [ + + + + ]: 1666880 : if (IS_MEDIUM_VALUE(a) && IS_MEDIUM_VALUE(b)) {
3515 : 1661535 : return _PyLong_FromSTwoDigits(medium_value(a) - medium_value(b));
3516 : : }
3517 [ + + ]: 5345 : if (Py_SIZE(a) < 0) {
3518 [ + + ]: 1052 : if (Py_SIZE(b) < 0) {
3519 : 29 : z = x_sub(b, a);
3520 : : }
3521 : : else {
3522 : 1023 : z = x_add(a, b);
3523 [ + - ]: 1023 : if (z != NULL) {
3524 : : assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
3525 : 1023 : Py_SET_SIZE(z, -(Py_SIZE(z)));
3526 : : }
3527 : : }
3528 : : }
3529 : : else {
3530 [ + + ]: 4293 : if (Py_SIZE(b) < 0)
3531 : 9 : z = x_add(a, b);
3532 : : else
3533 : 4284 : z = x_sub(a, b);
3534 : : }
3535 : 5345 : return (PyObject *)z;
3536 : : }
3537 : :
3538 : : static PyObject *
3539 : 4605 : long_sub(PyLongObject *a, PyLongObject *b)
3540 : : {
3541 [ + - + + ]: 4605 : CHECK_BINOP(a, b);
3542 : 4603 : return _PyLong_Subtract(a, b);
3543 : : }
3544 : :
3545 : : /* Grade school multiplication, ignoring the signs.
3546 : : * Returns the absolute value of the product, or NULL if error.
3547 : : */
3548 : : static PyLongObject *
3549 : 1032165 : x_mul(PyLongObject *a, PyLongObject *b)
3550 : : {
3551 : : PyLongObject *z;
3552 [ + + ]: 1032165 : Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3553 [ + + ]: 1032165 : Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
3554 : : Py_ssize_t i;
3555 : :
3556 : 1032165 : z = _PyLong_New(size_a + size_b);
3557 [ - + ]: 1032165 : if (z == NULL)
3558 : 0 : return NULL;
3559 : :
3560 : 1032165 : memset(z->long_value.ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3561 [ + + ]: 1032165 : if (a == b) {
3562 : : /* Efficient squaring per HAC, Algorithm 14.16:
3563 : : * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3564 : : * Gives slightly less than a 2x speedup when a == b,
3565 : : * via exploiting that each entry in the multiplication
3566 : : * pyramid appears twice (except for the size_a squares).
3567 : : */
3568 : 39749 : digit *paend = a->long_value.ob_digit + size_a;
3569 [ + + ]: 146838 : for (i = 0; i < size_a; ++i) {
3570 : : twodigits carry;
3571 : 107089 : twodigits f = a->long_value.ob_digit[i];
3572 : 107089 : digit *pz = z->long_value.ob_digit + (i << 1);
3573 : 107089 : digit *pa = a->long_value.ob_digit + i + 1;
3574 : :
3575 [ - + ]: 107089 : SIGCHECK({
3576 : : Py_DECREF(z);
3577 : : return NULL;
3578 : : });
3579 : :
3580 : 107089 : carry = *pz + f * f;
3581 : 107089 : *pz++ = (digit)(carry & PyLong_MASK);
3582 : 107089 : carry >>= PyLong_SHIFT;
3583 : : assert(carry <= PyLong_MASK);
3584 : :
3585 : : /* Now f is added in twice in each column of the
3586 : : * pyramid it appears. Same as adding f<<1 once.
3587 : : */
3588 : 107089 : f <<= 1;
3589 [ + + ]: 399395 : while (pa < paend) {
3590 : 292306 : carry += *pz + *pa++ * f;
3591 : 292306 : *pz++ = (digit)(carry & PyLong_MASK);
3592 : 292306 : carry >>= PyLong_SHIFT;
3593 : : assert(carry <= (PyLong_MASK << 1));
3594 : : }
3595 [ + + ]: 107089 : if (carry) {
3596 : : /* See comment below. pz points at the highest possible
3597 : : * carry position from the last outer loop iteration, so
3598 : : * *pz is at most 1.
3599 : : */
3600 : : assert(*pz <= 1);
3601 : 45478 : carry += *pz;
3602 : 45478 : *pz = (digit)(carry & PyLong_MASK);
3603 : 45478 : carry >>= PyLong_SHIFT;
3604 [ + + ]: 45478 : if (carry) {
3605 : : /* If there's still a carry, it must be into a position
3606 : : * that still holds a 0. Where the base
3607 : : ^ B is 1 << PyLong_SHIFT, the last add was of a carry no
3608 : : * more than 2*B - 2 to a stored digit no more than 1.
3609 : : * So the sum was no more than 2*B - 1, so the current
3610 : : * carry no more than floor((2*B - 1)/B) = 1.
3611 : : */
3612 : : assert(carry == 1);
3613 : : assert(pz[1] == 0);
3614 : 603 : pz[1] = (digit)carry;
3615 : : }
3616 : : }
3617 : : }
3618 : : }
3619 : : else { /* a is not the same as b -- gradeschool int mult */
3620 [ + + ]: 4839980 : for (i = 0; i < size_a; ++i) {
3621 : 3847564 : twodigits carry = 0;
3622 : 3847564 : twodigits f = a->long_value.ob_digit[i];
3623 : 3847564 : digit *pz = z->long_value.ob_digit + i;
3624 : 3847564 : digit *pb = b->long_value.ob_digit;
3625 : 3847564 : digit *pbend = b->long_value.ob_digit + size_b;
3626 : :
3627 [ - + ]: 3847564 : SIGCHECK({
3628 : : Py_DECREF(z);
3629 : : return NULL;
3630 : : });
3631 : :
3632 [ + + ]: 165274438 : while (pb < pbend) {
3633 : 161426874 : carry += *pz + *pb++ * f;
3634 : 161426874 : *pz++ = (digit)(carry & PyLong_MASK);
3635 : 161426874 : carry >>= PyLong_SHIFT;
3636 : : assert(carry <= PyLong_MASK);
3637 : : }
3638 [ + + ]: 3847564 : if (carry)
3639 : 3103317 : *pz += (digit)(carry & PyLong_MASK);
3640 : : assert((carry >> PyLong_SHIFT) == 0);
3641 : : }
3642 : : }
3643 : 1032165 : return long_normalize(z);
3644 : : }
3645 : :
3646 : : /* A helper for Karatsuba multiplication (k_mul).
3647 : : Takes an int "n" and an integer "size" representing the place to
3648 : : split, and sets low and high such that abs(n) == (high << size) + low,
3649 : : viewing the shift as being by digits. The sign bit is ignored, and
3650 : : the return values are >= 0.
3651 : : Returns 0 on success, -1 on failure.
3652 : : */
3653 : : static int
3654 : 1918 : kmul_split(PyLongObject *n,
3655 : : Py_ssize_t size,
3656 : : PyLongObject **high,
3657 : : PyLongObject **low)
3658 : : {
3659 : : PyLongObject *hi, *lo;
3660 : : Py_ssize_t size_lo, size_hi;
3661 [ - + ]: 1918 : const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
3662 : :
3663 : 1918 : size_lo = Py_MIN(size_n, size);
3664 : 1918 : size_hi = size_n - size_lo;
3665 : :
3666 [ - + ]: 1918 : if ((hi = _PyLong_New(size_hi)) == NULL)
3667 : 0 : return -1;
3668 [ - + ]: 1918 : if ((lo = _PyLong_New(size_lo)) == NULL) {
3669 : 0 : Py_DECREF(hi);
3670 : 0 : return -1;
3671 : : }
3672 : :
3673 : 1918 : memcpy(lo->long_value.ob_digit, n->long_value.ob_digit, size_lo * sizeof(digit));
3674 : 1918 : memcpy(hi->long_value.ob_digit, n->long_value.ob_digit + size_lo, size_hi * sizeof(digit));
3675 : :
3676 : 1918 : *high = long_normalize(hi);
3677 : 1918 : *low = long_normalize(lo);
3678 : 1918 : return 0;
3679 : : }
3680 : :
3681 : : static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3682 : :
3683 : : /* Karatsuba multiplication. Ignores the input signs, and returns the
3684 : : * absolute value of the product (or NULL if error).
3685 : : * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3686 : : */
3687 : : static PyLongObject *
3688 : 1036857 : k_mul(PyLongObject *a, PyLongObject *b)
3689 : : {
3690 [ + + ]: 1036857 : Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3691 [ + + ]: 1036857 : Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
3692 : 1036857 : PyLongObject *ah = NULL;
3693 : 1036857 : PyLongObject *al = NULL;
3694 : 1036857 : PyLongObject *bh = NULL;
3695 : 1036857 : PyLongObject *bl = NULL;
3696 : 1036857 : PyLongObject *ret = NULL;
3697 : : PyLongObject *t1, *t2, *t3;
3698 : : Py_ssize_t shift; /* the number of digits we split off */
3699 : : Py_ssize_t i;
3700 : :
3701 : : /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3702 : : * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3703 : : * Then the original product is
3704 : : * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3705 : : * By picking X to be a power of 2, "*X" is just shifting, and it's
3706 : : * been reduced to 3 multiplies on numbers half the size.
3707 : : */
3708 : :
3709 : : /* We want to split based on the larger number; fiddle so that b
3710 : : * is largest.
3711 : : */
3712 [ + + ]: 1036857 : if (asize > bsize) {
3713 : 156788 : t1 = a;
3714 : 156788 : a = b;
3715 : 156788 : b = t1;
3716 : :
3717 : 156788 : i = asize;
3718 : 156788 : asize = bsize;
3719 : 156788 : bsize = i;
3720 : : }
3721 : :
3722 : : /* Use gradeschool math when either number is too small. */
3723 [ + + ]: 1036857 : i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3724 [ + + ]: 1036857 : if (asize <= i) {
3725 [ + + ]: 1035895 : if (asize == 0)
3726 : 3730 : return (PyLongObject *)PyLong_FromLong(0);
3727 : : else
3728 : 1032165 : return x_mul(a, b);
3729 : : }
3730 : :
3731 : : /* If a is small compared to b, splitting on b gives a degenerate
3732 : : * case with ah==0, and Karatsuba may be (even much) less efficient
3733 : : * than "grade school" then. However, we can still win, by viewing
3734 : : * b as a string of "big digits", each of width a->ob_size. That
3735 : : * leads to a sequence of balanced calls to k_mul.
3736 : : */
3737 [ - + ]: 962 : if (2 * asize <= bsize)
3738 : 0 : return k_lopsided_mul(a, b);
3739 : :
3740 : : /* Split a & b into hi & lo pieces. */
3741 : 962 : shift = bsize >> 1;
3742 [ - + ]: 962 : if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3743 : : assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
3744 : :
3745 [ + + ]: 962 : if (a == b) {
3746 : 6 : bh = (PyLongObject*)Py_NewRef(ah);
3747 : 6 : bl = (PyLongObject*)Py_NewRef(al);
3748 : : }
3749 [ - + ]: 956 : else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
3750 : :
3751 : : /* The plan:
3752 : : * 1. Allocate result space (asize + bsize digits: that's always
3753 : : * enough).
3754 : : * 2. Compute ah*bh, and copy into result at 2*shift.
3755 : : * 3. Compute al*bl, and copy into result at 0. Note that this
3756 : : * can't overlap with #2.
3757 : : * 4. Subtract al*bl from the result, starting at shift. This may
3758 : : * underflow (borrow out of the high digit), but we don't care:
3759 : : * we're effectively doing unsigned arithmetic mod
3760 : : * BASE**(sizea + sizeb), and so long as the *final* result fits,
3761 : : * borrows and carries out of the high digit can be ignored.
3762 : : * 5. Subtract ah*bh from the result, starting at shift.
3763 : : * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3764 : : * at shift.
3765 : : */
3766 : :
3767 : : /* 1. Allocate result space. */
3768 : 962 : ret = _PyLong_New(asize + bsize);
3769 [ - + ]: 962 : if (ret == NULL) goto fail;
3770 : : #ifdef Py_DEBUG
3771 : : /* Fill with trash, to catch reference to uninitialized digits. */
3772 : : memset(ret->long_value.ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
3773 : : #endif
3774 : :
3775 : : /* 2. t1 <- ah*bh, and copy into high digits of result. */
3776 [ - + ]: 962 : if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3777 : : assert(Py_SIZE(t1) >= 0);
3778 : : assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3779 : 962 : memcpy(ret->long_value.ob_digit + 2*shift, t1->long_value.ob_digit,
3780 : 962 : Py_SIZE(t1) * sizeof(digit));
3781 : :
3782 : : /* Zero-out the digits higher than the ah*bh copy. */
3783 : 962 : i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3784 [ + + ]: 962 : if (i)
3785 : 456 : memset(ret->long_value.ob_digit + 2*shift + Py_SIZE(t1), 0,
3786 : : i * sizeof(digit));
3787 : :
3788 : : /* 3. t2 <- al*bl, and copy into the low digits. */
3789 [ - + ]: 962 : if ((t2 = k_mul(al, bl)) == NULL) {
3790 : 0 : Py_DECREF(t1);
3791 : 0 : goto fail;
3792 : : }
3793 : : assert(Py_SIZE(t2) >= 0);
3794 : : assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3795 : 962 : memcpy(ret->long_value.ob_digit, t2->long_value.ob_digit, Py_SIZE(t2) * sizeof(digit));
3796 : :
3797 : : /* Zero out remaining digits. */
3798 : 962 : i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3799 [ - + ]: 962 : if (i)
3800 : 0 : memset(ret->long_value.ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
3801 : :
3802 : : /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3803 : : * because it's fresher in cache.
3804 : : */
3805 : 962 : i = Py_SIZE(ret) - shift; /* # digits after shift */
3806 : 962 : (void)v_isub(ret->long_value.ob_digit + shift, i, t2->long_value.ob_digit, Py_SIZE(t2));
3807 : 962 : _Py_DECREF_INT(t2);
3808 : :
3809 : 962 : (void)v_isub(ret->long_value.ob_digit + shift, i, t1->long_value.ob_digit, Py_SIZE(t1));
3810 : 962 : _Py_DECREF_INT(t1);
3811 : :
3812 : : /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3813 [ - + ]: 962 : if ((t1 = x_add(ah, al)) == NULL) goto fail;
3814 : 962 : _Py_DECREF_INT(ah);
3815 : 962 : _Py_DECREF_INT(al);
3816 : 962 : ah = al = NULL;
3817 : :
3818 [ + + ]: 962 : if (a == b) {
3819 : 6 : t2 = (PyLongObject*)Py_NewRef(t1);
3820 : : }
3821 [ - + ]: 956 : else if ((t2 = x_add(bh, bl)) == NULL) {
3822 : 0 : Py_DECREF(t1);
3823 : 0 : goto fail;
3824 : : }
3825 : 962 : _Py_DECREF_INT(bh);
3826 : 962 : _Py_DECREF_INT(bl);
3827 : 962 : bh = bl = NULL;
3828 : :
3829 : 962 : t3 = k_mul(t1, t2);
3830 : 962 : _Py_DECREF_INT(t1);
3831 : 962 : _Py_DECREF_INT(t2);
3832 [ - + ]: 962 : if (t3 == NULL) goto fail;
3833 : : assert(Py_SIZE(t3) >= 0);
3834 : :
3835 : : /* Add t3. It's not obvious why we can't run out of room here.
3836 : : * See the (*) comment after this function.
3837 : : */
3838 : 962 : (void)v_iadd(ret->long_value.ob_digit + shift, i, t3->long_value.ob_digit, Py_SIZE(t3));
3839 : 962 : _Py_DECREF_INT(t3);
3840 : :
3841 : 962 : return long_normalize(ret);
3842 : :
3843 : 0 : fail:
3844 : 0 : Py_XDECREF(ret);
3845 : 0 : Py_XDECREF(ah);
3846 : 0 : Py_XDECREF(al);
3847 : 0 : Py_XDECREF(bh);
3848 : 0 : Py_XDECREF(bl);
3849 : 0 : return NULL;
3850 : : }
3851 : :
3852 : : /* (*) Why adding t3 can't "run out of room" above.
3853 : :
3854 : : Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3855 : : to start with:
3856 : :
3857 : : 1. For any integer i, i = c(i/2) + f(i/2). In particular,
3858 : : bsize = c(bsize/2) + f(bsize/2).
3859 : : 2. shift = f(bsize/2)
3860 : : 3. asize <= bsize
3861 : : 4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3862 : : routine, so asize > bsize/2 >= f(bsize/2) in this routine.
3863 : :
3864 : : We allocated asize + bsize result digits, and add t3 into them at an offset
3865 : : of shift. This leaves asize+bsize-shift allocated digit positions for t3
3866 : : to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3867 : : asize + c(bsize/2) available digit positions.
3868 : :
3869 : : bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3870 : : at most c(bsize/2) digits + 1 bit.
3871 : :
3872 : : If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3873 : : digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3874 : : most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
3875 : :
3876 : : The product (ah+al)*(bh+bl) therefore has at most
3877 : :
3878 : : c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
3879 : :
3880 : : and we have asize + c(bsize/2) available digit positions. We need to show
3881 : : this is always enough. An instance of c(bsize/2) cancels out in both, so
3882 : : the question reduces to whether asize digits is enough to hold
3883 : : (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3884 : : then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3885 : : asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
3886 : : digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
3887 : : asize == bsize, then we're asking whether bsize digits is enough to hold
3888 : : c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3889 : : is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3890 : : bsize >= KARATSUBA_CUTOFF >= 2.
3891 : :
3892 : : Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3893 : : clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3894 : : ah*bh and al*bl too.
3895 : : */
3896 : :
3897 : : /* b has at least twice the digits of a, and a is big enough that Karatsuba
3898 : : * would pay off *if* the inputs had balanced sizes. View b as a sequence
3899 : : * of slices, each with a->ob_size digits, and multiply the slices by a,
3900 : : * one at a time. This gives k_mul balanced inputs to work with, and is
3901 : : * also cache-friendly (we compute one double-width slice of the result
3902 : : * at a time, then move on, never backtracking except for the helpful
3903 : : * single-width slice overlap between successive partial sums).
3904 : : */
3905 : : static PyLongObject *
3906 : 0 : k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3907 : : {
3908 [ # # ]: 0 : const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3909 [ # # ]: 0 : Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
3910 : : Py_ssize_t nbdone; /* # of b digits already multiplied */
3911 : : PyLongObject *ret;
3912 : 0 : PyLongObject *bslice = NULL;
3913 : :
3914 : : assert(asize > KARATSUBA_CUTOFF);
3915 : : assert(2 * asize <= bsize);
3916 : :
3917 : : /* Allocate result space, and zero it out. */
3918 : 0 : ret = _PyLong_New(asize + bsize);
3919 [ # # ]: 0 : if (ret == NULL)
3920 : 0 : return NULL;
3921 : 0 : memset(ret->long_value.ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
3922 : :
3923 : : /* Successive slices of b are copied into bslice. */
3924 : 0 : bslice = _PyLong_New(asize);
3925 [ # # ]: 0 : if (bslice == NULL)
3926 : 0 : goto fail;
3927 : :
3928 : 0 : nbdone = 0;
3929 [ # # ]: 0 : while (bsize > 0) {
3930 : : PyLongObject *product;
3931 : 0 : const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
3932 : :
3933 : : /* Multiply the next slice of b by a. */
3934 : 0 : memcpy(bslice->long_value.ob_digit, b->long_value.ob_digit + nbdone,
3935 : : nbtouse * sizeof(digit));
3936 : 0 : Py_SET_SIZE(bslice, nbtouse);
3937 : 0 : product = k_mul(a, bslice);
3938 [ # # ]: 0 : if (product == NULL)
3939 : 0 : goto fail;
3940 : :
3941 : : /* Add into result. */
3942 : 0 : (void)v_iadd(ret->long_value.ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3943 : 0 : product->long_value.ob_digit, Py_SIZE(product));
3944 : 0 : _Py_DECREF_INT(product);
3945 : :
3946 : 0 : bsize -= nbtouse;
3947 : 0 : nbdone += nbtouse;
3948 : : }
3949 : :
3950 : 0 : _Py_DECREF_INT(bslice);
3951 : 0 : return long_normalize(ret);
3952 : :
3953 : 0 : fail:
3954 : 0 : Py_DECREF(ret);
3955 : 0 : Py_XDECREF(bslice);
3956 : 0 : return NULL;
3957 : : }
3958 : :
3959 : : PyObject *
3960 : 1665333 : _PyLong_Multiply(PyLongObject *a, PyLongObject *b)
3961 : : {
3962 : : PyLongObject *z;
3963 : :
3964 : : /* fast path for single-digit multiplication */
3965 [ + + + + ]: 1665333 : if (IS_MEDIUM_VALUE(a) && IS_MEDIUM_VALUE(b)) {
3966 : 631362 : stwodigits v = medium_value(a) * medium_value(b);
3967 : 631362 : return _PyLong_FromSTwoDigits(v);
3968 : : }
3969 : :
3970 : 1033971 : z = k_mul(a, b);
3971 : : /* Negate if exactly one of the inputs is negative. */
3972 [ + + + - ]: 1033971 : if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3973 : 10510 : _PyLong_Negate(&z);
3974 [ - + ]: 10510 : if (z == NULL)
3975 : 0 : return NULL;
3976 : : }
3977 : 1033971 : return (PyObject *)z;
3978 : : }
3979 : :
3980 : : static PyObject *
3981 : 1379792 : long_mul(PyLongObject *a, PyLongObject *b)
3982 : : {
3983 [ + + + + ]: 1379792 : CHECK_BINOP(a, b);
3984 : 1226058 : return _PyLong_Multiply(a, b);
3985 : : }
3986 : :
3987 : : /* Fast modulo division for single-digit longs. */
3988 : : static PyObject *
3989 : 87 : fast_mod(PyLongObject *a, PyLongObject *b)
3990 : : {
3991 : 87 : sdigit left = a->long_value.ob_digit[0];
3992 : 87 : sdigit right = b->long_value.ob_digit[0];
3993 : : sdigit mod;
3994 : :
3995 : : assert(Py_ABS(Py_SIZE(a)) == 1);
3996 : : assert(Py_ABS(Py_SIZE(b)) == 1);
3997 : :
3998 [ + + ]: 87 : if (Py_SIZE(a) == Py_SIZE(b)) {
3999 : : /* 'a' and 'b' have the same sign. */
4000 : 81 : mod = left % right;
4001 : : }
4002 : : else {
4003 : : /* Either 'a' or 'b' is negative. */
4004 : 6 : mod = right - 1 - (left - 1) % right;
4005 : : }
4006 : :
4007 : 87 : return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
4008 : : }
4009 : :
4010 : : /* Fast floor division for single-digit longs. */
4011 : : static PyObject *
4012 : 33714 : fast_floor_div(PyLongObject *a, PyLongObject *b)
4013 : : {
4014 : 33714 : sdigit left = a->long_value.ob_digit[0];
4015 : 33714 : sdigit right = b->long_value.ob_digit[0];
4016 : : sdigit div;
4017 : :
4018 : : assert(Py_ABS(Py_SIZE(a)) == 1);
4019 : : assert(Py_ABS(Py_SIZE(b)) == 1);
4020 : :
4021 [ + + ]: 33714 : if (Py_SIZE(a) == Py_SIZE(b)) {
4022 : : /* 'a' and 'b' have the same sign. */
4023 : 23269 : div = left / right;
4024 : : }
4025 : : else {
4026 : : /* Either 'a' or 'b' is negative. */
4027 : 10445 : div = -1 - (left - 1) / right;
4028 : : }
4029 : :
4030 : 33714 : return PyLong_FromLong(div);
4031 : : }
4032 : :
4033 : : #ifdef WITH_PYLONG_MODULE
4034 : : /* asymptotically faster divmod, using _pylong.py */
4035 : : static int
4036 : 0 : pylong_int_divmod(PyLongObject *v, PyLongObject *w,
4037 : : PyLongObject **pdiv, PyLongObject **pmod)
4038 : : {
4039 : 0 : PyObject *mod = PyImport_ImportModule("_pylong");
4040 [ # # ]: 0 : if (mod == NULL) {
4041 : 0 : return -1;
4042 : : }
4043 : 0 : PyObject *result = PyObject_CallMethod(mod, "int_divmod", "OO", v, w);
4044 : 0 : Py_DECREF(mod);
4045 [ # # ]: 0 : if (result == NULL) {
4046 : 0 : return -1;
4047 : : }
4048 [ # # ]: 0 : if (!PyTuple_Check(result)) {
4049 : 0 : Py_DECREF(result);
4050 : 0 : PyErr_SetString(PyExc_ValueError,
4051 : : "tuple is required from int_divmod()");
4052 : 0 : return -1;
4053 : : }
4054 : 0 : PyObject *q = PyTuple_GET_ITEM(result, 0);
4055 : 0 : PyObject *r = PyTuple_GET_ITEM(result, 1);
4056 [ # # # # ]: 0 : if (!PyLong_Check(q) || !PyLong_Check(r)) {
4057 : 0 : Py_DECREF(result);
4058 : 0 : PyErr_SetString(PyExc_ValueError,
4059 : : "tuple of int is required from int_divmod()");
4060 : 0 : return -1;
4061 : : }
4062 [ # # ]: 0 : if (pdiv != NULL) {
4063 : 0 : *pdiv = (PyLongObject *)Py_NewRef(q);
4064 : : }
4065 [ # # ]: 0 : if (pmod != NULL) {
4066 : 0 : *pmod = (PyLongObject *)Py_NewRef(r);
4067 : : }
4068 : 0 : Py_DECREF(result);
4069 : 0 : return 0;
4070 : : }
4071 : : #endif /* WITH_PYLONG_MODULE */
4072 : :
4073 : : /* The / and % operators are now defined in terms of divmod().
4074 : : The expression a mod b has the value a - b*floor(a/b).
4075 : : The long_divrem function gives the remainder after division of
4076 : : |a| by |b|, with the sign of a. This is also expressed
4077 : : as a - b*trunc(a/b), if trunc truncates towards zero.
4078 : : Some examples:
4079 : : a b a rem b a mod b
4080 : : 13 10 3 3
4081 : : -13 10 -3 7
4082 : : 13 -10 3 -7
4083 : : -13 -10 -3 -3
4084 : : So, to get from rem to mod, we have to add b if a and b
4085 : : have different signs. We then subtract one from the 'div'
4086 : : part of the outcome to keep the invariant intact. */
4087 : :
4088 : : /* Compute
4089 : : * *pdiv, *pmod = divmod(v, w)
4090 : : * NULL can be passed for pdiv or pmod, in which case that part of
4091 : : * the result is simply thrown away. The caller owns a reference to
4092 : : * each of these it requests (does not pass NULL for).
4093 : : */
4094 : : static int
4095 : 92284 : l_divmod(PyLongObject *v, PyLongObject *w,
4096 : : PyLongObject **pdiv, PyLongObject **pmod)
4097 : : {
4098 : : PyLongObject *div, *mod;
4099 : :
4100 [ + + + + : 92284 : if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
- + + + ]
4101 : : /* Fast path for single-digit longs */
4102 : 87 : div = NULL;
4103 [ + - ]: 87 : if (pdiv != NULL) {
4104 : 87 : div = (PyLongObject *)fast_floor_div(v, w);
4105 [ - + ]: 87 : if (div == NULL) {
4106 : 0 : return -1;
4107 : : }
4108 : : }
4109 [ + - ]: 87 : if (pmod != NULL) {
4110 : 87 : mod = (PyLongObject *)fast_mod(v, w);
4111 [ - + ]: 87 : if (mod == NULL) {
4112 : 0 : Py_XDECREF(div);
4113 : 0 : return -1;
4114 : : }
4115 : 87 : *pmod = mod;
4116 : : }
4117 [ + - ]: 87 : if (pdiv != NULL) {
4118 : : /* We only want to set `*pdiv` when `*pmod` is
4119 : : set successfully. */
4120 : 87 : *pdiv = div;
4121 : : }
4122 : 87 : return 0;
4123 : : }
4124 : : #if WITH_PYLONG_MODULE
4125 [ + + ]: 92197 : Py_ssize_t size_v = Py_ABS(Py_SIZE(v)); /* digits in numerator */
4126 [ - + ]: 92197 : Py_ssize_t size_w = Py_ABS(Py_SIZE(w)); /* digits in denominator */
4127 [ - + - - ]: 92197 : if (size_w > 300 && (size_v - size_w) > 150) {
4128 : : /* Switch to _pylong.int_divmod(). If the quotient is small then
4129 : : "schoolbook" division is linear-time so don't use in that case.
4130 : : These limits are empirically determined and should be slightly
4131 : : conservative so that _pylong is used in cases it is likely
4132 : : to be faster. See Tools/scripts/divmod_threshold.py. */
4133 : 0 : return pylong_int_divmod(v, w, pdiv, pmod);
4134 : : }
4135 : : #endif
4136 [ - + ]: 92197 : if (long_divrem(v, w, &div, &mod) < 0)
4137 : 0 : return -1;
4138 [ + + - + : 183372 : if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
+ + ]
4139 [ - + ]: 104593 : (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
4140 : : PyLongObject *temp;
4141 : 1022 : temp = (PyLongObject *) long_add(mod, w);
4142 : 1022 : Py_SETREF(mod, temp);
4143 [ - + ]: 1022 : if (mod == NULL) {
4144 : 0 : Py_DECREF(div);
4145 : 0 : return -1;
4146 : : }
4147 : 1022 : temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_GetOne());
4148 [ - + ]: 1022 : if (temp == NULL) {
4149 : 0 : Py_DECREF(mod);
4150 : 0 : Py_DECREF(div);
4151 : 0 : return -1;
4152 : : }
4153 : 1022 : Py_SETREF(div, temp);
4154 : : }
4155 [ + - ]: 92197 : if (pdiv != NULL)
4156 : 92197 : *pdiv = div;
4157 : : else
4158 : 0 : Py_DECREF(div);
4159 : :
4160 [ + + ]: 92197 : if (pmod != NULL)
4161 : 61 : *pmod = mod;
4162 : : else
4163 : 92136 : Py_DECREF(mod);
4164 : :
4165 : 92197 : return 0;
4166 : : }
4167 : :
4168 : : /* Compute
4169 : : * *pmod = v % w
4170 : : * pmod cannot be NULL. The caller owns a reference to pmod.
4171 : : */
4172 : : static int
4173 : 27184 : l_mod(PyLongObject *v, PyLongObject *w, PyLongObject **pmod)
4174 : : {
4175 : : PyLongObject *mod;
4176 : :
4177 : : assert(pmod);
4178 [ - + - + : 27184 : if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
- - - - ]
4179 : : /* Fast path for single-digit longs */
4180 : 0 : *pmod = (PyLongObject *)fast_mod(v, w);
4181 : 0 : return -(*pmod == NULL);
4182 : : }
4183 [ - + ]: 27184 : if (long_rem(v, w, &mod) < 0)
4184 : 0 : return -1;
4185 [ - + - - : 54368 : if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
+ + ]
4186 [ - + ]: 34425 : (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
4187 : : PyLongObject *temp;
4188 : 0 : temp = (PyLongObject *) long_add(mod, w);
4189 : 0 : Py_SETREF(mod, temp);
4190 [ # # ]: 0 : if (mod == NULL)
4191 : 0 : return -1;
4192 : : }
4193 : 27184 : *pmod = mod;
4194 : :
4195 : 27184 : return 0;
4196 : : }
4197 : :
4198 : : static PyObject *
4199 : 125763 : long_div(PyObject *a, PyObject *b)
4200 : : {
4201 : : PyLongObject *div;
4202 : :
4203 [ + - - + ]: 125763 : CHECK_BINOP(a, b);
4204 : :
4205 [ + + + + : 125763 : if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
- + + - ]
4206 : 33627 : return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
4207 : : }
4208 : :
4209 [ - + ]: 92136 : if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
4210 : 0 : div = NULL;
4211 : 92136 : return (PyObject *)div;
4212 : : }
4213 : :
4214 : : /* PyLong/PyLong -> float, with correctly rounded result. */
4215 : :
4216 : : #define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
4217 : : #define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
4218 : :
4219 : : static PyObject *
4220 : 27 : long_true_divide(PyObject *v, PyObject *w)
4221 : : {
4222 : : PyLongObject *a, *b, *x;
4223 : : Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
4224 : : digit mask, low;
4225 : : int inexact, negate, a_is_small, b_is_small;
4226 : : double dx, result;
4227 : :
4228 [ + - + + ]: 27 : CHECK_BINOP(v, w);
4229 : 25 : a = (PyLongObject *)v;
4230 : 25 : b = (PyLongObject *)w;
4231 : :
4232 : : /*
4233 : : Method in a nutshell:
4234 : :
4235 : : 0. reduce to case a, b > 0; filter out obvious underflow/overflow
4236 : : 1. choose a suitable integer 'shift'
4237 : : 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
4238 : : 3. adjust x for correct rounding
4239 : : 4. convert x to a double dx with the same value
4240 : : 5. return ldexp(dx, shift).
4241 : :
4242 : : In more detail:
4243 : :
4244 : : 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
4245 : : returns either 0.0 or -0.0, depending on the sign of b. For a and
4246 : : b both nonzero, ignore signs of a and b, and add the sign back in
4247 : : at the end. Now write a_bits and b_bits for the bit lengths of a
4248 : : and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
4249 : : for b). Then
4250 : :
4251 : : 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
4252 : :
4253 : : So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
4254 : : so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
4255 : : DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
4256 : : the way, we can assume that
4257 : :
4258 : : DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
4259 : :
4260 : : 1. The integer 'shift' is chosen so that x has the right number of
4261 : : bits for a double, plus two or three extra bits that will be used
4262 : : in the rounding decisions. Writing a_bits and b_bits for the
4263 : : number of significant bits in a and b respectively, a
4264 : : straightforward formula for shift is:
4265 : :
4266 : : shift = a_bits - b_bits - DBL_MANT_DIG - 2
4267 : :
4268 : : This is fine in the usual case, but if a/b is smaller than the
4269 : : smallest normal float then it can lead to double rounding on an
4270 : : IEEE 754 platform, giving incorrectly rounded results. So we
4271 : : adjust the formula slightly. The actual formula used is:
4272 : :
4273 : : shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
4274 : :
4275 : : 2. The quantity x is computed by first shifting a (left -shift bits
4276 : : if shift <= 0, right shift bits if shift > 0) and then dividing by
4277 : : b. For both the shift and the division, we keep track of whether
4278 : : the result is inexact, in a flag 'inexact'; this information is
4279 : : needed at the rounding stage.
4280 : :
4281 : : With the choice of shift above, together with our assumption that
4282 : : a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
4283 : : that x >= 1.
4284 : :
4285 : : 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
4286 : : this with an exactly representable float of the form
4287 : :
4288 : : round(x/2**extra_bits) * 2**(extra_bits+shift).
4289 : :
4290 : : For float representability, we need x/2**extra_bits <
4291 : : 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
4292 : : DBL_MANT_DIG. This translates to the condition:
4293 : :
4294 : : extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
4295 : :
4296 : : To round, we just modify the bottom digit of x in-place; this can
4297 : : end up giving a digit with value > PyLONG_MASK, but that's not a
4298 : : problem since digits can hold values up to 2*PyLONG_MASK+1.
4299 : :
4300 : : With the original choices for shift above, extra_bits will always
4301 : : be 2 or 3. Then rounding under the round-half-to-even rule, we
4302 : : round up iff the most significant of the extra bits is 1, and
4303 : : either: (a) the computation of x in step 2 had an inexact result,
4304 : : or (b) at least one other of the extra bits is 1, or (c) the least
4305 : : significant bit of x (above those to be rounded) is 1.
4306 : :
4307 : : 4. Conversion to a double is straightforward; all floating-point
4308 : : operations involved in the conversion are exact, so there's no
4309 : : danger of rounding errors.
4310 : :
4311 : : 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
4312 : : The result will always be exactly representable as a double, except
4313 : : in the case that it overflows. To avoid dependence on the exact
4314 : : behaviour of ldexp on overflow, we check for overflow before
4315 : : applying ldexp. The result of ldexp is adjusted for sign before
4316 : : returning.
4317 : : */
4318 : :
4319 : : /* Reduce to case where a and b are both positive. */
4320 [ + + ]: 25 : a_size = Py_ABS(Py_SIZE(a));
4321 [ - + ]: 25 : b_size = Py_ABS(Py_SIZE(b));
4322 : 25 : negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
4323 [ + + ]: 25 : if (b_size == 0) {
4324 : 1 : PyErr_SetString(PyExc_ZeroDivisionError,
4325 : : "division by zero");
4326 : 1 : goto error;
4327 : : }
4328 [ - + ]: 24 : if (a_size == 0)
4329 : 0 : goto underflow_or_zero;
4330 : :
4331 : : /* Fast path for a and b small (exactly representable in a double).
4332 : : Relies on floating-point division being correctly rounded; results
4333 : : may be subject to double rounding on x86 machines that operate with
4334 : : the x87 FPU set to 64-bit precision. */
4335 [ - + - - ]: 24 : a_is_small = a_size <= MANT_DIG_DIGITS ||
4336 : 0 : (a_size == MANT_DIG_DIGITS+1 &&
4337 [ # # ]: 0 : a->long_value.ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
4338 [ + + - + ]: 24 : b_is_small = b_size <= MANT_DIG_DIGITS ||
4339 : 0 : (b_size == MANT_DIG_DIGITS+1 &&
4340 [ # # ]: 0 : b->long_value.ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
4341 [ + - + + ]: 24 : if (a_is_small && b_is_small) {
4342 : : double da, db;
4343 : 20 : da = a->long_value.ob_digit[--a_size];
4344 [ - + ]: 20 : while (a_size > 0)
4345 : 0 : da = da * PyLong_BASE + a->long_value.ob_digit[--a_size];
4346 : 20 : db = b->long_value.ob_digit[--b_size];
4347 [ - + ]: 20 : while (b_size > 0)
4348 : 0 : db = db * PyLong_BASE + b->long_value.ob_digit[--b_size];
4349 : 20 : result = da / db;
4350 : 20 : goto success;
4351 : : }
4352 : :
4353 : : /* Catch obvious cases of underflow and overflow */
4354 : 4 : diff = a_size - b_size;
4355 [ - + ]: 4 : if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
4356 : : /* Extreme overflow */
4357 : 0 : goto overflow;
4358 [ - + ]: 4 : else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
4359 : : /* Extreme underflow */
4360 : 0 : goto underflow_or_zero;
4361 : : /* Next line is now safe from overflowing a Py_ssize_t */
4362 : 4 : diff = diff * PyLong_SHIFT + bit_length_digit(a->long_value.ob_digit[a_size - 1]) -
4363 : 4 : bit_length_digit(b->long_value.ob_digit[b_size - 1]);
4364 : : /* Now diff = a_bits - b_bits. */
4365 [ - + ]: 4 : if (diff > DBL_MAX_EXP)
4366 : 0 : goto overflow;
4367 [ - + ]: 4 : else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
4368 : 0 : goto underflow_or_zero;
4369 : :
4370 : : /* Choose value for shift; see comments for step 1 above. */
4371 : 4 : shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
4372 : :
4373 : 4 : inexact = 0;
4374 : :
4375 : : /* x = abs(a * 2**-shift) */
4376 [ + - ]: 4 : if (shift <= 0) {
4377 : 4 : Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
4378 : : digit rem;
4379 : : /* x = a << -shift */
4380 [ - + ]: 4 : if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
4381 : : /* In practice, it's probably impossible to end up
4382 : : here. Both a and b would have to be enormous,
4383 : : using close to SIZE_T_MAX bytes of memory each. */
4384 : 0 : PyErr_SetString(PyExc_OverflowError,
4385 : : "intermediate overflow during division");
4386 : 0 : goto error;
4387 : : }
4388 : 4 : x = _PyLong_New(a_size + shift_digits + 1);
4389 [ - + ]: 4 : if (x == NULL)
4390 : 0 : goto error;
4391 [ + + ]: 20 : for (i = 0; i < shift_digits; i++)
4392 : 16 : x->long_value.ob_digit[i] = 0;
4393 : 4 : rem = v_lshift(x->long_value.ob_digit + shift_digits, a->long_value.ob_digit,
4394 : 4 : a_size, -shift % PyLong_SHIFT);
4395 : 4 : x->long_value.ob_digit[a_size + shift_digits] = rem;
4396 : : }
4397 : : else {
4398 : 0 : Py_ssize_t shift_digits = shift / PyLong_SHIFT;
4399 : : digit rem;
4400 : : /* x = a >> shift */
4401 : : assert(a_size >= shift_digits);
4402 : 0 : x = _PyLong_New(a_size - shift_digits);
4403 [ # # ]: 0 : if (x == NULL)
4404 : 0 : goto error;
4405 : 0 : rem = v_rshift(x->long_value.ob_digit, a->long_value.ob_digit + shift_digits,
4406 : 0 : a_size - shift_digits, shift % PyLong_SHIFT);
4407 : : /* set inexact if any of the bits shifted out is nonzero */
4408 [ # # ]: 0 : if (rem)
4409 : 0 : inexact = 1;
4410 [ # # # # ]: 0 : while (!inexact && shift_digits > 0)
4411 [ # # ]: 0 : if (a->long_value.ob_digit[--shift_digits])
4412 : 0 : inexact = 1;
4413 : : }
4414 : 4 : long_normalize(x);
4415 : 4 : x_size = Py_SIZE(x);
4416 : :
4417 : : /* x //= b. If the remainder is nonzero, set inexact. We own the only
4418 : : reference to x, so it's safe to modify it in-place. */
4419 [ - + ]: 4 : if (b_size == 1) {
4420 : 0 : digit rem = inplace_divrem1(x->long_value.ob_digit, x->long_value.ob_digit, x_size,
4421 : : b->long_value.ob_digit[0]);
4422 : 0 : long_normalize(x);
4423 [ # # ]: 0 : if (rem)
4424 : 0 : inexact = 1;
4425 : : }
4426 : : else {
4427 : : PyLongObject *div, *rem;
4428 : 4 : div = x_divrem(x, b, &rem);
4429 : 4 : Py_SETREF(x, div);
4430 [ - + ]: 4 : if (x == NULL)
4431 : 0 : goto error;
4432 [ + - ]: 4 : if (Py_SIZE(rem))
4433 : 4 : inexact = 1;
4434 : 4 : Py_DECREF(rem);
4435 : : }
4436 [ - + ]: 4 : x_size = Py_ABS(Py_SIZE(x));
4437 : : assert(x_size > 0); /* result of division is never zero */
4438 : 4 : x_bits = (x_size-1)*PyLong_SHIFT+bit_length_digit(x->long_value.ob_digit[x_size-1]);
4439 : :
4440 : : /* The number of extra bits that have to be rounded away. */
4441 : 4 : extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
4442 : : assert(extra_bits == 2 || extra_bits == 3);
4443 : :
4444 : : /* Round by directly modifying the low digit of x. */
4445 : 4 : mask = (digit)1 << (extra_bits - 1);
4446 : 4 : low = x->long_value.ob_digit[0] | inexact;
4447 [ - + - - ]: 4 : if ((low & mask) && (low & (3U*mask-1U)))
4448 : 0 : low += mask;
4449 : 4 : x->long_value.ob_digit[0] = low & ~(2U*mask-1U);
4450 : :
4451 : : /* Convert x to a double dx; the conversion is exact. */
4452 : 4 : dx = x->long_value.ob_digit[--x_size];
4453 [ + + ]: 8 : while (x_size > 0)
4454 : 4 : dx = dx * PyLong_BASE + x->long_value.ob_digit[--x_size];
4455 : 4 : Py_DECREF(x);
4456 : :
4457 : : /* Check whether ldexp result will overflow a double. */
4458 [ - + ]: 4 : if (shift + x_bits >= DBL_MAX_EXP &&
4459 [ # # # # ]: 0 : (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
4460 : 0 : goto overflow;
4461 : 4 : result = ldexp(dx, (int)shift);
4462 : :
4463 : 24 : success:
4464 [ + + ]: 24 : return PyFloat_FromDouble(negate ? -result : result);
4465 : :
4466 : 0 : underflow_or_zero:
4467 [ # # ]: 0 : return PyFloat_FromDouble(negate ? -0.0 : 0.0);
4468 : :
4469 : 0 : overflow:
4470 : 0 : PyErr_SetString(PyExc_OverflowError,
4471 : : "integer division result too large for a float");
4472 : 1 : error:
4473 : 1 : return NULL;
4474 : : }
4475 : :
4476 : : static PyObject *
4477 : 0 : long_mod(PyObject *a, PyObject *b)
4478 : : {
4479 : : PyLongObject *mod;
4480 : :
4481 [ # # # # ]: 0 : CHECK_BINOP(a, b);
4482 : :
4483 [ # # ]: 0 : if (l_mod((PyLongObject*)a, (PyLongObject*)b, &mod) < 0)
4484 : 0 : mod = NULL;
4485 : 0 : return (PyObject *)mod;
4486 : : }
4487 : :
4488 : : static PyObject *
4489 : 148 : long_divmod(PyObject *a, PyObject *b)
4490 : : {
4491 : : PyLongObject *div, *mod;
4492 : : PyObject *z;
4493 : :
4494 [ + - - + ]: 148 : CHECK_BINOP(a, b);
4495 : :
4496 [ - + ]: 148 : if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4497 : 0 : return NULL;
4498 : : }
4499 : 148 : z = PyTuple_New(2);
4500 [ + - ]: 148 : if (z != NULL) {
4501 : 148 : PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4502 : 148 : PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
4503 : : }
4504 : : else {
4505 : 0 : Py_DECREF(div);
4506 : 0 : Py_DECREF(mod);
4507 : : }
4508 : 148 : return z;
4509 : : }
4510 : :
4511 : :
4512 : : /* Compute an inverse to a modulo n, or raise ValueError if a is not
4513 : : invertible modulo n. Assumes n is positive. The inverse returned
4514 : : is whatever falls out of the extended Euclidean algorithm: it may
4515 : : be either positive or negative, but will be smaller than n in
4516 : : absolute value.
4517 : :
4518 : : Pure Python equivalent for long_invmod:
4519 : :
4520 : : def invmod(a, n):
4521 : : b, c = 1, 0
4522 : : while n:
4523 : : q, r = divmod(a, n)
4524 : : a, b, c, n = n, c, b - q*c, r
4525 : :
4526 : : # at this point a is the gcd of the original inputs
4527 : : if a == 1:
4528 : : return b
4529 : : raise ValueError("Not invertible")
4530 : : */
4531 : :
4532 : : static PyLongObject *
4533 : 0 : long_invmod(PyLongObject *a, PyLongObject *n)
4534 : : {
4535 : : PyLongObject *b, *c;
4536 : :
4537 : : /* Should only ever be called for positive n */
4538 : : assert(Py_SIZE(n) > 0);
4539 : :
4540 : 0 : b = (PyLongObject *)PyLong_FromLong(1L);
4541 [ # # ]: 0 : if (b == NULL) {
4542 : 0 : return NULL;
4543 : : }
4544 : 0 : c = (PyLongObject *)PyLong_FromLong(0L);
4545 [ # # ]: 0 : if (c == NULL) {
4546 : 0 : Py_DECREF(b);
4547 : 0 : return NULL;
4548 : : }
4549 : 0 : Py_INCREF(a);
4550 : 0 : Py_INCREF(n);
4551 : :
4552 : : /* references now owned: a, b, c, n */
4553 [ # # ]: 0 : while (Py_SIZE(n) != 0) {
4554 : : PyLongObject *q, *r, *s, *t;
4555 : :
4556 [ # # ]: 0 : if (l_divmod(a, n, &q, &r) == -1) {
4557 : 0 : goto Error;
4558 : : }
4559 : 0 : Py_SETREF(a, n);
4560 : 0 : n = r;
4561 : 0 : t = (PyLongObject *)long_mul(q, c);
4562 : 0 : Py_DECREF(q);
4563 [ # # ]: 0 : if (t == NULL) {
4564 : 0 : goto Error;
4565 : : }
4566 : 0 : s = (PyLongObject *)long_sub(b, t);
4567 : 0 : Py_DECREF(t);
4568 [ # # ]: 0 : if (s == NULL) {
4569 : 0 : goto Error;
4570 : : }
4571 : 0 : Py_SETREF(b, c);
4572 : 0 : c = s;
4573 : : }
4574 : : /* references now owned: a, b, c, n */
4575 : :
4576 : 0 : Py_DECREF(c);
4577 : 0 : Py_DECREF(n);
4578 [ # # ]: 0 : if (long_compare(a, (PyLongObject *)_PyLong_GetOne())) {
4579 : : /* a != 1; we don't have an inverse. */
4580 : 0 : Py_DECREF(a);
4581 : 0 : Py_DECREF(b);
4582 : 0 : PyErr_SetString(PyExc_ValueError,
4583 : : "base is not invertible for the given modulus");
4584 : 0 : return NULL;
4585 : : }
4586 : : else {
4587 : : /* a == 1; b gives an inverse modulo n */
4588 : 0 : Py_DECREF(a);
4589 : 0 : return b;
4590 : : }
4591 : :
4592 : 0 : Error:
4593 : 0 : Py_DECREF(a);
4594 : 0 : Py_DECREF(b);
4595 : 0 : Py_DECREF(c);
4596 : 0 : Py_DECREF(n);
4597 : 0 : return NULL;
4598 : : }
4599 : :
4600 : :
4601 : : /* pow(v, w, x) */
4602 : : static PyObject *
4603 : 11362 : long_pow(PyObject *v, PyObject *w, PyObject *x)
4604 : : {
4605 : : PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4606 : 11362 : int negativeOutput = 0; /* if x<0 return negative output */
4607 : :
4608 : 11362 : PyLongObject *z = NULL; /* accumulated result */
4609 : : Py_ssize_t i, j; /* counters */
4610 : 11362 : PyLongObject *temp = NULL;
4611 : 11362 : PyLongObject *a2 = NULL; /* may temporarily hold a**2 % c */
4612 : :
4613 : : /* k-ary values. If the exponent is large enough, table is
4614 : : * precomputed so that table[i] == a**(2*i+1) % c for i in
4615 : : * range(EXP_TABLE_LEN).
4616 : : * Note: this is uninitialized stack trash: don't pay to set it to known
4617 : : * values unless it's needed. Instead ensure that num_table_entries is
4618 : : * set to the number of entries actually filled whenever a branch to the
4619 : : * Error or Done labels is possible.
4620 : : */
4621 : : PyLongObject *table[EXP_TABLE_LEN];
4622 : 11362 : Py_ssize_t num_table_entries = 0;
4623 : :
4624 : : /* a, b, c = v, w, x */
4625 [ + - + + ]: 11362 : CHECK_BINOP(v, w);
4626 : 11360 : a = (PyLongObject*)Py_NewRef(v);
4627 : 11360 : b = (PyLongObject*)Py_NewRef(w);
4628 [ - + ]: 11360 : if (PyLong_Check(x)) {
4629 : 0 : c = (PyLongObject *)Py_NewRef(x);
4630 : : }
4631 [ + - ]: 11360 : else if (x == Py_None)
4632 : 11360 : c = NULL;
4633 : : else {
4634 : 0 : Py_DECREF(a);
4635 : 0 : Py_DECREF(b);
4636 : 0 : Py_RETURN_NOTIMPLEMENTED;
4637 : : }
4638 : :
4639 [ + + + - ]: 11360 : if (Py_SIZE(b) < 0 && c == NULL) {
4640 : : /* if exponent is negative and there's no modulus:
4641 : : return a float. This works because we know
4642 : : that this calls float_pow() which converts its
4643 : : arguments to double. */
4644 : 7 : Py_DECREF(a);
4645 : 7 : Py_DECREF(b);
4646 : 7 : return PyFloat_Type.tp_as_number->nb_power(v, w, x);
4647 : : }
4648 : :
4649 [ - + ]: 11353 : if (c) {
4650 : : /* if modulus == 0:
4651 : : raise ValueError() */
4652 [ # # ]: 0 : if (Py_SIZE(c) == 0) {
4653 : 0 : PyErr_SetString(PyExc_ValueError,
4654 : : "pow() 3rd argument cannot be 0");
4655 : 0 : goto Error;
4656 : : }
4657 : :
4658 : : /* if modulus < 0:
4659 : : negativeOutput = True
4660 : : modulus = -modulus */
4661 [ # # ]: 0 : if (Py_SIZE(c) < 0) {
4662 : 0 : negativeOutput = 1;
4663 : 0 : temp = (PyLongObject *)_PyLong_Copy(c);
4664 [ # # ]: 0 : if (temp == NULL)
4665 : 0 : goto Error;
4666 : 0 : Py_SETREF(c, temp);
4667 : 0 : temp = NULL;
4668 : 0 : _PyLong_Negate(&c);
4669 [ # # ]: 0 : if (c == NULL)
4670 : 0 : goto Error;
4671 : : }
4672 : :
4673 : : /* if modulus == 1:
4674 : : return 0 */
4675 [ # # # # ]: 0 : if ((Py_SIZE(c) == 1) && (c->long_value.ob_digit[0] == 1)) {
4676 : 0 : z = (PyLongObject *)PyLong_FromLong(0L);
4677 : 0 : goto Done;
4678 : : }
4679 : :
4680 : : /* if exponent is negative, negate the exponent and
4681 : : replace the base with a modular inverse */
4682 [ # # ]: 0 : if (Py_SIZE(b) < 0) {
4683 : 0 : temp = (PyLongObject *)_PyLong_Copy(b);
4684 [ # # ]: 0 : if (temp == NULL)
4685 : 0 : goto Error;
4686 : 0 : Py_SETREF(b, temp);
4687 : 0 : temp = NULL;
4688 : 0 : _PyLong_Negate(&b);
4689 [ # # ]: 0 : if (b == NULL)
4690 : 0 : goto Error;
4691 : :
4692 : 0 : temp = long_invmod(a, c);
4693 [ # # ]: 0 : if (temp == NULL)
4694 : 0 : goto Error;
4695 : 0 : Py_SETREF(a, temp);
4696 : 0 : temp = NULL;
4697 : : }
4698 : :
4699 : : /* Reduce base by modulus in some cases:
4700 : : 1. If base < 0. Forcing the base non-negative makes things easier.
4701 : : 2. If base is obviously larger than the modulus. The "small
4702 : : exponent" case later can multiply directly by base repeatedly,
4703 : : while the "large exponent" case multiplies directly by base 31
4704 : : times. It can be unboundedly faster to multiply by
4705 : : base % modulus instead.
4706 : : We could _always_ do this reduction, but l_mod() isn't cheap,
4707 : : so we only do it when it buys something. */
4708 [ # # # # ]: 0 : if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
4709 [ # # ]: 0 : if (l_mod(a, c, &temp) < 0)
4710 : 0 : goto Error;
4711 : 0 : Py_SETREF(a, temp);
4712 : 0 : temp = NULL;
4713 : : }
4714 : : }
4715 : :
4716 : : /* At this point a, b, and c are guaranteed non-negative UNLESS
4717 : : c is NULL, in which case a may be negative. */
4718 : :
4719 : 11353 : z = (PyLongObject *)PyLong_FromLong(1L);
4720 [ - + ]: 11353 : if (z == NULL)
4721 : 0 : goto Error;
4722 : :
4723 : : /* Perform a modular reduction, X = X % c, but leave X alone if c
4724 : : * is NULL.
4725 : : */
4726 : : #define REDUCE(X) \
4727 : : do { \
4728 : : if (c != NULL) { \
4729 : : if (l_mod(X, c, &temp) < 0) \
4730 : : goto Error; \
4731 : : Py_XDECREF(X); \
4732 : : X = temp; \
4733 : : temp = NULL; \
4734 : : } \
4735 : : } while(0)
4736 : :
4737 : : /* Multiply two values, then reduce the result:
4738 : : result = X*Y % c. If c is NULL, skip the mod. */
4739 : : #define MULT(X, Y, result) \
4740 : : do { \
4741 : : temp = (PyLongObject *)long_mul(X, Y); \
4742 : : if (temp == NULL) \
4743 : : goto Error; \
4744 : : Py_XDECREF(result); \
4745 : : result = temp; \
4746 : : temp = NULL; \
4747 : : REDUCE(result); \
4748 : : } while(0)
4749 : :
4750 : 11353 : i = Py_SIZE(b);
4751 [ + + ]: 11353 : digit bi = i ? b->long_value.ob_digit[i-1] : 0;
4752 : : digit bit;
4753 [ + - + + ]: 11353 : if (i <= 1 && bi <= 3) {
4754 : : /* aim for minimal overhead */
4755 [ + + ]: 42 : if (bi >= 2) {
4756 [ - + - + : 4 : MULT(a, a, z);
- - ]
4757 [ + + ]: 4 : if (bi == 3) {
4758 [ - + - + : 3 : MULT(z, a, z);
- - ]
4759 : : }
4760 : : }
4761 [ - + ]: 38 : else if (bi == 1) {
4762 : : /* Multiplying by 1 serves two purposes: if `a` is of an int
4763 : : * subclass, makes the result an int (e.g., pow(False, 1) returns
4764 : : * 0 instead of False), and potentially reduces `a` by the modulus.
4765 : : */
4766 [ # # # # : 0 : MULT(a, z, z);
# # ]
4767 : : }
4768 : : /* else bi is 0, and z==1 is correct */
4769 : : }
4770 [ + - ]: 11311 : else if (i <= HUGE_EXP_CUTOFF / PyLong_SHIFT ) {
4771 : : /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4772 : : /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4773 : :
4774 : : /* Find the first significant exponent bit. Search right to left
4775 : : * because we're primarily trying to cut overhead for small powers.
4776 : : */
4777 : : assert(bi); /* else there is no significant bit */
4778 : 11311 : Py_SETREF(z, (PyLongObject*)Py_NewRef(a));
4779 : 84494 : for (bit = 2; ; bit <<= 1) {
4780 [ + + ]: 84494 : if (bit > bi) { /* found the first bit */
4781 : : assert((bi & bit) == 0);
4782 : 11311 : bit >>= 1;
4783 : : assert(bi & bit);
4784 : 11311 : break;
4785 : : }
4786 : : }
4787 : 11311 : for (--i, bit >>= 1;;) {
4788 [ + + ]: 84494 : for (; bit != 0; bit >>= 1) {
4789 [ - + - + : 73183 : MULT(z, z, z);
- - ]
4790 [ + + ]: 73183 : if (bi & bit) {
4791 [ - + - + : 33897 : MULT(z, a, z);
- - ]
4792 : : }
4793 : : }
4794 [ + - ]: 11311 : if (--i < 0) {
4795 : 11311 : break;
4796 : : }
4797 : 0 : bi = b->long_value.ob_digit[i];
4798 : 0 : bit = (digit)1 << (PyLong_SHIFT-1);
4799 : : }
4800 : : }
4801 : : else {
4802 : : /* Left-to-right k-ary sliding window exponentiation
4803 : : * (Handbook of Applied Cryptography (HAC) Algorithm 14.85)
4804 : : */
4805 : 0 : table[0] = (PyLongObject*)Py_NewRef(a);
4806 : 0 : num_table_entries = 1;
4807 [ # # # # : 0 : MULT(a, a, a2);
# # ]
4808 : : /* table[i] == a**(2*i + 1) % c */
4809 [ # # ]: 0 : for (i = 1; i < EXP_TABLE_LEN; ++i) {
4810 : 0 : table[i] = NULL; /* must set to known value for MULT */
4811 [ # # # # : 0 : MULT(table[i-1], a2, table[i]);
# # ]
4812 : 0 : ++num_table_entries; /* incremented iff MULT succeeded */
4813 : : }
4814 [ # # ]: 0 : Py_CLEAR(a2);
4815 : :
4816 : : /* Repeatedly extract the next (no more than) EXP_WINDOW_SIZE bits
4817 : : * into `pending`, starting with the next 1 bit. The current bit
4818 : : * length of `pending` is `blen`.
4819 : : */
4820 : 0 : int pending = 0, blen = 0;
4821 : : #define ABSORB_PENDING do { \
4822 : : int ntz = 0; /* number of trailing zeroes in `pending` */ \
4823 : : assert(pending && blen); \
4824 : : assert(pending >> (blen - 1)); \
4825 : : assert(pending >> blen == 0); \
4826 : : while ((pending & 1) == 0) { \
4827 : : ++ntz; \
4828 : : pending >>= 1; \
4829 : : } \
4830 : : assert(ntz < blen); \
4831 : : blen -= ntz; \
4832 : : do { \
4833 : : MULT(z, z, z); \
4834 : : } while (--blen); \
4835 : : MULT(z, table[pending >> 1], z); \
4836 : : while (ntz-- > 0) \
4837 : : MULT(z, z, z); \
4838 : : assert(blen == 0); \
4839 : : pending = 0; \
4840 : : } while(0)
4841 : :
4842 [ # # ]: 0 : for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4843 : 0 : const digit bi = b->long_value.ob_digit[i];
4844 [ # # ]: 0 : for (j = PyLong_SHIFT - 1; j >= 0; --j) {
4845 : 0 : const int bit = (bi >> j) & 1;
4846 : 0 : pending = (pending << 1) | bit;
4847 [ # # ]: 0 : if (pending) {
4848 : 0 : ++blen;
4849 [ # # ]: 0 : if (blen == EXP_WINDOW_SIZE)
4850 [ # # # # : 0 : ABSORB_PENDING;
# # # # #
# # # # #
# # # # #
# # # #
# ]
4851 : : }
4852 : : else /* absorb strings of 0 bits */
4853 [ # # # # : 0 : MULT(z, z, z);
# # ]
4854 : : }
4855 : : }
4856 [ # # ]: 0 : if (pending)
4857 [ # # # # : 0 : ABSORB_PENDING;
# # # # #
# # # # #
# # # # #
# # # #
# ]
4858 : : }
4859 : :
4860 [ - + - - ]: 11353 : if (negativeOutput && (Py_SIZE(z) != 0)) {
4861 : 0 : temp = (PyLongObject *)long_sub(z, c);
4862 [ # # ]: 0 : if (temp == NULL)
4863 : 0 : goto Error;
4864 : 0 : Py_SETREF(z, temp);
4865 : 0 : temp = NULL;
4866 : : }
4867 : 11353 : goto Done;
4868 : :
4869 : 0 : Error:
4870 [ # # ]: 0 : Py_CLEAR(z);
4871 : : /* fall through */
4872 : 0 : Done:
4873 [ - + ]: 11353 : for (i = 0; i < num_table_entries; ++i)
4874 : 0 : Py_DECREF(table[i]);
4875 : 11353 : Py_DECREF(a);
4876 : 11353 : Py_DECREF(b);
4877 : 11353 : Py_XDECREF(c);
4878 : 11353 : Py_XDECREF(a2);
4879 : 11353 : Py_XDECREF(temp);
4880 : 11353 : return (PyObject *)z;
4881 : : }
4882 : :
4883 : : static PyObject *
4884 : 18212 : long_invert(PyLongObject *v)
4885 : : {
4886 : : /* Implement ~x as -(x+1) */
4887 : : PyLongObject *x;
4888 [ + + ]: 18212 : if (IS_MEDIUM_VALUE(v))
4889 : 18153 : return _PyLong_FromSTwoDigits(~medium_value(v));
4890 : 59 : x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_GetOne());
4891 [ - + ]: 59 : if (x == NULL)
4892 : 0 : return NULL;
4893 : 59 : _PyLong_Negate(&x);
4894 : : /* No need for maybe_small_long here, since any small
4895 : : longs will have been caught in the Py_SIZE <= 1 fast path. */
4896 : 59 : return (PyObject *)x;
4897 : : }
4898 : :
4899 : : static PyObject *
4900 : 59050 : long_neg(PyLongObject *v)
4901 : : {
4902 : : PyLongObject *z;
4903 [ + + ]: 59050 : if (IS_MEDIUM_VALUE(v))
4904 : 57892 : return _PyLong_FromSTwoDigits(-medium_value(v));
4905 : 1158 : z = (PyLongObject *)_PyLong_Copy(v);
4906 [ + - ]: 1158 : if (z != NULL)
4907 : 1158 : Py_SET_SIZE(z, -(Py_SIZE(v)));
4908 : 1158 : return (PyObject *)z;
4909 : : }
4910 : :
4911 : : static PyObject *
4912 : 97248 : long_abs(PyLongObject *v)
4913 : : {
4914 [ + + ]: 97248 : if (Py_SIZE(v) < 0)
4915 : 23225 : return long_neg(v);
4916 : : else
4917 : 74023 : return long_long((PyObject *)v);
4918 : : }
4919 : :
4920 : : static int
4921 : 549608 : long_bool(PyLongObject *v)
4922 : : {
4923 : 549608 : return Py_SIZE(v) != 0;
4924 : : }
4925 : :
4926 : : /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4927 : : static int
4928 : 1062195 : divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
4929 : : {
4930 : : assert(PyLong_Check(shiftby));
4931 : : assert(Py_SIZE(shiftby) >= 0);
4932 : 1062195 : Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4933 [ + - ]: 1062195 : if (lshiftby >= 0) {
4934 : 1062195 : *wordshift = lshiftby / PyLong_SHIFT;
4935 : 1062195 : *remshift = lshiftby % PyLong_SHIFT;
4936 : 1062195 : return 0;
4937 : : }
4938 : : /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4939 : : be that PyLong_AsSsize_t raised an OverflowError. */
4940 : : assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4941 : 0 : PyErr_Clear();
4942 : 0 : PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
4943 [ # # ]: 0 : if (wordshift_obj == NULL) {
4944 : 0 : return -1;
4945 : : }
4946 : 0 : *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4947 : 0 : Py_DECREF(wordshift_obj);
4948 [ # # # # ]: 0 : if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4949 : 0 : return 0;
4950 : : }
4951 : 0 : PyErr_Clear();
4952 : : /* Clip the value. With such large wordshift the right shift
4953 : : returns 0 and the left shift raises an error in _PyLong_New(). */
4954 : 0 : *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4955 : 0 : *remshift = 0;
4956 : 0 : return 0;
4957 : : }
4958 : :
4959 : : /* Inner function for both long_rshift and _PyLong_Rshift, shifting an
4960 : : integer right by PyLong_SHIFT*wordshift + remshift bits.
4961 : : wordshift should be nonnegative. */
4962 : :
4963 : : static PyObject *
4964 : 536907 : long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4965 : : {
4966 : 536907 : PyLongObject *z = NULL;
4967 : : Py_ssize_t newsize, hishift, size_a;
4968 : : twodigits accum;
4969 : : int a_negative;
4970 : :
4971 : : /* Total number of bits shifted must be nonnegative. */
4972 : : assert(wordshift >= 0);
4973 : : assert(remshift < PyLong_SHIFT);
4974 : :
4975 : : /* Fast path for small a. */
4976 [ + + ]: 536907 : if (IS_MEDIUM_VALUE(a)) {
4977 : : stwodigits m, x;
4978 : : digit shift;
4979 : 509488 : m = medium_value(a);
4980 [ + - ]: 509488 : shift = wordshift == 0 ? remshift : PyLong_SHIFT;
4981 : 509488 : x = m < 0 ? ~(~m >> shift) : m >> shift;
4982 : 509488 : return _PyLong_FromSTwoDigits(x);
4983 : : }
4984 : :
4985 : 27419 : a_negative = Py_SIZE(a) < 0;
4986 [ - + ]: 27419 : size_a = Py_ABS(Py_SIZE(a));
4987 : :
4988 [ - + ]: 27419 : if (a_negative) {
4989 : : /* For negative 'a', adjust so that 0 < remshift <= PyLong_SHIFT,
4990 : : while keeping PyLong_SHIFT*wordshift + remshift the same. This
4991 : : ensures that 'newsize' is computed correctly below. */
4992 [ # # ]: 0 : if (remshift == 0) {
4993 [ # # ]: 0 : if (wordshift == 0) {
4994 : : /* Can only happen if the original shift was 0. */
4995 : 0 : return long_long((PyObject *)a);
4996 : : }
4997 : 0 : remshift = PyLong_SHIFT;
4998 : 0 : --wordshift;
4999 : : }
5000 : : }
5001 : :
5002 : : assert(wordshift >= 0);
5003 : 27419 : newsize = size_a - wordshift;
5004 [ - + ]: 27419 : if (newsize <= 0) {
5005 : : /* Shifting all the bits of 'a' out gives either -1 or 0. */
5006 : 0 : return PyLong_FromLong(-a_negative);
5007 : : }
5008 : 27419 : z = _PyLong_New(newsize);
5009 [ - + ]: 27419 : if (z == NULL) {
5010 : 0 : return NULL;
5011 : : }
5012 : 27419 : hishift = PyLong_SHIFT - remshift;
5013 : :
5014 : 27419 : accum = a->long_value.ob_digit[wordshift];
5015 [ - + ]: 27419 : if (a_negative) {
5016 : : /*
5017 : : For a positive integer a and nonnegative shift, we have:
5018 : :
5019 : : (-a) >> shift == -((a + 2**shift - 1) >> shift).
5020 : :
5021 : : In the addition `a + (2**shift - 1)`, the low `wordshift` digits of
5022 : : `2**shift - 1` all have value `PyLong_MASK`, so we get a carry out
5023 : : from the bottom `wordshift` digits when at least one of the least
5024 : : significant `wordshift` digits of `a` is nonzero. Digit `wordshift`
5025 : : of `2**shift - 1` has value `PyLong_MASK >> hishift`.
5026 : : */
5027 : 0 : Py_SET_SIZE(z, -newsize);
5028 : :
5029 : 0 : digit sticky = 0;
5030 [ # # ]: 0 : for (Py_ssize_t j = 0; j < wordshift; j++) {
5031 : 0 : sticky |= a->long_value.ob_digit[j];
5032 : : }
5033 : 0 : accum += (PyLong_MASK >> hishift) + (digit)(sticky != 0);
5034 : : }
5035 : :
5036 : 27419 : accum >>= remshift;
5037 [ + + ]: 98440 : for (Py_ssize_t i = 0, j = wordshift + 1; j < size_a; i++, j++) {
5038 : 71021 : accum += (twodigits)a->long_value.ob_digit[j] << hishift;
5039 : 71021 : z->long_value.ob_digit[i] = (digit)(accum & PyLong_MASK);
5040 : 71021 : accum >>= PyLong_SHIFT;
5041 : : }
5042 : : assert(accum <= PyLong_MASK);
5043 : 27419 : z->long_value.ob_digit[newsize - 1] = (digit)accum;
5044 : :
5045 : 27419 : z = maybe_small_long(long_normalize(z));
5046 : 27419 : return (PyObject *)z;
5047 : : }
5048 : :
5049 : : static PyObject *
5050 : 509999 : long_rshift(PyObject *a, PyObject *b)
5051 : : {
5052 : : Py_ssize_t wordshift;
5053 : : digit remshift;
5054 : :
5055 [ + - - + ]: 509999 : CHECK_BINOP(a, b);
5056 : :
5057 [ - + ]: 509999 : if (Py_SIZE(b) < 0) {
5058 : 0 : PyErr_SetString(PyExc_ValueError, "negative shift count");
5059 : 0 : return NULL;
5060 : : }
5061 [ + + ]: 509999 : if (Py_SIZE(a) == 0) {
5062 : 511 : return PyLong_FromLong(0);
5063 : : }
5064 [ - + ]: 509488 : if (divmod_shift(b, &wordshift, &remshift) < 0)
5065 : 0 : return NULL;
5066 : 509488 : return long_rshift1((PyLongObject *)a, wordshift, remshift);
5067 : : }
5068 : :
5069 : : /* Return a >> shiftby. */
5070 : : PyObject *
5071 : 27419 : _PyLong_Rshift(PyObject *a, size_t shiftby)
5072 : : {
5073 : : Py_ssize_t wordshift;
5074 : : digit remshift;
5075 : :
5076 : : assert(PyLong_Check(a));
5077 [ - + ]: 27419 : if (Py_SIZE(a) == 0) {
5078 : 0 : return PyLong_FromLong(0);
5079 : : }
5080 : 27419 : wordshift = shiftby / PyLong_SHIFT;
5081 : 27419 : remshift = shiftby % PyLong_SHIFT;
5082 : 27419 : return long_rshift1((PyLongObject *)a, wordshift, remshift);
5083 : : }
5084 : :
5085 : : static PyObject *
5086 : 615339 : long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
5087 : : {
5088 : 615339 : PyLongObject *z = NULL;
5089 : : Py_ssize_t oldsize, newsize, i, j;
5090 : : twodigits accum;
5091 : :
5092 [ + + + + ]: 615339 : if (wordshift == 0 && IS_MEDIUM_VALUE(a)) {
5093 : 14193 : stwodigits m = medium_value(a);
5094 : : // bypass undefined shift operator behavior
5095 [ + + ]: 14193 : stwodigits x = m < 0 ? -(-m << remshift) : m << remshift;
5096 : 14193 : return _PyLong_FromSTwoDigits(x);
5097 : : }
5098 : :
5099 [ + + ]: 601146 : oldsize = Py_ABS(Py_SIZE(a));
5100 : 601146 : newsize = oldsize + wordshift;
5101 [ + + ]: 601146 : if (remshift)
5102 : 542193 : ++newsize;
5103 : 601146 : z = _PyLong_New(newsize);
5104 [ - + ]: 601146 : if (z == NULL)
5105 : 0 : return NULL;
5106 [ + + ]: 601146 : if (Py_SIZE(a) < 0) {
5107 : : assert(Py_REFCNT(z) == 1);
5108 : 259262 : Py_SET_SIZE(z, -Py_SIZE(z));
5109 : : }
5110 [ + + ]: 2947275 : for (i = 0; i < wordshift; i++)
5111 : 2346129 : z->long_value.ob_digit[i] = 0;
5112 : 601146 : accum = 0;
5113 [ + + ]: 3321840 : for (j = 0; j < oldsize; i++, j++) {
5114 : 2720694 : accum |= (twodigits)a->long_value.ob_digit[j] << remshift;
5115 : 2720694 : z->long_value.ob_digit[i] = (digit)(accum & PyLong_MASK);
5116 : 2720694 : accum >>= PyLong_SHIFT;
5117 : : }
5118 [ + + ]: 601146 : if (remshift)
5119 : 542193 : z->long_value.ob_digit[newsize-1] = (digit)accum;
5120 : : else
5121 : : assert(!accum);
5122 : 601146 : z = long_normalize(z);
5123 : 601146 : return (PyObject *) maybe_small_long(z);
5124 : : }
5125 : :
5126 : : static PyObject *
5127 : 598741 : long_lshift(PyObject *a, PyObject *b)
5128 : : {
5129 : : Py_ssize_t wordshift;
5130 : : digit remshift;
5131 : :
5132 [ + - - + ]: 598741 : CHECK_BINOP(a, b);
5133 : :
5134 [ - + ]: 598741 : if (Py_SIZE(b) < 0) {
5135 : 0 : PyErr_SetString(PyExc_ValueError, "negative shift count");
5136 : 0 : return NULL;
5137 : : }
5138 [ + + ]: 598741 : if (Py_SIZE(a) == 0) {
5139 : 46034 : return PyLong_FromLong(0);
5140 : : }
5141 [ - + ]: 552707 : if (divmod_shift(b, &wordshift, &remshift) < 0)
5142 : 0 : return NULL;
5143 : 552707 : return long_lshift1((PyLongObject *)a, wordshift, remshift);
5144 : : }
5145 : :
5146 : : /* Return a << shiftby. */
5147 : : PyObject *
5148 : 62632 : _PyLong_Lshift(PyObject *a, size_t shiftby)
5149 : : {
5150 : : Py_ssize_t wordshift;
5151 : : digit remshift;
5152 : :
5153 : : assert(PyLong_Check(a));
5154 [ - + ]: 62632 : if (Py_SIZE(a) == 0) {
5155 : 0 : return PyLong_FromLong(0);
5156 : : }
5157 : 62632 : wordshift = shiftby / PyLong_SHIFT;
5158 : 62632 : remshift = shiftby % PyLong_SHIFT;
5159 : 62632 : return long_lshift1((PyLongObject *)a, wordshift, remshift);
5160 : : }
5161 : :
5162 : : /* Compute two's complement of digit vector a[0:m], writing result to
5163 : : z[0:m]. The digit vector a need not be normalized, but should not
5164 : : be entirely zero. a and z may point to the same digit vector. */
5165 : :
5166 : : static void
5167 : 1548 : v_complement(digit *z, digit *a, Py_ssize_t m)
5168 : : {
5169 : : Py_ssize_t i;
5170 : 1548 : digit carry = 1;
5171 [ + + ]: 7462 : for (i = 0; i < m; ++i) {
5172 : 5914 : carry += a[i] ^ PyLong_MASK;
5173 : 5914 : z[i] = carry & PyLong_MASK;
5174 : 5914 : carry >>= PyLong_SHIFT;
5175 : : }
5176 : : assert(carry == 0);
5177 : 1548 : }
5178 : :
5179 : : /* Bitwise and/xor/or operations */
5180 : :
5181 : : static PyObject *
5182 : 19593 : long_bitwise(PyLongObject *a,
5183 : : char op, /* '&', '|', '^' */
5184 : : PyLongObject *b)
5185 : : {
5186 : : int nega, negb, negz;
5187 : : Py_ssize_t size_a, size_b, size_z, i;
5188 : : PyLongObject *z;
5189 : :
5190 : : /* Bitwise operations for negative numbers operate as though
5191 : : on a two's complement representation. So convert arguments
5192 : : from sign-magnitude to two's complement, and convert the
5193 : : result back to sign-magnitude at the end. */
5194 : :
5195 : : /* If a is negative, replace it by its two's complement. */
5196 [ + + ]: 19593 : size_a = Py_ABS(Py_SIZE(a));
5197 : 19593 : nega = Py_SIZE(a) < 0;
5198 [ + + ]: 19593 : if (nega) {
5199 : 1524 : z = _PyLong_New(size_a);
5200 [ - + ]: 1524 : if (z == NULL)
5201 : 0 : return NULL;
5202 : 1524 : v_complement(z->long_value.ob_digit, a->long_value.ob_digit, size_a);
5203 : 1524 : a = z;
5204 : : }
5205 : : else
5206 : : /* Keep reference count consistent. */
5207 : 18069 : Py_INCREF(a);
5208 : :
5209 : : /* Same for b. */
5210 [ + + ]: 19593 : size_b = Py_ABS(Py_SIZE(b));
5211 : 19593 : negb = Py_SIZE(b) < 0;
5212 [ + + ]: 19593 : if (negb) {
5213 : 12 : z = _PyLong_New(size_b);
5214 [ - + ]: 12 : if (z == NULL) {
5215 : 0 : Py_DECREF(a);
5216 : 0 : return NULL;
5217 : : }
5218 : 12 : v_complement(z->long_value.ob_digit, b->long_value.ob_digit, size_b);
5219 : 12 : b = z;
5220 : : }
5221 : : else
5222 : 19581 : Py_INCREF(b);
5223 : :
5224 : : /* Swap a and b if necessary to ensure size_a >= size_b. */
5225 [ + + ]: 19593 : if (size_a < size_b) {
5226 : 16061 : z = a; a = b; b = z;
5227 : 16061 : size_z = size_a; size_a = size_b; size_b = size_z;
5228 : 16061 : negz = nega; nega = negb; negb = negz;
5229 : : }
5230 : :
5231 : : /* JRH: The original logic here was to allocate the result value (z)
5232 : : as the longer of the two operands. However, there are some cases
5233 : : where the result is guaranteed to be shorter than that: AND of two
5234 : : positives, OR of two negatives: use the shorter number. AND with
5235 : : mixed signs: use the positive number. OR with mixed signs: use the
5236 : : negative number.
5237 : : */
5238 [ - + + - ]: 19593 : switch (op) {
5239 : 0 : case '^':
5240 : 0 : negz = nega ^ negb;
5241 : 0 : size_z = size_a;
5242 : 0 : break;
5243 : 19560 : case '&':
5244 : 19560 : negz = nega & negb;
5245 [ - + ]: 19560 : size_z = negb ? size_a : size_b;
5246 : 19560 : break;
5247 : 33 : case '|':
5248 : 33 : negz = nega | negb;
5249 [ + + ]: 33 : size_z = negb ? size_b : size_a;
5250 : 33 : break;
5251 : 0 : default:
5252 : 0 : Py_UNREACHABLE();
5253 : : }
5254 : :
5255 : : /* We allow an extra digit if z is negative, to make sure that
5256 : : the final two's complement of z doesn't overflow. */
5257 : 19593 : z = _PyLong_New(size_z + negz);
5258 [ - + ]: 19593 : if (z == NULL) {
5259 : 0 : Py_DECREF(a);
5260 : 0 : Py_DECREF(b);
5261 : 0 : return NULL;
5262 : : }
5263 : :
5264 : : /* Compute digits for overlap of a and b. */
5265 [ + + - - ]: 19593 : switch(op) {
5266 : 19560 : case '&':
5267 [ + + ]: 40938 : for (i = 0; i < size_b; ++i)
5268 : 21378 : z->long_value.ob_digit[i] = a->long_value.ob_digit[i] & b->long_value.ob_digit[i];
5269 : 19560 : break;
5270 : 33 : case '|':
5271 [ + + ]: 76 : for (i = 0; i < size_b; ++i)
5272 : 43 : z->long_value.ob_digit[i] = a->long_value.ob_digit[i] | b->long_value.ob_digit[i];
5273 : 33 : break;
5274 : 0 : case '^':
5275 [ # # ]: 0 : for (i = 0; i < size_b; ++i)
5276 : 0 : z->long_value.ob_digit[i] = a->long_value.ob_digit[i] ^ b->long_value.ob_digit[i];
5277 : 0 : break;
5278 : 0 : default:
5279 : 0 : Py_UNREACHABLE();
5280 : : }
5281 : :
5282 : : /* Copy any remaining digits of a, inverting if necessary. */
5283 [ - + - - ]: 19593 : if (op == '^' && negb)
5284 [ # # ]: 0 : for (; i < size_z; ++i)
5285 : 0 : z->long_value.ob_digit[i] = a->long_value.ob_digit[i] ^ PyLong_MASK;
5286 [ + + ]: 19593 : else if (i < size_z)
5287 : 20 : memcpy(&z->long_value.ob_digit[i], &a->long_value.ob_digit[i],
5288 : 20 : (size_z-i)*sizeof(digit));
5289 : :
5290 : : /* Complement result if negative. */
5291 [ + + ]: 19593 : if (negz) {
5292 : 12 : Py_SET_SIZE(z, -(Py_SIZE(z)));
5293 : 12 : z->long_value.ob_digit[size_z] = PyLong_MASK;
5294 : 12 : v_complement(z->long_value.ob_digit, z->long_value.ob_digit, size_z+1);
5295 : : }
5296 : :
5297 : 19593 : Py_DECREF(a);
5298 : 19593 : Py_DECREF(b);
5299 : 19593 : return (PyObject *)maybe_small_long(long_normalize(z));
5300 : : }
5301 : :
5302 : : static PyObject *
5303 : 92552 : long_and(PyObject *a, PyObject *b)
5304 : : {
5305 [ + - - + ]: 92552 : CHECK_BINOP(a, b);
5306 : 92552 : PyLongObject *x = (PyLongObject*)a;
5307 : 92552 : PyLongObject *y = (PyLongObject*)b;
5308 [ + + + + ]: 92552 : if (IS_MEDIUM_VALUE(x) && IS_MEDIUM_VALUE(y)) {
5309 : 72992 : return _PyLong_FromSTwoDigits(medium_value(x) & medium_value(y));
5310 : : }
5311 : 19560 : return long_bitwise(x, '&', y);
5312 : : }
5313 : :
5314 : : static PyObject *
5315 : 22 : long_xor(PyObject *a, PyObject *b)
5316 : : {
5317 [ + - - + ]: 22 : CHECK_BINOP(a, b);
5318 : 22 : PyLongObject *x = (PyLongObject*)a;
5319 : 22 : PyLongObject *y = (PyLongObject*)b;
5320 [ + - + - ]: 22 : if (IS_MEDIUM_VALUE(x) && IS_MEDIUM_VALUE(y)) {
5321 : 22 : return _PyLong_FromSTwoDigits(medium_value(x) ^ medium_value(y));
5322 : : }
5323 : 0 : return long_bitwise(x, '^', y);
5324 : : }
5325 : :
5326 : : static PyObject *
5327 : 324290 : long_or(PyObject *a, PyObject *b)
5328 : : {
5329 [ + - - + ]: 324290 : CHECK_BINOP(a, b);
5330 : 324290 : PyLongObject *x = (PyLongObject*)a;
5331 : 324290 : PyLongObject *y = (PyLongObject*)b;
5332 [ + + + + ]: 324290 : if (IS_MEDIUM_VALUE(x) && IS_MEDIUM_VALUE(y)) {
5333 : 324257 : return _PyLong_FromSTwoDigits(medium_value(x) | medium_value(y));
5334 : : }
5335 : 33 : return long_bitwise(x, '|', y);
5336 : : }
5337 : :
5338 : : static PyObject *
5339 : 76172 : long_long(PyObject *v)
5340 : : {
5341 [ + - ]: 76172 : if (PyLong_CheckExact(v)) {
5342 : 76172 : return Py_NewRef(v);
5343 : : }
5344 : : else {
5345 : 0 : return _PyLong_Copy((PyLongObject *)v);
5346 : : }
5347 : : }
5348 : :
5349 : : PyObject *
5350 : 56449 : _PyLong_GCD(PyObject *aarg, PyObject *barg)
5351 : : {
5352 : 56449 : PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
5353 : : stwodigits x, y, q, s, t, c_carry, d_carry;
5354 : : stwodigits A, B, C, D, T;
5355 : : int nbits, k;
5356 : : Py_ssize_t size_a, size_b, alloc_a, alloc_b;
5357 : : digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
5358 : :
5359 : 56449 : a = (PyLongObject *)aarg;
5360 : 56449 : b = (PyLongObject *)barg;
5361 : 56449 : size_a = Py_SIZE(a);
5362 : 56449 : size_b = Py_SIZE(b);
5363 [ + + + + : 56449 : if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
+ - + + ]
5364 : 28663 : Py_INCREF(a);
5365 : 28663 : Py_INCREF(b);
5366 : 28663 : goto simple;
5367 : : }
5368 : :
5369 : : /* Initial reduction: make sure that 0 <= b <= a. */
5370 : 27786 : a = (PyLongObject *)long_abs(a);
5371 [ - + ]: 27786 : if (a == NULL)
5372 : 0 : return NULL;
5373 : 27786 : b = (PyLongObject *)long_abs(b);
5374 [ - + ]: 27786 : if (b == NULL) {
5375 : 0 : Py_DECREF(a);
5376 : 0 : return NULL;
5377 : : }
5378 [ + + ]: 27786 : if (long_compare(a, b) < 0) {
5379 : 10145 : r = a;
5380 : 10145 : a = b;
5381 : 10145 : b = r;
5382 : : }
5383 : : /* We now own references to a and b */
5384 : :
5385 : 27786 : alloc_a = Py_SIZE(a);
5386 : 27786 : alloc_b = Py_SIZE(b);
5387 : : /* reduce until a fits into 2 digits */
5388 [ + + ]: 55078 : while ((size_a = Py_SIZE(a)) > 2) {
5389 : 45253 : nbits = bit_length_digit(a->long_value.ob_digit[size_a-1]);
5390 : : /* extract top 2*PyLong_SHIFT bits of a into x, along with
5391 : : corresponding bits of b into y */
5392 : 45253 : size_b = Py_SIZE(b);
5393 : : assert(size_b <= size_a);
5394 [ + + ]: 45253 : if (size_b == 0) {
5395 [ + + ]: 17961 : if (size_a < alloc_a) {
5396 : 16 : r = (PyLongObject *)_PyLong_Copy(a);
5397 : 16 : Py_DECREF(a);
5398 : : }
5399 : : else
5400 : 17945 : r = a;
5401 : 17961 : Py_DECREF(b);
5402 : 17961 : Py_XDECREF(c);
5403 : 17961 : Py_XDECREF(d);
5404 : 17961 : return (PyObject *)r;
5405 : : }
5406 : 27292 : x = (((twodigits)a->long_value.ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
5407 : 27292 : ((twodigits)a->long_value.ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
5408 : 27292 : (a->long_value.ob_digit[size_a-3] >> nbits));
5409 : :
5410 [ + + ]: 27292 : y = ((size_b >= size_a - 2 ? b->long_value.ob_digit[size_a-3] >> nbits : 0) |
5411 [ + + ]: 27292 : (size_b >= size_a - 1 ? (twodigits)b->long_value.ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
5412 [ + + ]: 27292 : (size_b >= size_a ? (twodigits)b->long_value.ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
5413 : :
5414 : : /* inner loop of Lehmer's algorithm; A, B, C, D never grow
5415 : : larger than PyLong_MASK during the algorithm. */
5416 : 27292 : A = 1; B = 0; C = 0; D = 1;
5417 : 27292 : for (k=0;; k++) {
5418 [ + + ]: 28752 : if (y-C == 0)
5419 : 9823 : break;
5420 : 18929 : q = (x+(A-1))/(y-C);
5421 : 18929 : s = B+q*D;
5422 : 18929 : t = x-q*y;
5423 [ + + ]: 18929 : if (s > t)
5424 : 17469 : break;
5425 : 1460 : x = y; y = t;
5426 : 1460 : t = A+q*C; A = D; B = C; C = s; D = t;
5427 : : }
5428 : :
5429 [ + + ]: 27292 : if (k == 0) {
5430 : : /* no progress; do a Euclidean step */
5431 [ - + ]: 27184 : if (l_mod(a, b, &r) < 0)
5432 : 0 : goto error;
5433 : 27184 : Py_SETREF(a, b);
5434 : 27184 : b = r;
5435 : 27184 : alloc_a = alloc_b;
5436 : 27184 : alloc_b = Py_SIZE(b);
5437 : 27184 : continue;
5438 : : }
5439 : :
5440 : : /*
5441 : : a, b = A*b-B*a, D*a-C*b if k is odd
5442 : : a, b = A*a-B*b, D*b-C*a if k is even
5443 : : */
5444 [ + + ]: 108 : if (k&1) {
5445 : 48 : T = -A; A = -B; B = T;
5446 : 48 : T = -C; C = -D; D = T;
5447 : : }
5448 [ + + ]: 108 : if (c != NULL) {
5449 : 74 : Py_SET_SIZE(c, size_a);
5450 : : }
5451 [ + + ]: 34 : else if (Py_REFCNT(a) == 1) {
5452 : 16 : c = (PyLongObject*)Py_NewRef(a);
5453 : : }
5454 : : else {
5455 : 18 : alloc_a = size_a;
5456 : 18 : c = _PyLong_New(size_a);
5457 [ - + ]: 18 : if (c == NULL)
5458 : 0 : goto error;
5459 : : }
5460 : :
5461 [ + + ]: 108 : if (d != NULL) {
5462 : 74 : Py_SET_SIZE(d, size_a);
5463 : : }
5464 [ + + + - ]: 34 : else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
5465 : 24 : d = (PyLongObject*)Py_NewRef(b);
5466 : 24 : Py_SET_SIZE(d, size_a);
5467 : : }
5468 : : else {
5469 : 10 : alloc_b = size_a;
5470 : 10 : d = _PyLong_New(size_a);
5471 [ - + ]: 10 : if (d == NULL)
5472 : 0 : goto error;
5473 : : }
5474 : 108 : a_end = a->long_value.ob_digit + size_a;
5475 : 108 : b_end = b->long_value.ob_digit + size_b;
5476 : :
5477 : : /* compute new a and new b in parallel */
5478 : 108 : a_digit = a->long_value.ob_digit;
5479 : 108 : b_digit = b->long_value.ob_digit;
5480 : 108 : c_digit = c->long_value.ob_digit;
5481 : 108 : d_digit = d->long_value.ob_digit;
5482 : 108 : c_carry = 0;
5483 : 108 : d_carry = 0;
5484 [ + + ]: 774 : while (b_digit < b_end) {
5485 : 666 : c_carry += (A * *a_digit) - (B * *b_digit);
5486 : 666 : d_carry += (D * *b_digit++) - (C * *a_digit++);
5487 : 666 : *c_digit++ = (digit)(c_carry & PyLong_MASK);
5488 : 666 : *d_digit++ = (digit)(d_carry & PyLong_MASK);
5489 : 666 : c_carry >>= PyLong_SHIFT;
5490 : 666 : d_carry >>= PyLong_SHIFT;
5491 : : }
5492 [ + + ]: 110 : while (a_digit < a_end) {
5493 : 2 : c_carry += A * *a_digit;
5494 : 2 : d_carry -= C * *a_digit++;
5495 : 2 : *c_digit++ = (digit)(c_carry & PyLong_MASK);
5496 : 2 : *d_digit++ = (digit)(d_carry & PyLong_MASK);
5497 : 2 : c_carry >>= PyLong_SHIFT;
5498 : 2 : d_carry >>= PyLong_SHIFT;
5499 : : }
5500 : : assert(c_carry == 0);
5501 : : assert(d_carry == 0);
5502 : :
5503 : 108 : Py_INCREF(c);
5504 : 108 : Py_INCREF(d);
5505 : 108 : Py_DECREF(a);
5506 : 108 : Py_DECREF(b);
5507 : 108 : a = long_normalize(c);
5508 : 108 : b = long_normalize(d);
5509 : : }
5510 : 9825 : Py_XDECREF(c);
5511 : 9825 : Py_XDECREF(d);
5512 : :
5513 : 38488 : simple:
5514 : : assert(Py_REFCNT(a) > 0);
5515 : : assert(Py_REFCNT(b) > 0);
5516 : : /* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
5517 : : undefined behaviour when LONG_MAX type is smaller than 60 bits */
5518 : : #if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
5519 : : /* a fits into a long, so b must too */
5520 : 38488 : x = PyLong_AsLong((PyObject *)a);
5521 : 38488 : y = PyLong_AsLong((PyObject *)b);
5522 : : #elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
5523 : : x = PyLong_AsLongLong((PyObject *)a);
5524 : : y = PyLong_AsLongLong((PyObject *)b);
5525 : : #else
5526 : : # error "_PyLong_GCD"
5527 : : #endif
5528 : 38488 : x = Py_ABS(x);
5529 : 38488 : y = Py_ABS(y);
5530 : 38488 : Py_DECREF(a);
5531 : 38488 : Py_DECREF(b);
5532 : :
5533 : : /* usual Euclidean algorithm for longs */
5534 [ + + ]: 104972 : while (y != 0) {
5535 : 66484 : t = y;
5536 : 66484 : y = x % y;
5537 : 66484 : x = t;
5538 : : }
5539 : : #if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
5540 : 38488 : return PyLong_FromLong(x);
5541 : : #elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
5542 : : return PyLong_FromLongLong(x);
5543 : : #else
5544 : : # error "_PyLong_GCD"
5545 : : #endif
5546 : :
5547 : 0 : error:
5548 : 0 : Py_DECREF(a);
5549 : 0 : Py_DECREF(b);
5550 : 0 : Py_XDECREF(c);
5551 : 0 : Py_XDECREF(d);
5552 : 0 : return NULL;
5553 : : }
5554 : :
5555 : : static PyObject *
5556 : 48376 : long_float(PyObject *v)
5557 : : {
5558 : : double result;
5559 : 48376 : result = PyLong_AsDouble(v);
5560 [ + + - + ]: 48376 : if (result == -1.0 && PyErr_Occurred())
5561 : 0 : return NULL;
5562 : 48376 : return PyFloat_FromDouble(result);
5563 : : }
5564 : :
5565 : : static PyObject *
5566 : : long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5567 : :
5568 : : /*[clinic input]
5569 : : @classmethod
5570 : : int.__new__ as long_new
5571 : : x: object(c_default="NULL") = 0
5572 : : /
5573 : : base as obase: object(c_default="NULL") = 10
5574 : : [clinic start generated code]*/
5575 : :
5576 : : static PyObject *
5577 : 536594 : long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5578 : : /*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
5579 : : {
5580 : : Py_ssize_t base;
5581 : :
5582 [ + + ]: 536594 : if (type != &PyLong_Type)
5583 : 723 : return long_subtype_new(type, x, obase); /* Wimp out */
5584 [ + + ]: 535871 : if (x == NULL) {
5585 [ - + ]: 2233 : if (obase != NULL) {
5586 : 0 : PyErr_SetString(PyExc_TypeError,
5587 : : "int() missing string argument");
5588 : 0 : return NULL;
5589 : : }
5590 : 2233 : return PyLong_FromLong(0L);
5591 : : }
5592 : : /* default base and limit, forward to standard implementation */
5593 [ + + ]: 533638 : if (obase == NULL)
5594 : 533142 : return PyNumber_Long(x);
5595 : :
5596 : 496 : base = PyNumber_AsSsize_t(obase, NULL);
5597 [ - + - - ]: 496 : if (base == -1 && PyErr_Occurred())
5598 : 0 : return NULL;
5599 [ + - + - : 496 : if ((base != 0 && base < 2) || base > 36) {
- + ]
5600 : 0 : PyErr_SetString(PyExc_ValueError,
5601 : : "int() base must be >= 2 and <= 36, or 0");
5602 : 0 : return NULL;
5603 : : }
5604 : :
5605 [ - + ]: 496 : if (PyUnicode_Check(x))
5606 : 0 : return PyLong_FromUnicodeObject(x, (int)base);
5607 [ - + - - ]: 496 : else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
5608 : : const char *string;
5609 [ + - ]: 496 : if (PyByteArray_Check(x))
5610 : 496 : string = PyByteArray_AS_STRING(x);
5611 : : else
5612 : 0 : string = PyBytes_AS_STRING(x);
5613 : 496 : return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
5614 : : }
5615 : : else {
5616 : 0 : PyErr_SetString(PyExc_TypeError,
5617 : : "int() can't convert non-string with explicit base");
5618 : 0 : return NULL;
5619 : : }
5620 : : }
5621 : :
5622 : : /* Wimpy, slow approach to tp_new calls for subtypes of int:
5623 : : first create a regular int from whatever arguments we got,
5624 : : then allocate a subtype instance and initialize it from
5625 : : the regular int. The regular int is then thrown away.
5626 : : */
5627 : : static PyObject *
5628 : 723 : long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
5629 : : {
5630 : : PyLongObject *tmp, *newobj;
5631 : : Py_ssize_t i, n;
5632 : :
5633 : : assert(PyType_IsSubtype(type, &PyLong_Type));
5634 : 723 : tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
5635 [ - + ]: 723 : if (tmp == NULL)
5636 : 0 : return NULL;
5637 : : assert(PyLong_Check(tmp));
5638 : 723 : n = Py_SIZE(tmp);
5639 [ + + ]: 723 : if (n < 0)
5640 : 2 : n = -n;
5641 : : /* Fast operations for single digit integers (including zero)
5642 : : * assume that there is always at least one digit present. */
5643 [ + + ]: 723 : if (n == 0) {
5644 : 32 : n = 1;
5645 : : }
5646 : 723 : newobj = (PyLongObject *)type->tp_alloc(type, n);
5647 [ - + ]: 723 : if (newobj == NULL) {
5648 : 0 : Py_DECREF(tmp);
5649 : 0 : return NULL;
5650 : : }
5651 : : assert(PyLong_Check(newobj));
5652 : 723 : Py_SET_SIZE(newobj, Py_SIZE(tmp));
5653 [ + + ]: 1453 : for (i = 0; i < n; i++) {
5654 : 730 : newobj->long_value.ob_digit[i] = tmp->long_value.ob_digit[i];
5655 : : }
5656 : 723 : Py_DECREF(tmp);
5657 : 723 : return (PyObject *)newobj;
5658 : : }
5659 : :
5660 : : /*[clinic input]
5661 : : int.__getnewargs__
5662 : : [clinic start generated code]*/
5663 : :
5664 : : static PyObject *
5665 : 0 : int___getnewargs___impl(PyObject *self)
5666 : : /*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
5667 : : {
5668 : 0 : return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
5669 : : }
5670 : :
5671 : : static PyObject *
5672 : 0 : long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5673 : : {
5674 : 0 : return PyLong_FromLong(0L);
5675 : : }
5676 : :
5677 : : static PyObject *
5678 : 0 : long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5679 : : {
5680 : 0 : return PyLong_FromLong(1L);
5681 : : }
5682 : :
5683 : : /*[clinic input]
5684 : : int.__format__
5685 : :
5686 : : format_spec: unicode
5687 : : /
5688 : :
5689 : : Convert to a string according to format_spec.
5690 : : [clinic start generated code]*/
5691 : :
5692 : : static PyObject *
5693 : 268271 : int___format___impl(PyObject *self, PyObject *format_spec)
5694 : : /*[clinic end generated code: output=b4929dee9ae18689 input=d5e1254a47e8d1dc]*/
5695 : : {
5696 : : _PyUnicodeWriter writer;
5697 : : int ret;
5698 : :
5699 : 268271 : _PyUnicodeWriter_Init(&writer);
5700 : 268271 : ret = _PyLong_FormatAdvancedWriter(
5701 : : &writer,
5702 : : self,
5703 : : format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5704 [ - + ]: 268271 : if (ret == -1) {
5705 : 0 : _PyUnicodeWriter_Dealloc(&writer);
5706 : 0 : return NULL;
5707 : : }
5708 : 268271 : return _PyUnicodeWriter_Finish(&writer);
5709 : : }
5710 : :
5711 : : /* Return a pair (q, r) such that a = b * q + r, and
5712 : : abs(r) <= abs(b)/2, with equality possible only if q is even.
5713 : : In other words, q == a / b, rounded to the nearest integer using
5714 : : round-half-to-even. */
5715 : :
5716 : : PyObject *
5717 : 0 : _PyLong_DivmodNear(PyObject *a, PyObject *b)
5718 : : {
5719 : 0 : PyLongObject *quo = NULL, *rem = NULL;
5720 : : PyObject *twice_rem, *result, *temp;
5721 : : int quo_is_odd, quo_is_neg;
5722 : : Py_ssize_t cmp;
5723 : :
5724 : : /* Equivalent Python code:
5725 : :
5726 : : def divmod_near(a, b):
5727 : : q, r = divmod(a, b)
5728 : : # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5729 : : # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5730 : : # positive, 2 * r < b if b negative.
5731 : : greater_than_half = 2*r > b if b > 0 else 2*r < b
5732 : : exactly_half = 2*r == b
5733 : : if greater_than_half or exactly_half and q % 2 == 1:
5734 : : q += 1
5735 : : r -= b
5736 : : return q, r
5737 : :
5738 : : */
5739 [ # # # # ]: 0 : if (!PyLong_Check(a) || !PyLong_Check(b)) {
5740 : 0 : PyErr_SetString(PyExc_TypeError,
5741 : : "non-integer arguments in division");
5742 : 0 : return NULL;
5743 : : }
5744 : :
5745 : : /* Do a and b have different signs? If so, quotient is negative. */
5746 : 0 : quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5747 : :
5748 [ # # ]: 0 : if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
5749 : 0 : goto error;
5750 : :
5751 : : /* compare twice the remainder with the divisor, to see
5752 : : if we need to adjust the quotient and remainder */
5753 : 0 : PyObject *one = _PyLong_GetOne(); // borrowed reference
5754 : 0 : twice_rem = long_lshift((PyObject *)rem, one);
5755 [ # # ]: 0 : if (twice_rem == NULL)
5756 : 0 : goto error;
5757 [ # # ]: 0 : if (quo_is_neg) {
5758 : 0 : temp = long_neg((PyLongObject*)twice_rem);
5759 : 0 : Py_SETREF(twice_rem, temp);
5760 [ # # ]: 0 : if (twice_rem == NULL)
5761 : 0 : goto error;
5762 : : }
5763 : 0 : cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5764 : 0 : Py_DECREF(twice_rem);
5765 : :
5766 [ # # # # ]: 0 : quo_is_odd = Py_SIZE(quo) != 0 && ((quo->long_value.ob_digit[0] & 1) != 0);
5767 [ # # # # : 0 : if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
# # # # #
# ]
5768 : : /* fix up quotient */
5769 [ # # ]: 0 : if (quo_is_neg)
5770 : 0 : temp = long_sub(quo, (PyLongObject *)one);
5771 : : else
5772 : 0 : temp = long_add(quo, (PyLongObject *)one);
5773 : 0 : Py_SETREF(quo, (PyLongObject *)temp);
5774 [ # # ]: 0 : if (quo == NULL)
5775 : 0 : goto error;
5776 : : /* and remainder */
5777 [ # # ]: 0 : if (quo_is_neg)
5778 : 0 : temp = long_add(rem, (PyLongObject *)b);
5779 : : else
5780 : 0 : temp = long_sub(rem, (PyLongObject *)b);
5781 : 0 : Py_SETREF(rem, (PyLongObject *)temp);
5782 [ # # ]: 0 : if (rem == NULL)
5783 : 0 : goto error;
5784 : : }
5785 : :
5786 : 0 : result = PyTuple_New(2);
5787 [ # # ]: 0 : if (result == NULL)
5788 : 0 : goto error;
5789 : :
5790 : : /* PyTuple_SET_ITEM steals references */
5791 : 0 : PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5792 : 0 : PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
5793 : 0 : return result;
5794 : :
5795 : 0 : error:
5796 : 0 : Py_XDECREF(quo);
5797 : 0 : Py_XDECREF(rem);
5798 : 0 : return NULL;
5799 : : }
5800 : :
5801 : : /*[clinic input]
5802 : : int.__round__
5803 : :
5804 : : ndigits as o_ndigits: object = NULL
5805 : : /
5806 : :
5807 : : Rounding an Integral returns itself.
5808 : :
5809 : : Rounding with an ndigits argument also returns an integer.
5810 : : [clinic start generated code]*/
5811 : :
5812 : : static PyObject *
5813 : 0 : int___round___impl(PyObject *self, PyObject *o_ndigits)
5814 : : /*[clinic end generated code: output=954fda6b18875998 input=1614cf23ec9e18c3]*/
5815 : : {
5816 : : PyObject *temp, *result, *ndigits;
5817 : :
5818 : : /* To round an integer m to the nearest 10**n (n positive), we make use of
5819 : : * the divmod_near operation, defined by:
5820 : : *
5821 : : * divmod_near(a, b) = (q, r)
5822 : : *
5823 : : * where q is the nearest integer to the quotient a / b (the
5824 : : * nearest even integer in the case of a tie) and r == a - q * b.
5825 : : * Hence q * b = a - r is the nearest multiple of b to a,
5826 : : * preferring even multiples in the case of a tie.
5827 : : *
5828 : : * So the nearest multiple of 10**n to m is:
5829 : : *
5830 : : * m - divmod_near(m, 10**n)[1].
5831 : : */
5832 [ # # ]: 0 : if (o_ndigits == NULL)
5833 : 0 : return long_long(self);
5834 : :
5835 : 0 : ndigits = _PyNumber_Index(o_ndigits);
5836 [ # # ]: 0 : if (ndigits == NULL)
5837 : 0 : return NULL;
5838 : :
5839 : : /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
5840 [ # # ]: 0 : if (Py_SIZE(ndigits) >= 0) {
5841 : 0 : Py_DECREF(ndigits);
5842 : 0 : return long_long(self);
5843 : : }
5844 : :
5845 : : /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5846 : 0 : temp = long_neg((PyLongObject*)ndigits);
5847 : 0 : Py_SETREF(ndigits, temp);
5848 [ # # ]: 0 : if (ndigits == NULL)
5849 : 0 : return NULL;
5850 : :
5851 : 0 : result = PyLong_FromLong(10L);
5852 [ # # ]: 0 : if (result == NULL) {
5853 : 0 : Py_DECREF(ndigits);
5854 : 0 : return NULL;
5855 : : }
5856 : :
5857 : 0 : temp = long_pow(result, ndigits, Py_None);
5858 : 0 : Py_DECREF(ndigits);
5859 : 0 : Py_SETREF(result, temp);
5860 [ # # ]: 0 : if (result == NULL)
5861 : 0 : return NULL;
5862 : :
5863 : 0 : temp = _PyLong_DivmodNear(self, result);
5864 : 0 : Py_SETREF(result, temp);
5865 [ # # ]: 0 : if (result == NULL)
5866 : 0 : return NULL;
5867 : :
5868 : 0 : temp = long_sub((PyLongObject *)self,
5869 : 0 : (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5870 : 0 : Py_SETREF(result, temp);
5871 : :
5872 : 0 : return result;
5873 : : }
5874 : :
5875 : : /*[clinic input]
5876 : : int.__sizeof__ -> Py_ssize_t
5877 : :
5878 : : Returns size in memory, in bytes.
5879 : : [clinic start generated code]*/
5880 : :
5881 : : static Py_ssize_t
5882 : 0 : int___sizeof___impl(PyObject *self)
5883 : : /*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
5884 : : {
5885 : : /* using Py_MAX(..., 1) because we always allocate space for at least
5886 : : one digit, even though the integer zero has a Py_SIZE of 0 */
5887 [ # # # # : 0 : Py_ssize_t ndigits = Py_MAX(Py_ABS(Py_SIZE(self)), 1);
# # ]
5888 : 0 : return Py_TYPE(self)->tp_basicsize + Py_TYPE(self)->tp_itemsize * ndigits;
5889 : : }
5890 : :
5891 : : /*[clinic input]
5892 : : int.bit_length
5893 : :
5894 : : Number of bits necessary to represent self in binary.
5895 : :
5896 : : >>> bin(37)
5897 : : '0b100101'
5898 : : >>> (37).bit_length()
5899 : : 6
5900 : : [clinic start generated code]*/
5901 : :
5902 : : static PyObject *
5903 : 260115 : int_bit_length_impl(PyObject *self)
5904 : : /*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
5905 : : {
5906 : : PyLongObject *result, *x, *y;
5907 : : Py_ssize_t ndigits;
5908 : : int msd_bits;
5909 : : digit msd;
5910 : :
5911 : : assert(self != NULL);
5912 : : assert(PyLong_Check(self));
5913 : :
5914 [ - + ]: 260115 : ndigits = Py_ABS(Py_SIZE(self));
5915 [ + + ]: 260115 : if (ndigits == 0)
5916 : 38 : return PyLong_FromLong(0);
5917 : :
5918 : 260077 : msd = ((PyLongObject *)self)->long_value.ob_digit[ndigits-1];
5919 : 260077 : msd_bits = bit_length_digit(msd);
5920 : :
5921 [ + - ]: 260077 : if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5922 : 260077 : return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
5923 : :
5924 : : /* expression above may overflow; use Python integers instead */
5925 : 0 : result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5926 [ # # ]: 0 : if (result == NULL)
5927 : 0 : return NULL;
5928 : 0 : x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5929 [ # # ]: 0 : if (x == NULL)
5930 : 0 : goto error;
5931 : 0 : y = (PyLongObject *)long_mul(result, x);
5932 : 0 : Py_DECREF(x);
5933 [ # # ]: 0 : if (y == NULL)
5934 : 0 : goto error;
5935 : 0 : Py_SETREF(result, y);
5936 : :
5937 : 0 : x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5938 [ # # ]: 0 : if (x == NULL)
5939 : 0 : goto error;
5940 : 0 : y = (PyLongObject *)long_add(result, x);
5941 : 0 : Py_DECREF(x);
5942 [ # # ]: 0 : if (y == NULL)
5943 : 0 : goto error;
5944 : 0 : Py_SETREF(result, y);
5945 : :
5946 : 0 : return (PyObject *)result;
5947 : :
5948 : 0 : error:
5949 : 0 : Py_DECREF(result);
5950 : 0 : return NULL;
5951 : : }
5952 : :
5953 : : static int
5954 : 0 : popcount_digit(digit d)
5955 : : {
5956 : : // digit can be larger than uint32_t, but only PyLong_SHIFT bits
5957 : : // of it will be ever used.
5958 : : static_assert(PyLong_SHIFT <= 32, "digit is larger than uint32_t");
5959 : 0 : return _Py_popcount32((uint32_t)d);
5960 : : }
5961 : :
5962 : : /*[clinic input]
5963 : : int.bit_count
5964 : :
5965 : : Number of ones in the binary representation of the absolute value of self.
5966 : :
5967 : : Also known as the population count.
5968 : :
5969 : : >>> bin(13)
5970 : : '0b1101'
5971 : : >>> (13).bit_count()
5972 : : 3
5973 : : [clinic start generated code]*/
5974 : :
5975 : : static PyObject *
5976 : 0 : int_bit_count_impl(PyObject *self)
5977 : : /*[clinic end generated code: output=2e571970daf1e5c3 input=7e0adef8e8ccdf2e]*/
5978 : : {
5979 : : assert(self != NULL);
5980 : : assert(PyLong_Check(self));
5981 : :
5982 : 0 : PyLongObject *z = (PyLongObject *)self;
5983 [ # # ]: 0 : Py_ssize_t ndigits = Py_ABS(Py_SIZE(z));
5984 : 0 : Py_ssize_t bit_count = 0;
5985 : :
5986 : : /* Each digit has up to PyLong_SHIFT ones, so the accumulated bit count
5987 : : from the first PY_SSIZE_T_MAX/PyLong_SHIFT digits can't overflow a
5988 : : Py_ssize_t. */
5989 : 0 : Py_ssize_t ndigits_fast = Py_MIN(ndigits, PY_SSIZE_T_MAX/PyLong_SHIFT);
5990 [ # # ]: 0 : for (Py_ssize_t i = 0; i < ndigits_fast; i++) {
5991 : 0 : bit_count += popcount_digit(z->long_value.ob_digit[i]);
5992 : : }
5993 : :
5994 : 0 : PyObject *result = PyLong_FromSsize_t(bit_count);
5995 [ # # ]: 0 : if (result == NULL) {
5996 : 0 : return NULL;
5997 : : }
5998 : :
5999 : : /* Use Python integers if bit_count would overflow. */
6000 [ # # ]: 0 : for (Py_ssize_t i = ndigits_fast; i < ndigits; i++) {
6001 : 0 : PyObject *x = PyLong_FromLong(popcount_digit(z->long_value.ob_digit[i]));
6002 [ # # ]: 0 : if (x == NULL) {
6003 : 0 : goto error;
6004 : : }
6005 : 0 : PyObject *y = long_add((PyLongObject *)result, (PyLongObject *)x);
6006 : 0 : Py_DECREF(x);
6007 [ # # ]: 0 : if (y == NULL) {
6008 : 0 : goto error;
6009 : : }
6010 : 0 : Py_SETREF(result, y);
6011 : : }
6012 : :
6013 : 0 : return result;
6014 : :
6015 : 0 : error:
6016 : 0 : Py_DECREF(result);
6017 : 0 : return NULL;
6018 : : }
6019 : :
6020 : : /*[clinic input]
6021 : : int.as_integer_ratio
6022 : :
6023 : : Return a pair of integers, whose ratio is equal to the original int.
6024 : :
6025 : : The ratio is in lowest terms and has a positive denominator.
6026 : :
6027 : : >>> (10).as_integer_ratio()
6028 : : (10, 1)
6029 : : >>> (-10).as_integer_ratio()
6030 : : (-10, 1)
6031 : : >>> (0).as_integer_ratio()
6032 : : (0, 1)
6033 : : [clinic start generated code]*/
6034 : :
6035 : : static PyObject *
6036 : 0 : int_as_integer_ratio_impl(PyObject *self)
6037 : : /*[clinic end generated code: output=e60803ae1cc8621a input=384ff1766634bec2]*/
6038 : : {
6039 : : PyObject *ratio_tuple;
6040 : 0 : PyObject *numerator = long_long(self);
6041 [ # # ]: 0 : if (numerator == NULL) {
6042 : 0 : return NULL;
6043 : : }
6044 : 0 : ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_GetOne());
6045 : 0 : Py_DECREF(numerator);
6046 : 0 : return ratio_tuple;
6047 : : }
6048 : :
6049 : : /*[clinic input]
6050 : : int.to_bytes
6051 : :
6052 : : length: Py_ssize_t = 1
6053 : : Length of bytes object to use. An OverflowError is raised if the
6054 : : integer is not representable with the given number of bytes. Default
6055 : : is length 1.
6056 : : byteorder: unicode(c_default="NULL") = "big"
6057 : : The byte order used to represent the integer. If byteorder is 'big',
6058 : : the most significant byte is at the beginning of the byte array. If
6059 : : byteorder is 'little', the most significant byte is at the end of the
6060 : : byte array. To request the native byte order of the host system, use
6061 : : `sys.byteorder' as the byte order value. Default is to use 'big'.
6062 : : *
6063 : : signed as is_signed: bool = False
6064 : : Determines whether two's complement is used to represent the integer.
6065 : : If signed is False and a negative integer is given, an OverflowError
6066 : : is raised.
6067 : :
6068 : : Return an array of bytes representing an integer.
6069 : : [clinic start generated code]*/
6070 : :
6071 : : static PyObject *
6072 : 502 : int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
6073 : : int is_signed)
6074 : : /*[clinic end generated code: output=89c801df114050a3 input=d42ecfb545039d71]*/
6075 : : {
6076 : : int little_endian;
6077 : : PyObject *bytes;
6078 : :
6079 [ - + ]: 502 : if (byteorder == NULL)
6080 : 0 : little_endian = 0;
6081 [ + - ]: 502 : else if (_PyUnicode_Equal(byteorder, &_Py_ID(little)))
6082 : 502 : little_endian = 1;
6083 [ # # ]: 0 : else if (_PyUnicode_Equal(byteorder, &_Py_ID(big)))
6084 : 0 : little_endian = 0;
6085 : : else {
6086 : 0 : PyErr_SetString(PyExc_ValueError,
6087 : : "byteorder must be either 'little' or 'big'");
6088 : 0 : return NULL;
6089 : : }
6090 : :
6091 [ - + ]: 502 : if (length < 0) {
6092 : 0 : PyErr_SetString(PyExc_ValueError,
6093 : : "length argument must be non-negative");
6094 : 0 : return NULL;
6095 : : }
6096 : :
6097 : 502 : bytes = PyBytes_FromStringAndSize(NULL, length);
6098 [ - + ]: 502 : if (bytes == NULL)
6099 : 0 : return NULL;
6100 : :
6101 [ - + ]: 502 : if (_PyLong_AsByteArray((PyLongObject *)self,
6102 : 502 : (unsigned char *)PyBytes_AS_STRING(bytes),
6103 : : length, little_endian, is_signed) < 0) {
6104 : 0 : Py_DECREF(bytes);
6105 : 0 : return NULL;
6106 : : }
6107 : :
6108 : 502 : return bytes;
6109 : : }
6110 : :
6111 : : /*[clinic input]
6112 : : @classmethod
6113 : : int.from_bytes
6114 : :
6115 : : bytes as bytes_obj: object
6116 : : Holds the array of bytes to convert. The argument must either
6117 : : support the buffer protocol or be an iterable object producing bytes.
6118 : : Bytes and bytearray are examples of built-in objects that support the
6119 : : buffer protocol.
6120 : : byteorder: unicode(c_default="NULL") = "big"
6121 : : The byte order used to represent the integer. If byteorder is 'big',
6122 : : the most significant byte is at the beginning of the byte array. If
6123 : : byteorder is 'little', the most significant byte is at the end of the
6124 : : byte array. To request the native byte order of the host system, use
6125 : : `sys.byteorder' as the byte order value. Default is to use 'big'.
6126 : : *
6127 : : signed as is_signed: bool = False
6128 : : Indicates whether two's complement is used to represent the integer.
6129 : :
6130 : : Return the integer represented by the given array of bytes.
6131 : : [clinic start generated code]*/
6132 : :
6133 : : static PyObject *
6134 : 1183 : int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
6135 : : PyObject *byteorder, int is_signed)
6136 : : /*[clinic end generated code: output=efc5d68e31f9314f input=33326dccdd655553]*/
6137 : : {
6138 : : int little_endian;
6139 : : PyObject *long_obj, *bytes;
6140 : :
6141 [ - + ]: 1183 : if (byteorder == NULL)
6142 : 0 : little_endian = 0;
6143 [ + - ]: 1183 : else if (_PyUnicode_Equal(byteorder, &_Py_ID(little)))
6144 : 1183 : little_endian = 1;
6145 [ # # ]: 0 : else if (_PyUnicode_Equal(byteorder, &_Py_ID(big)))
6146 : 0 : little_endian = 0;
6147 : : else {
6148 : 0 : PyErr_SetString(PyExc_ValueError,
6149 : : "byteorder must be either 'little' or 'big'");
6150 : 0 : return NULL;
6151 : : }
6152 : :
6153 : 1183 : bytes = PyObject_Bytes(bytes_obj);
6154 [ - + ]: 1183 : if (bytes == NULL)
6155 : 0 : return NULL;
6156 : :
6157 : 1183 : long_obj = _PyLong_FromByteArray(
6158 : 1183 : (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
6159 : : little_endian, is_signed);
6160 : 1183 : Py_DECREF(bytes);
6161 : :
6162 [ + - - + ]: 1183 : if (long_obj != NULL && type != &PyLong_Type) {
6163 : 0 : Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
6164 : : }
6165 : :
6166 : 1183 : return long_obj;
6167 : : }
6168 : :
6169 : : static PyObject *
6170 : 3 : long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
6171 : : {
6172 : 3 : return long_long(self);
6173 : : }
6174 : :
6175 : : /*[clinic input]
6176 : : int.is_integer
6177 : :
6178 : : Returns True. Exists for duck type compatibility with float.is_integer.
6179 : : [clinic start generated code]*/
6180 : :
6181 : : static PyObject *
6182 : 0 : int_is_integer_impl(PyObject *self)
6183 : : /*[clinic end generated code: output=90f8e794ce5430ef input=7e41c4d4416e05f2]*/
6184 : : {
6185 : 0 : Py_RETURN_TRUE;
6186 : : }
6187 : :
6188 : : static PyMethodDef long_methods[] = {
6189 : : {"conjugate", long_long_meth, METH_NOARGS,
6190 : : "Returns self, the complex conjugate of any int."},
6191 : : INT_BIT_LENGTH_METHODDEF
6192 : : INT_BIT_COUNT_METHODDEF
6193 : : INT_TO_BYTES_METHODDEF
6194 : : INT_FROM_BYTES_METHODDEF
6195 : : INT_AS_INTEGER_RATIO_METHODDEF
6196 : : {"__trunc__", long_long_meth, METH_NOARGS,
6197 : : "Truncating an Integral returns itself."},
6198 : : {"__floor__", long_long_meth, METH_NOARGS,
6199 : : "Flooring an Integral returns itself."},
6200 : : {"__ceil__", long_long_meth, METH_NOARGS,
6201 : : "Ceiling of an Integral returns itself."},
6202 : : INT___ROUND___METHODDEF
6203 : : INT___GETNEWARGS___METHODDEF
6204 : : INT___FORMAT___METHODDEF
6205 : : INT___SIZEOF___METHODDEF
6206 : : INT_IS_INTEGER_METHODDEF
6207 : : {NULL, NULL} /* sentinel */
6208 : : };
6209 : :
6210 : : static PyGetSetDef long_getset[] = {
6211 : : {"real",
6212 : : (getter)long_long_meth, (setter)NULL,
6213 : : "the real part of a complex number",
6214 : : NULL},
6215 : : {"imag",
6216 : : long_get0, (setter)NULL,
6217 : : "the imaginary part of a complex number",
6218 : : NULL},
6219 : : {"numerator",
6220 : : (getter)long_long_meth, (setter)NULL,
6221 : : "the numerator of a rational number in lowest terms",
6222 : : NULL},
6223 : : {"denominator",
6224 : : long_get1, (setter)NULL,
6225 : : "the denominator of a rational number in lowest terms",
6226 : : NULL},
6227 : : {NULL} /* Sentinel */
6228 : : };
6229 : :
6230 : : PyDoc_STRVAR(long_doc,
6231 : : "int([x]) -> integer\n\
6232 : : int(x, base=10) -> integer\n\
6233 : : \n\
6234 : : Convert a number or string to an integer, or return 0 if no arguments\n\
6235 : : are given. If x is a number, return x.__int__(). For floating point\n\
6236 : : numbers, this truncates towards zero.\n\
6237 : : \n\
6238 : : If x is not a number or if base is given, then x must be a string,\n\
6239 : : bytes, or bytearray instance representing an integer literal in the\n\
6240 : : given base. The literal can be preceded by '+' or '-' and be surrounded\n\
6241 : : by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
6242 : : Base 0 means to interpret the base from the string as an integer literal.\n\
6243 : : >>> int('0b100', base=0)\n\
6244 : : 4");
6245 : :
6246 : : static PyNumberMethods long_as_number = {
6247 : : (binaryfunc)long_add, /*nb_add*/
6248 : : (binaryfunc)long_sub, /*nb_subtract*/
6249 : : (binaryfunc)long_mul, /*nb_multiply*/
6250 : : long_mod, /*nb_remainder*/
6251 : : long_divmod, /*nb_divmod*/
6252 : : long_pow, /*nb_power*/
6253 : : (unaryfunc)long_neg, /*nb_negative*/
6254 : : long_long, /*tp_positive*/
6255 : : (unaryfunc)long_abs, /*tp_absolute*/
6256 : : (inquiry)long_bool, /*tp_bool*/
6257 : : (unaryfunc)long_invert, /*nb_invert*/
6258 : : long_lshift, /*nb_lshift*/
6259 : : long_rshift, /*nb_rshift*/
6260 : : long_and, /*nb_and*/
6261 : : long_xor, /*nb_xor*/
6262 : : long_or, /*nb_or*/
6263 : : long_long, /*nb_int*/
6264 : : 0, /*nb_reserved*/
6265 : : long_float, /*nb_float*/
6266 : : 0, /* nb_inplace_add */
6267 : : 0, /* nb_inplace_subtract */
6268 : : 0, /* nb_inplace_multiply */
6269 : : 0, /* nb_inplace_remainder */
6270 : : 0, /* nb_inplace_power */
6271 : : 0, /* nb_inplace_lshift */
6272 : : 0, /* nb_inplace_rshift */
6273 : : 0, /* nb_inplace_and */
6274 : : 0, /* nb_inplace_xor */
6275 : : 0, /* nb_inplace_or */
6276 : : long_div, /* nb_floor_divide */
6277 : : long_true_divide, /* nb_true_divide */
6278 : : 0, /* nb_inplace_floor_divide */
6279 : : 0, /* nb_inplace_true_divide */
6280 : : long_long, /* nb_index */
6281 : : };
6282 : :
6283 : : PyTypeObject PyLong_Type = {
6284 : : PyVarObject_HEAD_INIT(&PyType_Type, 0)
6285 : : "int", /* tp_name */
6286 : : offsetof(PyLongObject, long_value.ob_digit), /* tp_basicsize */
6287 : : sizeof(digit), /* tp_itemsize */
6288 : : 0, /* tp_dealloc */
6289 : : 0, /* tp_vectorcall_offset */
6290 : : 0, /* tp_getattr */
6291 : : 0, /* tp_setattr */
6292 : : 0, /* tp_as_async */
6293 : : long_to_decimal_string, /* tp_repr */
6294 : : &long_as_number, /* tp_as_number */
6295 : : 0, /* tp_as_sequence */
6296 : : 0, /* tp_as_mapping */
6297 : : (hashfunc)long_hash, /* tp_hash */
6298 : : 0, /* tp_call */
6299 : : 0, /* tp_str */
6300 : : PyObject_GenericGetAttr, /* tp_getattro */
6301 : : 0, /* tp_setattro */
6302 : : 0, /* tp_as_buffer */
6303 : : Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
6304 : : Py_TPFLAGS_LONG_SUBCLASS |
6305 : : _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
6306 : : long_doc, /* tp_doc */
6307 : : 0, /* tp_traverse */
6308 : : 0, /* tp_clear */
6309 : : long_richcompare, /* tp_richcompare */
6310 : : 0, /* tp_weaklistoffset */
6311 : : 0, /* tp_iter */
6312 : : 0, /* tp_iternext */
6313 : : long_methods, /* tp_methods */
6314 : : 0, /* tp_members */
6315 : : long_getset, /* tp_getset */
6316 : : 0, /* tp_base */
6317 : : 0, /* tp_dict */
6318 : : 0, /* tp_descr_get */
6319 : : 0, /* tp_descr_set */
6320 : : 0, /* tp_dictoffset */
6321 : : 0, /* tp_init */
6322 : : 0, /* tp_alloc */
6323 : : long_new, /* tp_new */
6324 : : PyObject_Free, /* tp_free */
6325 : : };
6326 : :
6327 : : static PyTypeObject Int_InfoType;
6328 : :
6329 : : PyDoc_STRVAR(int_info__doc__,
6330 : : "sys.int_info\n\
6331 : : \n\
6332 : : A named tuple that holds information about Python's\n\
6333 : : internal representation of integers. The attributes are read only.");
6334 : :
6335 : : static PyStructSequence_Field int_info_fields[] = {
6336 : : {"bits_per_digit", "size of a digit in bits"},
6337 : : {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
6338 : : {"default_max_str_digits", "maximum string conversion digits limitation"},
6339 : : {"str_digits_check_threshold", "minimum positive value for int_max_str_digits"},
6340 : : {NULL, NULL}
6341 : : };
6342 : :
6343 : : static PyStructSequence_Desc int_info_desc = {
6344 : : "sys.int_info", /* name */
6345 : : int_info__doc__, /* doc */
6346 : : int_info_fields, /* fields */
6347 : : 4 /* number of fields */
6348 : : };
6349 : :
6350 : : PyObject *
6351 : 29 : PyLong_GetInfo(void)
6352 : : {
6353 : : PyObject* int_info;
6354 : 29 : int field = 0;
6355 : 29 : int_info = PyStructSequence_New(&Int_InfoType);
6356 [ - + ]: 29 : if (int_info == NULL)
6357 : 0 : return NULL;
6358 : 29 : PyStructSequence_SET_ITEM(int_info, field++,
6359 : : PyLong_FromLong(PyLong_SHIFT));
6360 : 29 : PyStructSequence_SET_ITEM(int_info, field++,
6361 : : PyLong_FromLong(sizeof(digit)));
6362 : : /*
6363 : : * The following two fields were added after investigating uses of
6364 : : * sys.int_info in the wild: Exceedingly rarely used. The ONLY use found was
6365 : : * numba using sys.int_info.bits_per_digit as attribute access rather than
6366 : : * sequence unpacking. Cython and sympy also refer to sys.int_info but only
6367 : : * as info for debugging. No concern about adding these in a backport.
6368 : : */
6369 : 29 : PyStructSequence_SET_ITEM(int_info, field++,
6370 : : PyLong_FromLong(_PY_LONG_DEFAULT_MAX_STR_DIGITS));
6371 : 29 : PyStructSequence_SET_ITEM(int_info, field++,
6372 : : PyLong_FromLong(_PY_LONG_MAX_STR_DIGITS_THRESHOLD));
6373 [ - + ]: 29 : if (PyErr_Occurred()) {
6374 [ # # ]: 0 : Py_CLEAR(int_info);
6375 : 0 : return NULL;
6376 : : }
6377 : 29 : return int_info;
6378 : : }
6379 : :
6380 : :
6381 : : /* runtime lifecycle */
6382 : :
6383 : : PyStatus
6384 : 29 : _PyLong_InitTypes(PyInterpreterState *interp)
6385 : : {
6386 [ - + ]: 29 : if (!_Py_IsMainInterpreter(interp)) {
6387 : 0 : return _PyStatus_OK();
6388 : : }
6389 : :
6390 [ - + ]: 29 : if (PyType_Ready(&PyLong_Type) < 0) {
6391 : 0 : return _PyStatus_ERR("Can't initialize int type");
6392 : : }
6393 : :
6394 : : /* initialize int_info */
6395 [ + - ]: 29 : if (Int_InfoType.tp_name == NULL) {
6396 [ - + ]: 29 : if (_PyStructSequence_InitBuiltin(&Int_InfoType, &int_info_desc) < 0) {
6397 : 0 : return _PyStatus_ERR("can't init int info type");
6398 : : }
6399 : : }
6400 : :
6401 : 29 : return _PyStatus_OK();
6402 : : }
6403 : :
6404 : :
6405 : : void
6406 : 25 : _PyLong_FiniTypes(PyInterpreterState *interp)
6407 : : {
6408 [ - + ]: 25 : if (!_Py_IsMainInterpreter(interp)) {
6409 : 0 : return;
6410 : : }
6411 : :
6412 : 25 : _PyStructSequence_FiniType(&Int_InfoType);
6413 : : }
|